API/functional-examples

functional-examples

npm install functional-examples
v0.1.2NPMGitHub

functional-examples

A language-agnostic library for treating code examples as first-class citizens.

Features

  • Pluggable metadata extraction: YAML frontmatter and meta.yml built-in
  • Language-aware region parsing: Extracts code regions with comment-style detection
  • Flexible scanning: Directory-based and file-based example discovery
  • Type-safe API: Full TypeScript support with generic metadata types

Installation

npm install functional-examples
# or
pnpm add functional-examples
# or
yarn add functional-examples

Quick Start

Scanning for Examples

/**
 * Basic example: Scanning for examples programmatically
 */
import { scan } from 'functional-examples';

async function main() {
  // scan() auto-discovers config and plugins
  const result = await scan();

  console.log(`Found ${result.examples.length} examples:`);
  for (const example of result.examples) {
    console.log(`  - ${example.title} (${example.id})`);
  }

  if (result.errors.length > 0) {
    console.log(`\n${result.errors.length} errors occurred:`);
    for (const error of result.errors) {
      console.log(`  - ${error.path}: ${error.message}`);
    }
  }
}

main().catch(console.error);

Example Formats

Directory-based (meta.yml)

id: basic-usage
title: Basic Usage
description: |
  Demonstrates scanning for examples in a directory
  using the functional-examples library.
tags:
  - getting-started
  - api

This meta.yml defines metadata for one example directory.

File-based (YAML frontmatter)

// ---
// id: hello
// title: Hello World
// description: A minimal example
// ---

export function hello() {
  return 'Hello from functional-examples!';
}

Region Markers

/**
 * ---
 * id: region-markers
 * title: Region Markers Demo
 * ---
 */

import { scan } from 'functional-examples';

// #region setup
const result = await scan();
// #endregion

// #region execution
console.log(result.examples);
// #endregion

Supports 30+ languages with automatic comment syntax detection.

Custom Extractors

/**
 * Custom TOML-based extractor example.
 *
 * This demonstrates how to create your own extractor that:
 * 1. Scans for a specific file pattern (meta.toml)
 * 2. Parses metadata from that file format
 * 3. Claims files and returns Example objects
 */
import {
  ExampleFile,
  type Example,
  type Extractor,
  type ExtractorResult,
} from 'functional-examples';
import { readdirSync, type Dirent } from 'node:fs';
import { readFile } from 'node:fs/promises';
import path, { join } from 'node:path';

/**
 * Metadata structure for TOML examples.
 * You can define any shape that fits your use case.
 */
export interface TomlMetadata {
  id: string;
  title: string;
  description?: string;
  author?: string;
  [key: string]: unknown;
}

/**
 * Create a custom extractor that reads TOML metadata files.
 *
 * Extractors implement a candidate-based pattern: they're called with
 * pre-filtered candidates (files and directories) and decide which to handle.
 */
export function createTomlExtractor(): Extractor<TomlMetadata> {
  return {
    name: 'toml-extractor',

    async extract(
      candidates: Dirent[]
    ): Promise<ExtractorResult<TomlMetadata>> {
      const examples: Example<TomlMetadata>[] = [];
      const claimedFiles = new Set<string>();
      const errors: { path: string; message: string }[] = [];

      // Find meta.toml files from candidates
      const tomlFiles: string[] = [];

      for (const candidate of candidates) {
        const fullPath = path.join(candidate.parentPath, candidate.name);

        if (candidate.isFile()) {
          // Direct file candidate: check if it's a meta.toml
          if (candidate.name === 'meta.toml') {
            tomlFiles.push(fullPath);
          }
        } else if (candidate.isDirectory()) {
          // Directory candidate: look for meta.toml inside
          const metaPath = path.join(fullPath, 'meta.toml');
          try {
            await readFile(metaPath, 'utf-8');
            tomlFiles.push(metaPath);
          } catch {
            // No meta.toml in this directory, skip
          }
        }
      }

      for (const tomlFile of tomlFiles) {
        try {
          const content = await readFile(tomlFile, 'utf-8');
          const metadata = parseSimpleToml(content);

          const exampleDir = path.dirname(tomlFile);

          // Collect all files in the example directory
          const files = collectExampleFiles(exampleDir);

          // Claim all files
          for (const file of files) {
            claimedFiles.add(file);
          }

          examples.push({
            id: metadata.id,
            title: metadata.title,
            description: metadata.description,
            rootPath: exampleDir,
            files: files.map((f) => new ExampleFile({
              absolutePath: f,
              relativePath: path.relative(exampleDir, f),
            })),
            metadata,
            extractorName: 'toml-extractor',
          });
        } catch (err) {
          errors.push({
            path: tomlFile,
            message: `Failed to parse: ${(err as Error).message}`,
          });
        }
      }

      return { examples, errors, claimedFiles };
    },
  };
}

