Skip to content

@gram-lang/kitchen

This is the compiler. It accepts a RecipeAST (from @gram-lang/parser) and produces a CompilationResult: a clean, structured JSON object ready for rendering (unified shopping list, section-sliced instructions with scheduling metadata, global registries of ingredients and cookware, and structural warnings). No ingredient database is required at this stage: physical enrichment is handled by @gram-lang/analyzer.

function compile(ast: RecipeAST, options?: CompilerOptions): CompilationResult
import { getAST } from '@gram-lang/parser';
import { compile } from '@gram-lang/kitchen';

const ast = getAST(source);
const compiled = compile(ast);
// compiled.shopping_list, compiled.sections, compiled.metrics, compiled.schedule, compiled.warnings, ...

This function throws a JavaScript Error for structural violations that cannot be represented as recoverable warnings (for example, multiple ingredients annotated with the baker’s percentage reference marker *).

interface CompilerOptions {
  scaleFactor?: number; // applies a fixed multiplier to the compiled output
}
interface CompilationResult {
  generator: string;                 // "@gram-lang/kitchen@<version>": compiler version that generated this JSON
  title: string | null;
  slug: string | null;
  meta: Meta;                        // parsed frontmatter metadata
  scaleFactor?: number;              // present whenever a scale factor was applied
  registry: {
    ingredients: Record<string, RegistryEntry>;
    cookware: Record<string, { id: string; name: string }>;
  };
  shopping_list: (ShoppingListItem | CompositeItem | Usage)[];
  cookware: Usage[];
  sections: ProcessedSection[];
  warnings: Warning[];
  metrics: {
    preparationTime: number;         // sum of miseEnPlace[].duration (minutes)
    activeTime: number;              // sum of brigade active hands-on work (minutes)
    // Deprecated since 1.4.0, removed in 2.0.0 (see below):
    totalTime: number;
    idleTime: number;
    activeBreakdown: TimeBreakdownItem[];
    prepBreakdown: TimeBreakdownItem[];
    totalBreakdown: TimeBreakdownItem[];
  };
  miseEnPlace: SectionMiseEnPlace[]; // required preparation tasks and durations per section
  tasks: TaskGraph;                  // neutral task graph with durations and dependencies
  schedule: Schedule;                // default theoretical schedule laid out from `tasks`
}

interface SectionMiseEnPlace {
  section: number;                   // index in `sections`
  duration: number;                  // == sum of items[].duration
  items: MiseEnPlaceItem[];
}

type MiseEnPlaceItem =
  | { kind: "gather"; target: "ingredient" | "cookware"; count: number; duration: number; intermediates?: number }
  | { kind: "prepare"; ref: { type: "ingredient" | "cookware"; id: string }; duration: number; intermediate?: true };

interface Schedule {
  miseEnPlace: MiseEnPlaceMode;      // preparation placement strategy: "perSection" by default
  rests: RestChoice;                 // passive timer elasticity: "shortest" by default
  totalTime: number;                 // max(end) across all scheduled blocks, relative to t = 0
  activeTime: number;                // hands-on kitchen work, excluding preparation
  preparationTime: number;           // cumulative preparation duration (sum of prep tasks)
  idleTime: number;                  // total idle duration: totalTime - activeTime - preparationTime
  blocks: ScheduledBlock[];          // complete timeline blocks (prep, step, passive)
  days: ScheduleDay[];       // plan breakdown by working day relative to service
}

See Data formats for an annotated example of this structure, and the Warnings reference for diagnostics emitted in warnings.

Recipes are compiled initially at baseline quantities. Scaling is a pure, composable operation: client interfaces (such as an interactive portion slider) can recalculate quantities instantly without reparsing or recompiling.

function resolveScaleFactor(
  compiled: CompilationResult | null,
  request: ScaleRequest,
  convertUnit?: UnitConverter,
): ScaleResolution

function applyScale(result: CompilationResult, factor: number): CompilationResult

The ScaleRequest structure accepts a fixed multiplier or a target quantity for a specific shopping list ingredient:

type ScaleRequest =
  | { type: "factor"; value: number }
  | { type: "target"; id: string; qty: number; unit: string | null };
import { resolveScaleFactor, applyScale } from '@gram-lang/kitchen';

// "I want 300g flour total" -> derives factor from compiled shopping list
const { factor } = resolveScaleFactor(compiled, { type: 'target', id: 'flour', qty: 300, unit: 'g' });
const scaled = applyScale(compiled, factor);

