Skip to content

API reference

Gram is not just a file format — it is a pipeline of small, composable libraries. Each package does one dedicated job and hands a deterministic JSON object to the next. You can use the full pipeline end-to-end, or pick out just the module you need (e.g. only the parser, to build a custom linter).

npm install @gram-lang/parser @gram-lang/modules @gram-lang/kitchen @gram-lang/scheduler @gram-lang/analyzer @gram-lang/renderer @gram-lang/format

All packages are ESM-only, side-effect free, and run in any JavaScript runtime — Node.js, Deno, Bun, edge runtimes, or directly in the browser (see the Playground for a fully client-side demonstration).

PackageRoleMain entry point
@gram-lang/parserTurns .gram source text into an Abstract Syntax Tree (AST)getAST(source)
@gram-lang/modulesResolves @use imports, tracks dependencies, scales bases by yield, and composes a unified ASTloadModuleGraph(entry, host), composeRecipe(graph, opts)
@gram-lang/kitchenCompiles the AST into a structured, render-ready payload (shopping list, task graph, default schedule, cookware registry)compile(ast, options?)
@gram-lang/schedulerComputes theoretical ALAP scheduling and projects recipes onto a real-world calendar based on target serving time and availabilitylayout(graph, options?), project(recipes, context), runSheet(plan), findServeTimes(), earliestServe()
@gram-lang/analyzerEnriches a compiled recipe with physical properties (mass, yield, nutrition, baker’s percentages) using an ingredient databaseanalyze(compiled, database, options?)
@gram-lang/rendererRenders a (compiled or analyzed) recipe to Markdown, HTML, or plain text, and the run sheet of a scheduletoMarkdown, toHTML, toPrintHTML, toText, runSheetTo*
@gram-lang/formatCanonical code formatter for .gram files (13 unified formatting rules)formatGram(source)
@gram-lang/i18nShared unit/time normalization and UI dictionaries used internally by the pipeline packagesnormalizeUnit, getDictionary

Analysis is optional: compile() alone provides a complete, renderable recipe (with raw, un-standardized quantities). You only need @gram-lang/analyzer when you require volume-to-mass conversion, nutrition estimation, or baker’s math, which rely on an ingredient database.

Optional: Node-only shortcut (@gram-lang/cli)

Section titled “Optional: Node-only shortcut (@gram-lang/cli)”

If you are running in Node.js and do not require stage-by-stage control, @gram-lang/cli — the same package that powers the gram CLI binary — also exports a concise programmatic helper:

import { runPipeline, GramCLIError } from '@gram-lang/cli';

const { content, compiled, analyzed } = await runPipeline('recipe.gram', {
  db: myDatabase,           // optional — omit to skip the analyzer stage
  scaleFactor: 2,            // optional
  bakersReference: 'flour',  // optional
});

runPipeline(filePath, options?) reads the file from disk, then executes getAST → compile → (only if db is supplied) analyze, returning { content, compiled, analyzed }. It throws a GramCLIError (an Error subclass carrying an .exitCode property aligned with the exported ExitCode enum) instead of a generic error — making it easy to map failures to custom process exit codes. This shortcut is Node-only (reads via node:fs); for browsers or edge runtimes, compose the individual packages as shown below.

import { getAST, GramParseError } from '@gram-lang/parser';
import { compile } from '@gram-lang/kitchen';
import { layout } from '@gram-lang/scheduler';
import { analyze, validateIngredientDatabase } from '@gram-lang/analyzer';
import { toHTML } from '@gram-lang/renderer';

function renderRecipe(source: string, rawIngredientDb: unknown) {
  // 1. Parse .gram text into an AST
  let ast;
  try {
    ast = getAST(source);
  } catch (err) {
    if (err instanceof GramParseError) {
      console.error(`Syntax error at offset ${err.offset}: expected ${err.expected}`);
    }
    throw err;
  }

  // 2. Compile the AST into a structured recipe (shopping list, task graph, default schedule)
  const compiled = compile(ast);

  // 2b. Optional: compute a custom schedule from the neutral task graph
  // const { schedule } = layout(compiled.tasks, { miseEnPlace: 'upfront' });

  // 3. Load and validate the ingredient database, then enrich with physical/nutritional data
  const { data: database, rejected } = validateIngredientDatabase(rawIngredientDb);
  if (rejected.length > 0) {
    console.warn('Ignoring invalid ingredient entries:', rejected);
  }
  const { result: analyzed, missingIngredients } = analyze(compiled, database);

  // 4. Render to HTML
  return toHTML(analyzed);
}

When working with recipes that contain @use import directives across multiple files, insert @gram-lang/modules between the parser and the compiler:

import { loadModuleGraph, composeRecipe, finalizeComposed, createMemoryHost } from '@gram-lang/modules';
import { compile } from '@gram-lang/kitchen';
import { analyze } from '@gram-lang/analyzer';
import { toHTML } from '@gram-lang/renderer';

async function renderModularRecipe(entryUri: string, host: ModuleHost, rawIngredientDb: unknown) {
  // 1. Resolve and load the full import graph (DFS, cycle detection)
  const graph = await loadModuleGraph(entryUri, host);

  // 2. Compose into a single AST with yield scaling and hygienic renaming
  const composed = composeRecipe(graph, { db: database });

  // 3. Compile the composed AST
  const compiled = compile(composed.ast);
  const result = finalizeComposed(compiled, composed);

  // 4. Enrich with physical database + synthetic ingredients for stocked intermediate preparations
  const enrichedDb = { ...database, ...composed.syntheticIngredients };
  const { result: analyzed } = analyze(result, enrichedDb);

  // 5. Render to HTML
  return toHTML(analyzed);
}

getAST() is the only function in the pipeline that throws: a syntax error means there is no AST to work with. Every later stage instead collects warnings — a recipe with non-fatal issues still compiles, allowing your application to render the preview and surface diagnostics to the user.

  • GramParseError (thrown by getAST): carries .message (human-readable diagnostic from Ohm.js, source excerpt included), .offset (character offset into the input string), and .expected (grammar rule or token expected).
  • CompilationResult.warnings / AnalyzedCompilationResult.warnings (returned by compile() and carried through analyze()): an array of structured Warning objects. See the Warnings reference for the complete list of error codes and instructions for enforcing --strict-style gates.