/**
 * Simplified TOML parser for demonstration.
 * In production, use a proper TOML library like @iarna/toml.
 */
function parseSimpleToml(content: string): TomlMetadata {
  const lines = content.split('\n');
  const result: Record<string, string> = {};

  for (const line of lines) {
    // Match: key = "value"
    const match = line.match(/^(\w+)\s*=\s*"(.*)"/);
    if (match) {
      result[match[1]] = match[2];
    }
  }

  if (!result['id'] || !result['title']) {
    throw new Error('TOML must have id and title fields');
  }

  return {
    id: result['id'],
    title: result['title'],
    description: result['description'],
    author: result['author'],
  };
}

function collectExampleFiles(root: string) {
  if (root.endsWith('node_modules')) {
    return [];
  }

  let files: string[] = [];
  const entries = readdirSync(root, { withFileTypes: true });
  for (const entry of entries) {
    if (entry.isDirectory()) {
      files = files.concat(
        collectExampleFiles(join(entry.parentPath, entry.name))
      );
    } else {
      files.push(join(entry.parentPath, entry.name));
    }
  }
  return files;
}

API Reference

Scanner

  • scan(options?) - Discover config and scan in one call
  • scanExamples(resolvedConfig) - Scan with a pre-resolved config

Configuration

  • findConfigFile(root?)
  • loadConfig(configPath)
  • resolveConfig(config)
  • validateConfig(config)
  • mergeConfigs(...configs)

Plugins and Validation

  • PluginRegistry
  • createInitialContext(context)
  • runParsePipeline(context, parsers)
  • validatePluginOptions(context)
  • validateExampleMetadata(context)

File Helpers

  • readExampleFile(path, options?)
  • readExampleFiles(root, files)

Schema Utilities

  • mergeConfigSchema(...)
  • mergeMetadataSchemas(...)
  • generateTypes(...)

License

MIT

API EXPORTS

Functions

createInitialContextfunction

Create the initial parse context for a file.

findConfigFilefunction
generateTypesfunction

Generate TypeScript type declarations from merged metadata schema and plugin schemas, emitting a single `declare module` block that contains both the ExampleMetadataRegistry and (when plugins are present) PluginOptionsRegistry interface augmentations.

loadConfigfunction
mergeConfigsfunction

Merge multiple configuration sources with later configs taking precedence.

mergeConfigSchemafunction

Merge plugin schemas into a complete config schema.

mergeMetadataSchemasfunction

Merge metadata schemas from config and plugins. Config schema takes priority on conflicts.

readExampleFilefunction

Read an example file's contents.

readExampleFilesfunction

Read multiple files from an example directory.

resolveConfigfunction

Resolve a configuration to actual plugin and extractor instances. Plugin resolution follows this priority: 1. If `config.plugins` contains Plugin instances (from TS configs), use directly 2. If `config.plugins` contains string/tuple references (from JSON configs), resolve them by dynamically importing the package and calling its factory 3. If no plugins specified at all, auto-detect installed plugin packages

runParsePipelinefunction

