# Parsing

> Reference for the exports in @recipe-book/core that turn recipe input into a recipe, a quantity, or an ingredient line, and report the issues they find.

Source: https://recipe-book.siraj.page/reference/core/parsing/

Use these exports to turn recipe input from any source into a [`Recipe`](https://recipe-book.siraj.page/reference/core/types.md#recipe), a [`Quantity`](https://recipe-book.siraj.page/reference/core/units.md#quantity), or an [`IngredientLine`](https://recipe-book.siraj.page/reference/core/types.md#ingredientline). None of them throws for bad input. Each reports the issues it finds, with a path to each one. In a React app, replace `@recipe-book/core` with `@recipe-book/react/core` in this page's imports.

## `parseRecipe`

```ts
function parseRecipe(input: unknown): ParseResult<Recipe>
function parseRecipe(
  input: unknown,
  options?: ParseRecipeOptions,
): ParseResult<Recipe>
```

Validates recipe input and normalizes it into a [`Recipe`](https://recipe-book.siraj.page/reference/core/types.md#recipe).

| Name      | Type                              | Default  | Description                                                                                                                                       |
| --------- | --------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `input`   | `unknown`                         | Required | The recipe input, usually a [`RecipeInput`](https://recipe-book.siraj.page/reference/core/types.md#recipeinput) or parsed JSON. It needs no cast. |
| `options` | `ParseRecipeOptions \| undefined` | None     | How to read the input. It's ignored when it's a number or another value that isn't an object, so `rows.map(parseRecipe)` works; a string throws.  |

`options` has the type `ParseRecipeOptions`, which core exports. It takes the two [`ParseQuantityOptions`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantityoptions) fields, which apply only to text: `decimal` to every amount written as text, and `units` to the units in quantity text, such as an ingredient's `quantity` and `equivalents`. It also takes this field.

| Name                  | Type                                                                                          | Description                                                                                                                                                                                                                                                                                                                      |
| --------------------- | --------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `parseIngredientLine` | `((text: string, options: ParseQuantityOptions) => ParseResult<IngredientLine>) \| undefined` | Reads ingredients written as text. Pass [`parseIngredientLine`](https://recipe-book.siraj.page/reference/core/parsing.md#parseingredientline), or a function that calls it. It's called with each line and the `decimal` and `units` this parse reads with, so a function of your own can pass them on to `parseIngredientLine`. |

Returns a [`ParseResult<Recipe>`](https://recipe-book.siraj.page/reference/core/parsing.md#parseresult).

The recipe is normalized, so code that reads it handles one shape:

- Unit aliases become unit IDs: `'cups'` becomes `'cup'`, and `'T'` becomes `'tbsp'`.
- Quantity text becomes a [`Quantity`](https://recipe-book.siraj.page/reference/core/units.md#quantity), and ISO 8601 durations become minutes. A duration with years or months other than zero, such as `'P30M'`, is an [`invalid_duration`](https://recipe-book.siraj.page/errors.md#issue-invalid_duration) error.
- Servings and yield become a [`Servings`](https://recipe-book.siraj.page/reference/core/types.md#servings) and a [`Yield`](https://recipe-book.siraj.page/reference/core/types.md#yield), with a range's upper end in `max`: `servings: 4` becomes `{ amount: 4 }`, `servings: '4–6'` becomes `{ amount: 4, max: 6 }`, and `yield: '24 cookies'` becomes `{ amount: 24, unit: 'cookie', plural: 'cookies' }`. Yield text gets a `plural` the way a [bare count](https://recipe-book.siraj.page/reference/core/parsing.md#parseingredientline) does, so `'8 slices of bread'` becomes `{ amount: 8, unit: 'slice of bread', plural: 'slices of bread' }`. [`YieldInput`](https://recipe-book.siraj.page/reference/core/types.md#yieldinput) has every rule.
- Nutrient text becomes a number in the nutrient's unit, as [`NutritionInput`](https://recipe-book.siraj.page/reference/core/types.md#nutritioninput) describes. Nutrition with no values is left out.
- `ingredients` and `steps` are lists of sections. Each run of loose items becomes an untitled section.
- The recipe and every section, ingredient, step, note, piece of equipment, and custom time have an `id`, authored or derived from a name, title, or label. A derived ID is that text in lowercase, with characters such as `½` and `ﬁ` spelled out, accents dropped from Latin letters, marks in other scripts, such as Devanagari vowel signs, kept with their letters, and each run of characters other than letters and digits turned into one `-`, with none at either end, so `'Crème fraîche!'` gives `creme-fraiche`, `'हरी मिर्च'` gives `हरी-मिर्च`, and `'½ lemon'` gives `1-2-lemon`. Repeated names get a suffix among items of one kind, such as the ingredients or the step sections, so two ingredients named `egg` get `egg` and `egg-2`, even in different sections, but a note titled `Egg` gets `egg` too. Authored IDs are claimed first, so a derived ID that matches one of the same kind gets a suffix instead, even on an earlier item. When a name, title, or label has no letters or digits in its NFKD form, the ID is `recipe`, `ingredient`, `equipment`, or `time`, with `-2` and so on added after the first, as for other repeated IDs, and a section, step, or note gets the ID it would have without a title or name. An untitled section uses `ingredients` or `steps`, an unnamed step uses its number, counted across sections, and an untitled note uses its position, each with `-2` and so on added as for other repeated IDs, so the steps `'Mix.'`, `{ name: 'Fold', text: 'Fold in the egg.' }`, and `'Bake.'` get `step-1`, `fold`, and `step-3`.
- A string in `steps`, `notes`, or `equipment` becomes an object: a step or note with only `text`, or equipment with only a `name`.
- Text is trimmed, and empty optional text is left out.
- `times`, `times.custom`, `notes`, `equipment`, `equivalents`, and `optional` are always present.
- `system` is the authored measurement system. Otherwise it's inferred from each ingredient's `quantity`, ignoring equivalents: the system with more quantities in metric-only or US-only units wins, and on a tie the first such quantity decides. It's absent when no `quantity` has a metric-only or US-only unit.

```ts
import { parseRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Toast',
  ingredients: [{ name: 'bread', quantity: '2 slices' }],
  steps: ['Toast the bread.'],
})
```

result.data
```json title="result.data"
{
  "id": "toast",
  "name": "Toast",
  "times": {
    "custom": []
  },
  "ingredients": [
    {
      "id": "ingredients",
      "items": [
        {
          "id": "bread",
          "name": "bread",
          "quantity": {
            "amount": 2,
            "unit": "slice"
          },
          "equivalents": [],
          "optional": false
        }
      ]
    }
  ],
  "steps": [
    {
      "id": "steps",
      "items": [
        {
          "id": "step-1",
          "text": "Toast the bread."
        }
      ]
    }
  ],
  "notes": [],
  "equipment": []
}
```

A link or image URL that [Types](https://recipe-book.siraj.page/reference/core/types.md) doesn't allow, such as a `javascript:` URL or `'http://[bad'`, is an [`invalid_url`](https://recipe-book.siraj.page/errors.md#issue-invalid_url) error.

To put ingredient lines in recipe input, pass `{ parseIngredientLine }`, as in [Author recipes](https://recipe-book.siraj.page/guides/author-recipes.md#write-ingredients-as-text):

```ts {8}
import { parseIngredientLine, parseRecipe } from '@recipe-book/core'

const input = {
  name: 'Toast',
  ingredients: ['2 slices bread', '1 tbsp butter, softened'],
  steps: ['Toast the bread.'],
}
const result = parseRecipe(input, { parseIngredientLine })

result.success && result.data.ingredients[0]?.items[1] // { id: 'butter', name: 'butter', quantity: { amount: 1, unit: 'tbsp' }, equivalents: [], note: 'softened', optional: false }

const without = parseRecipe(input)
```

Without it, each line is an [`invalid_type`](https://recipe-book.siraj.page/errors.md#issue-invalid_type) error whose message names the option, so recipes written as objects don't load the line parser:

without.error.message
```txt title="without.error.message"
"Toast" has 2 problems:
  ✖ ingredients[0]  Expected an ingredient such as { name: "flour", quantity: "2 cups" }, received "2 slices bread". To read ingredient lines, pass parseIngredientLine: parseRecipe(input, { parseIngredientLine }).
  ✖ ingredients[1]  Expected an ingredient such as { name: "flour", quantity: "2 cups" }, received "1 tbsp butter, softened". To read ingredient lines, pass parseIngredientLine: parseRecipe(input, { parseIngredientLine }).
See https://recipe-book.siraj.page/errors/invalid_recipe/
```

`parseRecipe` keeps each ingredient line and step as written. A line such as `'For the glaze:'` is an ingredient named "For the glaze:", not a section's title, and a step such as `'1. Heat the oven.'` keeps its number, and a line that's only a label, such as `'Step 2'`, is a step. To read a recipe pasted as text, pass its lines to [`fromJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#fromjsonld) instead, as in [Read a pasted recipe](https://recipe-book.siraj.page/guides/import-recipes.md#read-a-pasted-recipe).

Doesn't throw for bad input. It returns a [`RecipeValidationError`](https://recipe-book.siraj.page/reference/core/errors.md#recipevalidationerror) with the code [`invalid_recipe`](https://recipe-book.siraj.page/errors/invalid_recipe.md), whose issues each have one of the [issue codes](https://recipe-book.siraj.page/errors.md#issue-codes). An error thrown by a getter or a proxy in the input or options passes through, and so does an error thrown by a `parseIngredientLine` of your own. When yours returns something other than a parse result, `parseRecipe` can throw a `TypeError`. It throws a [`RecipeBookError`](https://recipe-book.siraj.page/reference/core/errors.md#recipebookerror) with the code [`invalid_argument`](https://recipe-book.siraj.page/errors/invalid_argument.md) when `options` is a string, when `options.decimal` or `options.units` isn't valid, as for [`parseQuantity`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantity), or when `options.parseIngredientLine` is present but isn't a function.

[Author recipes](https://recipe-book.siraj.page/guides/author-recipes.md) uses it to parse the recipe input it writes.

## `parseQuantity`

```ts
function parseQuantity(text: string): ParseResult<Quantity>
function parseQuantity(
  text: string,
  options?: ParseQuantityOptions,
): ParseResult<Quantity>
```

Parses quantity text, such as `'1 ½ cups'` or `'2-3 tbsp'`, into a [`Quantity`](https://recipe-book.siraj.page/reference/core/units.md#quantity).

| Name      | Type                                                                                                    | Default  | Description                                                                                                                                                                       |
| --------- | ------------------------------------------------------------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `text`    | `string`                                                                                                | Required | An amount followed by an optional unit alias. Extra whitespace is ignored.                                                                                                        |
| `options` | [`ParseQuantityOptions`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantityoptions) | `{}`     | The decimal mark and the cup and tablespoon to read. It's ignored when it's a number or another value that isn't an object, so `texts.map(parseQuantity)` works; a string throws. |

The text is made of these parts:

| Part    | Accepted forms                                                                                                                                                                                           |
| ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Amount  | Integers (`3`), decimals (`1.5`, `.5`, `0,5`), fractions (`1/2`, `½`, also with the fraction slash `⁄`), and mixed numbers (`1 1/2`, `1½`, `1 ½`), all above 0                                           |
| Range   | Two amounts joined by `-`, `–`, `—`, or `to` (`2-3`, `2 to 3`)                                                                                                                                           |
| Article | `a` or `an` for 1 before a unit alias (`a pinch`)                                                                                                                                                        |
| Unit    | Any [unit alias](https://recipe-book.siraj.page/reference/core/units.md#unitalias), with or without a space (`250 g`, `250g`), and with an optional period at the end of a word (`2 tbsp.`, `2 fl. oz.`) |

A range with equal ends becomes a number. Aliases match in any case, except `T` for tbsp, `t` for tsp, and `c` for cup, so `'180 C'` is an unknown unit.

A period or a comma between digits is a decimal mark, so `'0,5 l'` and `'2.5 kg'` read with no options. The exception is a number such as `'1,500'` or `'1.500'`, with one to three digits before its mark, the first not 0, and exactly three after, because its mark could also separate thousands. It reads as a decimal when its mark is `options.decimal`, a period by default, and is an issue with the other mark. A number with two or more marks, such as `'1.500,5'`, is an issue too, because thousands separators aren't read. The [edge cases](https://recipe-book.siraj.page/reference/core/parsing.md#edge-cases) under `ParseQuantityOptions` show what each `decimal` value reads.

Returns a [`ParseResult<Quantity>`](https://recipe-book.siraj.page/reference/core/parsing.md#parseresult). `warnings` is always empty.

```ts
import { parseQuantity } from '@recipe-book/core'

parseQuantity('1 ½ cups') // { success: true, data: { amount: 1.5, unit: 'cup' }, warnings: [] }
parseQuantity('2-3 tbsp') // { success: true, data: { amount: { min: 2, max: 3 }, unit: 'tbsp' }, warnings: [] }
parseQuantity('a pinch') // { success: true, data: { amount: 1, unit: 'pinch' }, warnings: [] }
parseQuantity('3') // { success: true, data: { amount: 3 }, warnings: [] }
parseQuantity('0,5 l') // { success: true, data: { amount: 0.5, unit: 'l' }, warnings: [] }
```

Doesn't throw for text. For text it can't read, it returns a [`RecipeValidationError`](https://recipe-book.siraj.page/reference/core/errors.md#recipevalidationerror) with the code [`invalid_quantity`](https://recipe-book.siraj.page/errors/invalid_quantity.md) and one issue, whose path is empty. An error thrown by a getter or a proxy in the options passes through. It throws a [`RecipeBookError`](https://recipe-book.siraj.page/reference/core/errors.md#recipebookerror) with the code [`invalid_argument`](https://recipe-book.siraj.page/errors/invalid_argument.md) when `options` is a string, when `options.units` isn't an object or has a key other than `cup` and `tbsp`, or when `options.decimal` or an entry of `options.units` isn't one of its values.

## `parseIngredientLine`

```ts
function parseIngredientLine(text: string): ParseResult<IngredientLine>
function parseIngredientLine(
  text: string,
  options?: ParseQuantityOptions,
): ParseResult<IngredientLine>
```

Reads an ingredient line, such as `'1 ½ cups (190 g) flour, sifted'`, into an [`IngredientLine`](https://recipe-book.siraj.page/reference/core/types.md#ingredientline).

| Name      | Type                                                                                                    | Default  | Description                                                                                                                                                                                                      |
| --------- | ------------------------------------------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `text`    | `string`                                                                                                | Required | One ingredient line. Extra whitespace is ignored.                                                                                                                                                                |
| `options` | [`ParseQuantityOptions`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantityoptions) | `{}`     | The decimal mark and the cup and tablespoon to read the line's measures with. It's ignored when it's a number or another value that isn't an object, so `lines.map(parseIngredientLine)` works; a string throws. |

A leading `- ` list marker or `▢` checkbox is left out when the rest reads as an ingredient.

The line is made of these parts, all optional except the name:

| Part           | Accepted forms                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    | Read into                                                                              |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| Amount         | Any amount or range that [`parseQuantity`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantity) reads, `a` or `an` for 1 before a name too (`an onion`), but not when it starts a phrase from the Note row (`a few eggs`, `a lot of cheese`), a whole number from 1 joined by a dash to a fraction below 1, as a mixed number, at the start of a measure (`1-1/2 cups flour`, `1-½ cups flour`, and `1–1/2 cups flour` are 1 ½ cups, `1-½ to 2 cups flour` is 1 ½–2 cups, and `200 g/1-½ cups flour` is 200 g, then 1 ½ cups, but not `1 to 1-½ cups flour`), the words `one` to `twelve`, and a hyphen, en dash, or em dash followed by a space as a separator between an amount in numerals and a word or parentheses (`1 14- ounce can milk` is 1 can, then 14 oz, and `2 - eggs` and `2 – eggs` read like `2 eggs`, and `4— (8-ounce) ramekins` like `4 (8-ounce) ramekins`), or between a unit and a word, with a space on both sides, or between a second measure in parentheses and a word, with a space after it, but never before a numeral (`2 cups - flour` reads like `2 cups flour`, `2 Tbsp (40ml) - olive oil` and `2 Tbsp (40ml)- olive oil` like `2 Tbsp (40ml) olive oil`, and `1 cup - two cups broth` like `1 cup two cups broth`, but `1 cup - 1 ½ cups broth` keeps the whole line as the name)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          | `quantity`                                                                             |
| Unit           | Any [unit alias](https://recipe-book.siraj.page/reference/core/units.md#unitalias), including after a dash (`3-pound chicken`) and before `of`, or before a lowercase `de`, `di`, or `d'` (`a pinch of salt`, `2 tsp de sel`). With no amount, a unit before one of those reads as 1 when it starts the line, after any leading `optional` or `(optional)` and up to one comma, semicolon, colon, period, hyphen (`-`), en dash (`–`), or em dash (`—`) after it, and after any size word or `packed`, `lightly packed`, or `firmly packed` (`tsp. of salt`, `fl oz of water`, `Optional - pinch of salt`, `big pinch of salt` with the note `big`, and `packed cup of sugar` with the note `packed`)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | `quantity`                                                                             |
| Second measure | In parentheses that hold nothing but measures or start with them before a comma and a space (`1 can (15 oz, drained) beans`, but not `1 can (15 oz,drained) beans`), each measure up to the first item after a comma and a space that isn't one (`1 can (15 oz, 425 g, drained) beans` gets 15 oz and 425 g), including in parentheses inside them, which come after the outer ones, after `/`, `;`, or a space (`1 cup/240 ml milk`, `500 ml 2 cups milk`), a size before `can`, `package`, `jar`, `bag`, or `stick`, or after a count unit (`1 15-ounce can beans`, `1 can 15 oz beans`; with no count, `400 g can tomatoes` is 1 can, then 400 g, but a range size isn't read that way, as in `14-15 oz can tomatoes`), or a pack size, read as the total (`2 x 400 g tomatoes` is `800 g`, and `2 (15 oz (425 g)) cans beans` is 30 oz and 850 g). After a count unit, measures in parentheses with `each` at the end are for each one, and with `total` at the end they're the total (`3 cloves (15 g each) garlic` is 45 g). Without either, they're for each one after `can`, `package`, `jar`, or `bag` (`2 cans (15 oz) beans` is 30 oz) and the total after any other count unit (`2 sticks (1 cup) butter` is 1 cup). After a weight size, a weight alone in parentheses right before or after `can`, `package`, `jar`, `bag`, or `stick` counts as each one's weight when it's within 5% of the size (`2 8-ounce (227 g) packages cream cheese` and `2 8-ounce packages (227 g) cream cheese` are 2 packages, then 16 oz and 454 g), and otherwise it's the total (`Three 8-ounce (680 g) packages cream cheese` is 3 packages, then 24 oz and 680 g). One in the same [dimension](https://recipe-book.siraj.page/reference/core/units.md#dimension), mass or volume, after `plus`, `and`, or `+`, or straight after the first in the same system (tsp and tbsp count as US), is added to it instead (`1 lb 2 oz flour` is 1.125 lb), including in a size after a leading count (`2 1 lb 2 oz cans tomatoes` is 2 cans, then 2.25 lb). After the leading measure, a third is added to the second the same way, then both to the first (`1 gallon 1 quart 1 cup water` is 1.3125 gallons), but a fourth isn't (`1 cup plus 2 tbsp plus 2 tsp plus 1 tsp flour` gets the name `plus 1 tsp flour`). The sum stays in the first unit when [`formatQuantity`](https://recipe-book.siraj.page/reference/core/formatting.md#formatquantity) writes it in that unit within 5% of the sum, and is otherwise in the smaller unit, so `⅓ cup + 1½ tbsp milk` is 6 ⅚ tbsp, not 0.43 cup, which would print as ⅜ cup. Outside parentheses, a measure after the leading one that's followed by `plus`, `and`, or `+` and anything it can't add is read alone, and the connector starts the name (`1 cup/240 ml plus salt` and `1 cup 240 ml and salt` are 1 cup, then 240 ml), except a size after a count unit, which is part of the name with them (`1 can 15 oz + salt` is 1 can, with the name `15 oz + salt`). In parentheses, any other sum (across dimensions, in count units such as `pinch`, or of three measures) makes every measure in them part of the note (`1 cup (8 oz + 1 tbsp) milk`). With no leading amount or unit, the first measure in such parentheses is the `quantity` instead (`Butter (100g)`). Measures after a leading `optional` in parentheses, or beside it as its own comma-separated item, are read the same way | `equivalents`, or `quantity` when added or when the line has no leading amount or unit |
| Name           | The rest of the line, up to the first comma outside parentheses that doesn't follow `boneless` or `skinless` (one that does still ends the name before a preparation word from the Note row's dash list, as in `1 lb chicken breast boneless, cubed`) and isn't between two digits, where it's part of a number with either decimal mark (`1 Flasche Wein 0,75 l` gets the name `Flasche Wein 0,75 l`, and `1 bag sugar 1,500 g` gets `sugar 1,500 g`), stopping before preparation words from the Note row that end it, such as `chopped` or `melted`, without text in parentheses, and without `of`, `of a`, `of an`, or `of the` right after the quantity, as in `½ of an onion`, or a lowercase `de` or `di`, or `d'` or `d’` joined to the next word, as in `500 g de carottes` and `800 g d'oignons jaunes`. A capitalized `De`, `Di`, or `D'` stays in the name, as the brand in `1 lb De Cecco spaghetti` does. With no leading amount or unit, an amount and unit after the name and a colon, or a hyphen (`-`), en dash (`–`), or em dash (`—`) with a space on both sides, are read when nothing else follows but a note after a comma, and the name is the text before the delimiter (`nagaimo: 160 g, grated` and `Beurre doux : 120 g` read). `Cajun seasoning - 2 tbsp` reads, `Breadcrumbs – 60g` reads, and `salt-free seasoning — 2 tsp` reads. A dash without both spaces isn't a delimiter (`Cajun seasoning- 2 tbsp` and `Breadcrumbs –60g` keep the whole line as the name). Neither is the delimiter read when the text has an ASCII digit from 0 to 9, starts with the word `for`, `to`, `a`, `an`, `yield`, `yields`, or `total`, or is only `makes`, `serves`, `serving`, `servings`, `serving size`, `protein`, `carbs`, `carbohydrate`, `carbohydrates`, `fiber`, `fibre`, `sodium`, `cholesterol`, `saturated fat`, or `fat` (`For the sauce: 1 cup`, `For the sauce - 1 cup`, `Protein: 12 g`, and `Protein – 12 g` keep the whole line as the name, but `Protein powder: 30 g` reads)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              | `name`, and `plural` after a bare count                                                |
| Note           | The text after that comma, text in parentheses before it that isn't a measure or `optional`, `about`, `approx`, `approx.`, `approximately`, or `~` before the amount, including before the words `one` to `twelve` (`about two cups flour` is 2 cups, with the name `flour` and note `about`; `~2 cups flour` is 2 cups, with the note `~`), or before measures in parentheses, which read as if it weren't there (`4 carrots, chopped (about 2 cups)` is 4, then 2 cups, with the note `chopped (about)`), a size word (`heaping`, `heaped`, `level`, `scant`, `rounded`, `generous`, `good`, `small`, `medium`, `large`, `big`, `tiny`, `thin`, or `thick`) or `packed`, `lightly packed`, or `firmly packed` between the amount and the unit (`1 heaping tbsp sugar`, `4 packed cups strawberries`), phrases such as "to taste" or "a splash of", a label after a leading `optional`, and preparation words at the end of the name, after any text in parentheses: `chopped`, `minced`, `diced`, `sliced`, `grated`, `shredded`, `melted`, `softened`, `crushed`, `juiced`, `zested`, `peeled`, `seeded`, `quartered`, `trimmed`, `drained`, `rinsed`, `sifted`, `packed`, `divided`, `room temperature`, or `at room temperature`, each after any `finely` or `thinly`, and up to three joined by `and` (`1 onion finely chopped`, `2 tomatoes seeded and chopped`). They stay in the name when they're all of it (`1 cup chopped`), or follow a dash (`4 eggs - room temperature`), `and`, `or`, `and/or`, `to`, `then`, `very`, `well`, `not`, `&`, `+`, `/`, a word ending in `ly`, or `thin`, `fine`, `fresh`, `rough`, `light`, or `coarse` (`1 onion halved and thinly sliced`, `1 onion roughly chopped`, `1 cup flour not sifted`, `1 lb flank steak thin sliced`). A comma, semicolon, or colon right before them stays out of the name (`1 lb chicken thighs boneless, diced` gets the name `chicken thighs boneless`). In a line with a quantity outside parentheses, though, each spaced hyphen, en dash, or em dash before a preparation word reads as a comma does, even after `boneless` or `skinless`: one of those words other than `room temperature` and `at room temperature`, or `cooked`, `thawed`, `cubed`, or `cut`, each after any `finely` or `thinly` (`4 potatoes - peeled and cubed` is 4, with the name `potato` and note `peeled and cubed`, `2 tomatoes - seeded – chopped` gets the note `seeded, chopped`, and `1 lb chicken breast boneless - cubed` gets the name `chicken breast boneless` and note `cubed`). A plural ending in parentheses right after a word, as in `cup(s)` or `pinch(es)`, is dropped rather than read as a note. A leading phrase such as "a splash of", or `about`, `approx`, `approx.`, or `approximately` before the amount, is lowercased in the note (`Splash of red wine vinegar` gets `splash`, and `A drizzle of honey` gets `a drizzle`), but a unit after the phrase keeps its case (`A couple T of butter` gets `a couple T`)                                                                                                                                                                                                                                                                                                                                                                                                                                           | `note`                                                                                 |
| Optional       | `optional` or `(optional)` at the start of the line, with or without one comma, semicolon, colon, period, hyphen (`-`), en dash (`–`), or em dash (`—`) after it (`Optional - 2 cups flour`), `optional` at the start of text in parentheses, or as its own comma-separated item, alone or before text in parentheses (`1 tsp chipotle paste, optional (more if you want it spicier)`), after the first comma or in parentheses. After a leading optional mark, the rest is read as if it were the whole line, unless it starts with a label. A label there of up to three words with no combining marks, such as an accent in decomposed (NFD) form, followed by a colon, is a note instead, ahead of any other, when what follows it begins with a quantity (after any `about`) or a phrase such as `splash of`. When what follows the label is an amount or range in numerals, or `a` or `an`, and a unit, and then nothing, only text in parentheses, only preparation words from the Note row, or a comma, the label is the name (`Optional Butter: 2 tbsp (melted)` has the name `Butter` and note `melted`). A spaced hyphen, en dash, or em dash and a word after the unit start the note, as a comma does (`Optional Butter: 2 tbsp - room temperature` has the name `Butter` and note `room temperature`, and `Optional Butter: 2 tbsp - for greasing` has the name `Butter` and note `for greasing`). When a second colon puts such a quantity after a name, with nothing after it but a note after a comma, the label stays a note (`Optional Glaze: brown sugar: 2 cups` has the name `brown sugar` and note `Glaze`). It's also the name when it would be one without `optional`, so `Optional salt: 1 g` has `name: 'salt'`. When the label is neither a note nor the name in these ways, the rest is read as it would be on its own, with `optional: true` (`Optional Butter: 1 lb 2 oz` has the name `Butter: 1 lb 2 oz`, and `Optional Butter: 2 tbsp - 1 tbsp` has the name `Butter: 2 tbsp - 1 tbsp`)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         | `optional: true`                                                                       |

Parentheses around nothing, or nothing but more parentheses, are left out of the name, however deep they nest, so `'2 eggs (())'` gets the name `egg` and `'1 cup () flour'` gets `flour`. When parentheses before the first comma nest more than two deep, the outer levels stay in the name with their own text, if they have any. So `'2 onions (diced (fine (very)))'` gets the name `onions (diced)` and the note `fine (very)`, `'2 cups water ((for the rice (or stock)))'` gets the name `water`, and `'1 cup ((((sifted)))) flour'` gets `flour` and the note `sifted`.

A unit and `of`, or a lowercase `de`, `di`, or `d'`, after a phrase from the Note row go into the note with it, without a quantity, so `'few sprigs of thyme'` gets the name `thyme` and the note `few sprigs`, and `'few sprigs de thym'` the name `thym` and the same note.

A size of one number, such as `9`, `9.5`, or `9½`, written with "inch" or "inches" right after the amount is part of the name, with or without a dash, so `'1 9-inch pie crust'`, `'1 9 inch pie crust'`, and `'1 9½ inch tart shell'` are 1, with the names `9-inch pie crust`, `9 inch pie crust`, and `9½ inch tart shell`. A size of a number and a separate fraction, as in `'1 9 ½ inch tart shell'` or `'1 9 1/2 inch tart shell'`, or of a number such as `9` or `9.5` with "in" after a space, as in `'1 9 in pie crust'`, is an [`invalid_quantity`](https://recipe-book.siraj.page/errors.md#issue-invalid_quantity) warning, and the whole line is the name.

With no leading amount or unit, an amount after `of` or `from` stays in the name, so `'Juice of 1 lime'` and `'Zest from 2 lemons'` have no quantity and don't scale, but `'1 lime, juiced'` is 1, with the name `lime` and the note `juiced`.

The cup alias `c`, with or without its period, isn't a unit before the word `à`, before `a` and one of the words `soupe`, `cafe`, `café`, `the`, `thé`, or `table`, or before `de` and one of the words `sopa`, `cha`, or `chá`, in any case, because French and Portuguese write the tablespoon and teaspoon that way. So `'1 c. à soupe de sucre'`, `'2 c a cafe de sel'`, and `'3 c. de sopa polpa de tomate'` are bare counts named from the `c` on, not cups. A longer word beginning with one of those doesn't count, so `'1 c. a tablet'` and `'1 c a cafeteria'` are still cups.

A bare count gets a `plural` from the word before `of`, a leading container such as `boxes`, or else the last word. After a count above 1, a range, or a decimal below 1, that word is made singular in the name. So `'2 large eggs'` scales to "1 large egg", `'2 boxes of crackers'` gets the name `box of crackers`, and so does `'0.2 boxes of crackers'`. After a decimal below 1, a word with no plural ending is read as singular instead, so `'0.5 onion'` gets the plural `onions`. There's no `plural` when that word gets no other form, as when it ends in parentheses (`'2 onions (diced (fine (very)))'`), has no plural ending after a count above 1 or a range (`'2 broccoli'`), ends in `s` after 1 or a fraction below 1 (`'1 eggs'`, `'½ onions'`) but not in `ss` after a letter other than `e` or `u` (`'1 glass'` gets `glasses`), has four or more letters and ends in `ed` but not `eed`, as `chopped` does but `bed` and `seed` don't (`'1 onion roughly chopped'`), or is `children`, `mice`, `dozen`, the symbol of [a unit Recipe Book knows](https://recipe-book.siraj.page/reference/core/units.md#units) that's the same in the plural, such as `L`, `kg`, `tbsp`, or `fl oz`, the abbreviations `T`, `t`, `tb`, `tl`, `el`, `fl-oz`, `tbsp-au`, and `c` (but not `C`), or one of these nouns that are the same in the plural: `sheep`, `deer`, `moose`, `fish`, `shrimp`, `squid`, `salmon`, `trout`, `bass`, or `anise` (`'1 mice'`, `'1 chicken 1.5 kg'`, `'1 whole fish'`). Another symbol or noun can still get a plural, so `'1 chicken 1.5 cm'` gets `chicken 1.5 cms` and `'1 whole cod'` gets `whole cods`. Without one, the name reads the same at any count. A count before a word joined by a dash, as in `'2 9-inch pie crusts'`, stays part of the name. A [count unit](https://recipe-book.siraj.page/reference/core/units.md#dimension) with no name after it, as in `'2 slices'`, becomes the name, with a bare count.

That word is made singular by how it ends, in any case, and so is the `unit` of a [yield](https://recipe-book.siraj.page/reference/core/types.md#yieldinput) written as text:

- A plural ending in `leaves`, `halves`, or `loaves` ends in `f`, so `leaves` reads as "leaf". Another plural ending in `ves` only drops its `s`, so `knives` reads as "knive".
- A plural ending in `ries` or `vies` reads as `-y`, so `berries` and `gravies` read as "berry" and "gravy".
- A plural ending in `lies` after a consonant, `i`, `u`, or `y` reads as `-ly`, except `chilies`, `chillies`, `ollies`, and one ending in `collies`. `jellies`, `bellies`, `lilies`, and `follies` read as "jelly", "belly", "lily", and "folly", and `chilies`, `chillies`, `collies`, `goalies`, `wheelies`, `coolies`, and `lies` read as "chili", "chilli", "collie", "goalie", "wheelie", "coolie", and "lie".
- A plural ending in `ties` or `dies` after a letter reads as `-ty` or `-dy`, except one ending in `cuties`, `oodies`, or `irdies`. `duties`, `beauties`, `bodies`, `melodies`, and `jeopardies` read as "duty", "beauty", "body", "melody", and "jeopardy", and `ties`, `dies`, `cuties`, `goodies`, `hoodies`, `foodies`, and `birdies` read as "tie", "die", "cutie", "goodie", "hoodie", "foodie", and "birdie".
- Another plural ending in `ies` only drops its `s`, so `cookies` reads as "cookie".
- A plural ending in `ches`, `shes`, `xes`, `oes`, `sses`, `tzes`, or `zzes` drops "es", so `peaches`, `dishes`, `boxes`, `tomatoes`, `glasses`, `blintzes`, and `fizzes` read as "peach", "dish", "box", "tomato", "glass", "blintz", and "fizz", and `quizzes` reads as "quizz". Three kinds keep their "e" and drop only the `s`:
  - One ending in `aches`, `iches`, or `oches` after a letter other than `e`, `o`, `r`, or `w`, except `spinaches`. `quiches`, `brioches`, `ganaches`, `caches`, `ceviches`, and `niches` read as "quiche", "brioche", "ganache", "cache", "ceviche", and "niche", and `spinaches`, `coaches`, and `sandwiches` read as "spinach", "coach", and "sandwich".
  - One ending in `ousses`, so `mousses` reads as "mousse", and `busses` and `fusses` read as "buss" and "fuss".
  - One ending in `ezzes`, so `mezzes` reads as "mezze".
- Another word ending in `s`, but not in `ss` or `us`, drops its `s`, so `sizes` reads as "size". A word that ends any other way has no plural ending, as `broccoli` and `asparagus` don't.

A name, or a yield's text, that `toUpperCase()` leaves unchanged gets its other form in capitals, so `'1 ONION'` gets the plural `ONIONS`, `'1 BOX OF CRACKERS'` gets `BOXES OF CRACKERS`, `'1 TV'` gets `TVS`, and the yield `'2 LOAVES'` gets the unit `LOAF`. Otherwise the ending is lowercase, so `'1 vitamin C'` gets `vitamin Cs`.

A few words that end in "-lie" read back wrong, such as `charlies` and `ghillies` as "charly" and "ghilly", and `pasties` reads as "pasty", though it's also the plural of "pastie". To keep the right singular, give such an ingredient as an object, as in `{ name: 'ghillie', plural: 'ghillies', quantity: '2' }`, and such a yield as an object with a `plural`, as in `{ amount: 2, unit: 'charlie', plural: 'charlies' }`. A name or unit given in an object isn't made singular.

Returns a [`ParseResult<IngredientLine>`](https://recipe-book.siraj.page/reference/core/parsing.md#parseresult). Fields the line doesn't have are left out.

```ts
import { parseIngredientLine } from '@recipe-book/core'

parseIngredientLine('1 ½ cups (190 g) flour, sifted') // { success: true, data: { name: 'flour', quantity: { amount: 1.5, unit: 'cup' }, equivalents: [{ amount: 190, unit: 'g' }], note: 'sifted' }, warnings: [] }
parseIngredientLine('2 large eggs') // { success: true, data: { name: 'large egg', plural: 'large eggs', quantity: { amount: 2 } }, warnings: [] }
parseIngredientLine('salt, to taste') // { success: true, data: { name: 'salt', note: 'to taste' }, warnings: [] }
parseIngredientLine('2 tomatoes (peeled, seeded), diced') // { success: true, data: { name: 'tomato', plural: 'tomatoes', quantity: { amount: 2 }, note: 'peeled, seeded, diced' }, warnings: [] }
parseIngredientLine('optional: 1 tbsp honey') // { success: true, data: { name: 'honey', quantity: { amount: 1, unit: 'tbsp' }, optional: true }, warnings: [] }
parseIngredientLine('2 cups flour', { units: { cup: 'cup-metric' } }) // { success: true, data: { name: 'flour', quantity: { amount: 2, unit: 'cup-metric' } }, warnings: [] }
parseIngredientLine('2 cupz flour') // { success: true, data: { name: 'cupz flour', quantity: { amount: 2 } }, warnings: [{ code: 'unknown_unit', severity: 'warning', path: [], message: `"cupz" isn't a unit, so it's read as part of the name. Did you mean "cups"?`, suggestion: 'cups' }] }
```

A line that starts with an amount it can't use, such as 0, a reversed range, an amount too large or too small to read, or a number whose marks it can't read, as in `'0 eggs'`, `'3-2 eggs'`, or `'1,500 g flour'`, succeeds with the whole line as the name and one warning that says how to fix it. So does a line that's only a mass or volume, as in `'2 cups'`, and some lines with a quantity it can't read in full, as in `'2 or 3 eggs'`, so an ingredient list never fails because of how a line is written. A sign, `NaN`, or `Infinity` at the start isn't an amount, so `'-2 eggs'`, `'NaN cups flour'`, and `'Infinity g flour'` keep the whole line as the name with no warning, as `'salt'` does. In recipe input, the issue's path is the line's path.

Doesn't throw for text. For blank text or a value that isn't text, it returns a [`RecipeValidationError`](https://recipe-book.siraj.page/reference/core/errors.md#recipevalidationerror) with the code [`invalid_ingredient`](https://recipe-book.siraj.page/errors/invalid_ingredient.md), whose page lists the warnings too. An error thrown by a getter or a proxy in the options passes through. It throws a [`RecipeBookError`](https://recipe-book.siraj.page/reference/core/errors.md#recipebookerror) with the code [`invalid_argument`](https://recipe-book.siraj.page/errors/invalid_argument.md) for an invalid option, as [`parseQuantity`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantity) does.

## `recipeSchema`

```ts
const recipeSchema: RecipeSchema
```

Validates recipe input with [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe), in the [Standard Schema](https://standardschema.dev) v1 format that validation libraries accept. It reads ingredient objects only; use [`createRecipeSchema`](https://recipe-book.siraj.page/reference/core/parsing.md#createrecipeschema) for ingredient lines.

`recipeSchema['~standard']` has `version: 1`, `vendor: 'recipe-book'`, and a `validate` function that takes these parameters:

| Name      | Type                                                                 | Default  | Description                                                      |
| --------- | -------------------------------------------------------------------- | -------- | ---------------------------------------------------------------- |
| `value`   | `unknown`                                                            | Required | The recipe input to validate.                                    |
| `options` | `{ readonly libraryOptions?: Record<string, unknown> \| undefined }` | None     | Options from the library that calls `validate`. They're ignored. |

`validate` returns `{ value }` with the recipe on success, or `{ issues }` on failure, where each issue has a `message` and a `path`. It returns only issues with the severity `error`, so recipe input whose issues all have the severity `warning` passes. Validation is synchronous, so `validate` returns the result itself, never a promise.

```ts
import { recipeSchema } from '@recipe-book/core'

const result = recipeSchema['~standard'].validate({
  name: 'Toast',
  servings: 0,
  ingredients: [{ name: 'bread', quantity: '2 slicez' }],
  steps: ['Toast the bread.'],
})

result.issues // [{ message: 'Expected a positive number, received 0.', path: ['servings'] }, { message: 'Unknown unit "slicez". Did you mean "slices"?', path: ['ingredients', 0, 'quantity'] }]
```

Libraries that accept a Standard Schema include tRPC 11 and TanStack Form, and Hono and React Hook Form through `@hono/standard-validator` and `@hookform/resolvers`. [Validate recipes](https://recipe-book.siraj.page/guides/validate-recipes.md#validate-with-standard-schema) shows `recipeSchema` in tRPC.

Doesn't throw for bad input, though an error thrown by a getter or proxy in the input passes through.

`recipeSchema` has the type `RecipeSchema`, which core exports. `createRecipeSchema` returns a `RecipeSchema<string>` when the options' type includes `parseIngredientLine`: when you pass it, or when the options are typed as `ParseRecipeOptions`, though without `parseIngredientLine` its `validate` reads ingredient objects only. `RecipeSchema<string>` takes [`RecipeInput<string>`](https://recipe-book.siraj.page/reference/core/types.md#recipeinput), which allows ingredient lines:

```ts
interface RecipeSchema<
  Line extends string = never,
> extends StandardSchemaV1<RecipeInput<Line>, Recipe> {
  readonly '~standard': {
    readonly version: 1
    readonly vendor: 'recipe-book'
    readonly validate: (
      value: unknown,
      options?: StandardSchemaV1.Options,
    ) =>
      | StandardSchemaV1.SuccessResult<Recipe>
      | {
          readonly issues: readonly {
            readonly message: string
            readonly path: readonly (string | number)[]
          }[]
        }
    readonly types?:
      StandardSchemaV1.Types<RecipeInput<Line>, Recipe> | undefined
  }
}
```

`StandardSchemaV1` and its base type, `StandardTypedV1`, are exported too:

```ts
interface StandardSchemaV1<Input = unknown, Output = Input> {
  readonly '~standard': StandardSchemaV1.Props<Input, Output>
}
interface StandardTypedV1<Input = unknown, Output = Input> {
  readonly '~standard': StandardTypedV1.Props<Input, Output>
}
```

They're copies of the types in [`@standard-schema/spec`](https://www.npmjs.com/package/@standard-schema/spec), which describes each member. The namespaces are copied too, so `StandardSchemaV1.InferOutput<typeof recipeSchema>` is `Recipe` without that package installed.

## `createRecipeSchema`

```ts
function createRecipeSchema(
  options?: Omit<ParseRecipeOptions, 'parseIngredientLine'> & {
    parseIngredientLine?: undefined
  },
): RecipeSchema
function createRecipeSchema(options: ParseRecipeOptions): RecipeSchema<string>
```

Makes a schema like [`recipeSchema`](https://recipe-book.siraj.page/reference/core/parsing.md#recipeschema) whose `validate` parses with `options`.

| Name      | Type                 | Default | Description                                                                                                                                                                                                 |
| --------- | -------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `options` | `ParseRecipeOptions` | `{}`    | The [`parseRecipe` options](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe) to parse with: `decimal`, `units`, and `parseIngredientLine`. They're read once, when the schema is made. |

Returns a [`RecipeSchema<string>`](https://recipe-book.siraj.page/reference/core/parsing.md#recipeschema) when `options` has `parseIngredientLine`, and a `RecipeSchema`, which reads ingredient objects only, like `recipeSchema`, when it doesn't, as with `createRecipeSchema({ decimal: ',' })`. The return type follows the type of `options`, so one typed as `ParseRecipeOptions` gives a `RecipeSchema<string>` even when it has no `parseIngredientLine`, though its `validate` then reads ingredient objects only. In tRPC 11, pass it to `.input()`:

```ts
import { createRecipeSchema, parseIngredientLine } from '@recipe-book/core'
import { initTRPC } from '@trpc/server'

const t = initTRPC.create()

export const appRouter = t.router({
  saveRecipe: t.procedure
    .input(createRecipeSchema({ parseIngredientLine }))
    .mutation(({ input }) => input.id),
})
```

Throws a [`RecipeBookError`](https://recipe-book.siraj.page/reference/core/errors.md#recipebookerror) with the code [`invalid_argument`](https://recipe-book.siraj.page/errors/invalid_argument.md) for an invalid option, as [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe) does. It reads `options` once, when it makes the schema, so an error thrown by a getter or proxy in them passes through from `createRecipeSchema` itself. Its `validate` doesn't throw for bad input, though an error thrown by a getter or proxy in the input, or by a `parseIngredientLine` of your own, passes through. When yours returns something other than a parse result, `validate` can throw a `TypeError`.

## `ParseQuantityOptions`

```ts
type ParseQuantityOptions = {
  decimal?: '.' | ',' | undefined
  units?:
    | {
        cup?: 'cup' | 'cup-metric' | undefined
        tbsp?: 'tbsp' | 'tbsp-au' | undefined
      }
    | undefined
}
```

The options for [`parseQuantity`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantity) and [`parseIngredientLine`](https://recipe-book.siraj.page/reference/core/parsing.md#parseingredientline), which [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe), [`createRecipeSchema`](https://recipe-book.siraj.page/reference/core/parsing.md#createrecipeschema), and [`fromJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#fromjsonld) take too: how to read the decimal marks and units in quantity text.

| Name      | Type                                                                                                 | Description                                                                                                                                                                                                                                                                                                                                  |
| --------- | ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `decimal` | `'.' \| ',' \| undefined`                                                                            | The decimal mark the text uses. Defaults to `'.'`. It decides whether a number such as `1,500` or `1.500`, whose mark could also separate thousands, is a decimal, as [`parseQuantity`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantity) describes.                                                                   |
| `units`   | `{ cup?: 'cup' \| 'cup-metric' \| undefined; tbsp?: 'tbsp' \| 'tbsp-au' \| undefined } \| undefined` | Which cup and tablespoon the text means. `cup: 'cup-metric'` reads every alias of cup, such as `cups` and `c`, as the 250 mL metric cup, and `tbsp: 'tbsp-au'` reads every alias of tbsp as the 20 mL Australian tablespoon. Defaults to the US `'cup'` and `'tbsp'`. It applies to text only: a quantity object's `unit` keeps its meaning. |

Other keys are ignored, except in `units`, where a key other than `cup` and `tbsp` throws [`invalid_argument`](https://recipe-book.siraj.page/errors/invalid_argument.md). Neither option is read from a locale, because the decimal mark doesn't follow the language: European recipe sites write both periods and commas.

```ts
import { parseQuantity } from '@recipe-book/core'

parseQuantity('1,500 g', { decimal: ',' }) // { success: true, data: { amount: 1.5, unit: 'g' }, warnings: [] }
parseQuantity('2 tbsp', { units: { tbsp: 'tbsp-au' } }) // { success: true, data: { amount: 2, unit: 'tbsp-au' }, warnings: [] }
```

> **Caution**
>
> Pass `units` only for text written with metric cups or Australian tablespoons. A US recipe read with `cup: 'cup-metric'` gets cups about 6% larger, and one read with `tbsp: 'tbsp-au'` gets tablespoons about 35% larger.

[Author recipes](https://recipe-book.siraj.page/guides/author-recipes.md#read-regional-recipes) reads a German recipe with `decimal` and an Australian one with `units`.

### Edge cases

For a number whose mark could separate thousands, the issue's message gives both readings:

```ts
import { parseQuantity } from '@recipe-book/core'

const result = parseQuantity('1,500 g')

result.success // false
parseQuantity('1.500 g') // { success: true, data: { amount: 1.5, unit: 'g' }, warnings: [] }
parseQuantity('1.500 g', { decimal: ',' }).success // false
```

result.error.message
```txt title="result.error.message"
"1,500 g" has 1 problem:
  ✖ (root)  Couldn't read "1,500 g". "1,500" could be "1500" or "1.5": write one of those, or pass { decimal: "," } to read commas as decimals.
See https://recipe-book.siraj.page/errors/invalid_quantity/
```

- In a range, or text with several numbers, the message quotes the first number that could be either, so `'250-1,500 g'` gets `"1,500" could be "1500" or "1.5"`.
- In an ingredient line, a comma decimal in parentheses reads as a period does, so `'2 cups milk (0,5 l)'` gets the equivalent `{ amount: 0.5, unit: 'l' }`. Parentheses it can't read stay a note, so without `decimal: ','`, `'flour (1,500 g)'` gets the note `1,500 g`.
- `decimal` changes only what the parsers read. The formatters write decimals for their `locale`, so `formatQuantity` with `locale: 'de'` and `rounding: 'none'` writes `1,125 kg`, which reads back only with `decimal: ','`.

## `ParseResult`

```ts
type ParseResult<T> =
  | { success: true; data: T; warnings: RecipeIssue[] }
  | { success: false; error: RecipeValidationError }
```

The result of [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe), [`parseQuantity`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantity), and [`parseIngredientLine`](https://recipe-book.siraj.page/reference/core/parsing.md#parseingredientline), which you narrow by checking `success`. [`fromJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#fromjsonld) returns one with an `extra` field added, a [`FromJsonLdResult`](https://recipe-book.siraj.page/reference/core/schema-org.md#fromjsonldresult).

| Name       | Type                                                                                                     | Description                                                                                                                                                                            |
| ---------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `success`  | `true \| false`                                                                                          | `true` when the input parsed.                                                                                                                                                          |
| `data`     | `T`                                                                                                      | The parsed value. Present only when `success` is `true`.                                                                                                                               |
| `warnings` | [`RecipeIssue`](https://recipe-book.siraj.page/reference/core/errors.md#recipeissue)[]                   | The issues with the severity `warning`. A warning doesn't fail the parse. Present only when `success` is `true`.                                                                       |
| `error`    | [`RecipeValidationError`](https://recipe-book.siraj.page/reference/core/errors.md#recipevalidationerror) | The error, whose `issues` lists every issue. It's an `Error`, so throwing it gives a stack trace and a message that lists the first 10 issues. Present only when `success` is `false`. |

```ts
import { parseRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Toast',
  serving: 2,
  ingredients: [{ name: 'bread', quantity: '2 slices' }],
  steps: ['Toast the bread.'],
})

if (!result.success) {
  throw result.error
}

result.warnings // [{ code: 'unknown_field', severity: 'warning', path: ['serving'], message: 'Unknown field. Did you mean "servings"?', suggestion: 'servings' }]
```

[Validate recipes](https://recipe-book.siraj.page/guides/validate-recipes.md) uses it to read a failed parse's issues and a successful one's warnings.
