▲ Cairn

cairn-core

API reference for the framework-agnostic engine — FlowEngine, defineFlow, and persistence.

cairn-core

The framework-agnostic state-machine engine. Zero dependencies. Use it directly for non-React apps, custom renderers, or server-side logic.

defineFlow(definition)

A typed identity helper. It returns the definition unchanged but pins the context type C, so next and canEnter callbacks get full inference.

const flow = defineFlow<{ hasTeam: boolean }>({
  id: "onboarding",
  initialContext: { hasTeam: false },
  steps: [/* … */],
});

new FlowEngine(definition, options?)

Creates and owns a running flow.

const engine = new FlowEngine(flow, {
  autoStart: false,
  persistence: { adapter: createWebStorageAdapter() },
});

EngineOptions

OptionTypeDefaultDescription
autoStartbooleanfalseStart the flow immediately on construction.
persistencePersistenceConfigPersist & resume across reloads.

Methods

MethodDescription
getState()Current immutable FlowState snapshot.
start()Begin (or resume) the flow.
next()Resolve the current step's next and transition.
back()Re-enter the previous step in history.
goTo(stepId)Jump to a step by id.
setContext(patch)Merge a patch into context; emits context:update.
skip() / dismiss()End the flow as skipped / dismissed.
reset()Clear persisted progress; return to idle.
subscribe(fn)State-snapshot subscription. Returns an unsubscribe fn.
on(type, fn)Subscribe to a single event. Returns an unsubscribe fn.
onAny(fn)Subscribe to every event. Returns an unsubscribe fn.
destroy()Remove all listeners.

subscribe is shaped for React's useSyncExternalStore; the snapshot reference is stable between transitions, so it won't cause spurious renders.

Persistence API

import {
  createWebStorageAdapter,
  createMemoryAdapter,
  clearPersisted,
  persistenceKey,
  type PersistenceAdapter,
  type PersistenceConfig,
  type PersistedFlow,
} from "cairn-core";

PersistenceConfig

FieldTypeDefaultDescription
adapterPersistenceAdapterThe key-value store.
keystringOverride the storage key entirely.
namespacestringScope the key (e.g. a user id) → cairn:ns:flowId.
respectCompletedbooleantrueDon't re-show a finished flow on start().

PersistenceAdapter

interface PersistenceAdapter {
  load(key: string): string | null;
  save(key: string, value: string): void;
  remove(key: string): void;
}

See Persistence & Resume for the full guide.

Types

All public types are exported: FlowDefinition, StepDefinition, FlowState, FlowStatus, StepTarget, StepGuard, FlowContext, CairnEvent, CairnEventType, CairnEventMap.

On this page