resolveScaleFactor throws a typed subclass of ScaleError (carrying a specific .code) when the request cannot be resolved: InvalidFactorError (non-positive factor or infinite quantity), IngredientNotFoundError, NestedOnlyTargetError (ingredient only used inside a sub-recipe), AlternativeTargetError (ingredient inside an alternative group @a|@b), FixedIngredientError (fixed @= or non-numeric quantity), RelativeTargetError (percentage-derived quantity %), AmbiguousMultiUnitError (incompatible units across recipe), NonNumericTargetError, UnitMismatchError.

The applyScale function is pure: it never mutates its input. The same CompilationResult can be scaled repeatedly without drift. It guarantees the mathematical invariant: applyScale(compile(ast), factor) ≡ compile(ast, { scaleFactor: factor }).

The compile() function orchestrates these utilities internally. They are exposed for specialized use cases (e.g. recalculating a shopping list from a programmatically synthesized ProcessedSection[] array).

function generateShoppingList(
  sections: ProcessedSection[],
  registry: Registry,
  options?: CompilerOptions,
): (ShoppingListItem | CompositeItem | Usage)[]

function calculatePreparationTime(
  sections: ProcessedSection[],
  registry: Registry,
  mise?: SectionMiseEnPlace[],
): { total: number; breakdown: TimeBreakdownItem[] } // `breakdown` is deprecated

function computeMiseEnPlace(sections: ProcessedSection[], registry: Registry): SectionMiseEnPlace[]

type MiseEnPlaceMode = "perSection" | "upfront" | "perDay"
const MISE_EN_PLACE_MODES: readonly ["perSection", "upfront", "perDay"]
const DEFAULT_MISE_EN_PLACE_MODE: MiseEnPlaceMode // "perSection"
function isMiseEnPlaceMode(value: unknown): value is MiseEnPlaceMode

type RestChoice = "shortest" | "balanced" | "longest"
const REST_CHOICES: readonly ["shortest", "balanced", "longest"]
const DEFAULT_REST_CHOICE: RestChoice // "shortest"
function isRestChoice(value: unknown): value is RestChoice

function scheduleFor(compiled: CompilationResult, mode?: MiseEnPlaceMode, rests?: RestChoice): Schedule | undefined
function scheduleTimes(compiled: CompilationResult, mode?: MiseEnPlaceMode, rests?: RestChoice): { totalTime: number; idleTime: number }

function layout(graph: TaskGraph, options?: LayoutOptions): { schedule: Schedule; diagnostics: SchedulingDiagnostic[] }

const MAX_DURATION_MINUTES: number // 525_600_000 (1000 years)
function quantityToMinutes(qty: { value: number; unit: string }): number
function isDurationTooLong(qty: { value: number; unit: string }): boolean
function maxDurationIn(unit: string): number

v1.5.0 readAnchor reads a section anchor (-2h, -1j 12h, -1:30 h) the way the schedule plans it: strictly negative, a single duration (no range), in days, hours and minutes (no seconds, no prime). The value comes back positive, in days when the anchor is written with days (it then opens a working day), otherwise in its smallest unit. A refused anchor comes back with the warning it gets when compiled.

function readAnchor(raw: string): AnchorReading

type AnchorReading =
  | { ok: true; value: number; unit: "d" | "h" | "min"; text?: string } // `text`: the number as written, for a single term
  | { ok: false; problem: { code: "MISSING_UNIT" } | { code: "INVALID_UNIT"; unit: string } | { code: "INVALID_DURATION"; reason: string } }

readAnchor('-1j 12h'); // { ok: true, value: 1.5, unit: "d" }
readAnchor('-1h30');   // { ok: true, value: 90, unit: "min" }
readAnchor('-1-2d');   // { ok: false, problem: { code: "INVALID_DURATION", reason: "anchorRange" } }

The mutable registry of ingredients and cookware built during compilation, keyed by slugify(name). It implements the Registry interface (ingredients: Map, cookware: Map, warnings: Warning[]).

class RecipeRegistry implements Registry {
  registerIngredient(name: string, data?: Partial<Omit<RegistryEntry, "id" | "name">>): string; // returns id
  registerCookware(name: string): string;                                                        // returns id
  getIngredientId(name: string): string;
  toPlainObject(): { ingredients: Record<string, RegistryEntry>; cookware: Record<string, {...}> };
}

The RegistryEntry structure exposes id, name, and optionally default_unit, is_composite, parent (for composite sub-ingredients), and is_intermediate.

The CompilationResult.warnings property is an array of Warning[] objects listing all structural defects detected during compilation (missing references, scope conflicts, invalid timer units, circular dependencies…). See the Warnings reference for codes, severity levels, and helper functions (WarningCode, pushWarning).