Run file content through a parser pipeline. Parsers execute in order, each receiving the output of the previous. Hunks are accumulated across parsers automatically. Each parser receives an empty hunks array and only needs to return its own hunks. The pipeline merges them in order so parsers don't need to preserve earlier hunks.

scanfunction

Scan for examples using automatic config discovery. This is the simplest entry point for programmatic scanning. It discovers the nearest config file, loads it, resolves plugins, and runs the scanner — all in one call.

scanExamplesfunction

Scan a directory for examples using the provided extractors. The scanner: 1. Runs all extractors in parallel against the root 2. Collects claimed files and detects conflicts 3. Resolves conflicts via path mappings (or errors if unresolved) 4. Applies include/exclude filters AFTER extraction 5. Returns unified results

validateConfigfunction
validateExampleMetadatafunction

Validate example metadata after extraction. Runs all metadata validators against each example's metadata.

validatePluginOptionsfunction

Validate plugin options before extraction. Runs each plugin's options validator against its configured options.

Interfaces

BaseMetadatainterface

Base metadata that all examples should have. Used for type constraints when users want stricter typing.

Configinterface
ConfigValidationErrorinterface

Error from config validation.

Exampleinterface

A discovered example with metadata and files. This is the base type returned by extractors. Metadata is typed via `ExampleMetadata` by default, which can be augmented by running `functional-examples generate`. You can also pass an explicit generic parameter for custom typing.

ExampleMetadataRegistryinterface

Augmentable registry for example metadata typing. Run `functional-examples generate` to create a declaration file that augments this interface, providing type-safe metadata for your examples.

Extractorinterface

Candidate-based extractor interface. Called with pre-filtered candidates (files and/or directories). Extractor decides which candidates it can handle.

ExtractorConfiginterface

Reference to an extractor package (for config files)

ExtractorErrorinterface

Error encountered during extraction

ExtractorOptionsinterface

Options passed to extractor during extraction

ExtractorResultinterface

Result from a candidate-based extractor

FileConflictinterface

Conflict when multiple extractors claim the same file

FileContentsParserinterface

Parser that processes file contents in a pipeline. Receives accumulated context, transforms it, returns updated context.

FileParseContextinterface

Context passed through the FileContentsParser pipeline. Each parser receives this, transforms it, and returns an updated version.

GenerateConfiginterface

Configuration for the generate command output.

GenerateTypesOptionsinterface
JSONSchemainterface

JSON Schema type (subset of JSON Schema spec).

JSONSchemaObjectinterface

JSON Schema object for metadata validation. Subset of JSON Schema spec used for config files.

MergeConfigSchemaOptionsinterface
MergeMetadataSchemasOptionsinterface
MetadataValidationContextinterface

Context for validating example metadata.

MetadataValidationErrorinterface

Error from metadata validation with example context.

MetadataValidationResultinterface

Result of validating example metadata.

OptionsValidationErrorinterface

Error from options validation with plugin context.

OptionsValidationResultinterface

Result of validating plugin options.

ParsedRegioninterface

Parsed code region from #region markers.

PathMappinginterface

Path-to-extractor mapping for conflict resolution.

Plugininterface

Plugin containing optional extractors, parsers, schemas, and validators. Auto-registers for declared file extensions.

PluginOptionsValidationContextinterface

Context for validating plugin options.

PluginSchemaEntryinterface

Schema entry from a plugin with plugin name context.

PluginSchemasinterface

Schema definitions for a plugin (JSON Schema format). Used for IDE autocomplete and documentation generation.

PluginValidatorinterface

Wrapper for a plugin's validator function with plugin name context.

PluginValidatorsinterface

Validator functions for a plugin. Allows plugins to use any validation library (Zod, TypeBox, etc.)

ResolvedConfiginterface

Resolved configuration with actual extractor instances. This is the runtime-ready configuration after all plugins are loaded.

ScanConfiginterface

Scan configuration options.

ScanOptionsinterface

Options for the convenience `scan()` function.

ScanResultinterface

Result of scanning for examples

ValidationErrorinterface

A single validation error.

ValidationResultinterface

Result of a validation operation.