npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ai-digital-factory/state-flow-runtime

v0.2.0

Published

Application-owned durable State Flow execution over a storage adapter the application chooses.

Readme

@ai-digital-factory/state-flow-runtime

Application-owned durable execution over the storage the application chooses (ADR 0109). Requires Node.js 22.13 or later.

Storage

createRuntime takes a storage adapter, with no default:

| Adapter | Package | Keeps data | | ------------------------- | ----------------------------------------------- | ------------------------------------------------- | | sqliteStorage({ path }) | @ai-digital-factory/state-flow-storage-sqlite | In a file: instances survive restarts and deploys | | memoryStorage() | @ai-digital-factory/state-flow-storage-memory | In the object, for as long as the process lives |

Every recovery strategy works on both while the process runs. Only SQLite keeps them across a crash: with memory, a crash or deploy loses in-flight work, including an effect whose outcome was unknown. The runtime itself contains no storage code. An adapter implements StorageAdapter, an asynchronous contract of named reads and atomic batch commits checked against each root's version, so databases without interactive transactions can implement it too.

The runtime keeps the records of the instances it has opened in memory, and writes each checkpoint to storage before anything outside it can observe it. No callback runs, no outcome handler is called and no snapshot is returned until what preceded it is stored. If storage refuses a write, the runtime stops as a crash would (onRecoveryError receives the error), and the next runtime recovers from what storage holds.

Import from @ai-digital-factory/state-flow-runtime. There is one execution model: callback checkpoints, request deduplication and bounded recovery. Unknown external outcomes become authored States, never operator work (ADR 0106).

Every handlers package compiles for this runtime. No execution opt-in is needed. A callback's shape is its recovery, and state-flow compile type-checks it against its generated contract (ADR 0106):

  • Safe callbacks ({ run }): guards, onEnter, onExit, children, resolveStartState and the onTransition of a plain <Transition>. They are replayed on failure, so they must not cause external effects; they receive SafeDependencies, which omit effects at compile time and at runtime.
  • External callbacks ({ run, reconcile }): only the onTransition of an <ExternalTransition unresolved="…">. reconcile asks the external system what happened and returns completed, safe-to-retry, pending or unknown. unknown, or retries running out, commits the Transition's unresolved State; the application resolves it later with its own Transitions.
import { z } from "zod";

export const payloadSchema = z.strictObject({ amount: z.number().positive() });
export type Payload = z.output<typeof payloadSchema>;

export const onTransition = {
  run: async (context, payload) => {
    await context.dependencies.effects.payments.charge({
      idempotencyKey: context.operation.operationId,
      amount: payload.amount,
    });
  },
  reconcile: async (context) =>
    (await context.dependencies.effects.payments.find(
      context.operation.operationId,
    ))
      ? { decision: "completed" }
      : { decision: "safe-to-retry" },
} satisfies ExternalTransitionCallback<
  TransitionContext<Dependencies>,
  Payload
>;

A handlers package splits its Dependencies into { reads, effects } when it has External Transitions; only their onTransition sees effects.

Callbacks read service-supplied implementations through context.dependencies (formerly context.config). The handlers package owns the dependency interfaces; the service passes implementations to createFlow(compiled, dependencies) again after every restart, and State Flow never persists them.

Transition destinations and FinalState

A Transition declares its destinations with <To> children (ADR 0087). With one destination, onTransition is optional and returns nothing. With several, onTransition is required and returns one of the authored destination names; the generated TransitionResult type is that exact union:

import type {
  TransitionContext,
  TransitionResult, // "placed" | "rejected"
} from "@scope/flows/place-order.submit-order";

export const onTransition = {
  run: async (context, payload) => {
    const decision = await context.dependencies.effects.broker.submit({
      idempotencyKey: context.operation.operationId,
      ...payload,
    });
    return decision === "accepted" ? "placed" : "rejected";
  },
  reconcile: async (context) => {
    const decision = await context.dependencies.effects.broker.lookup(
      context.operation.operationId,
    );
    return decision === null
      ? { decision: "safe-to-retry" }
      : {
          decision: "completed",
          result: decision === "accepted" ? "placed" : "rejected",
        };
  },
} satisfies ExternalTransitionCallback<
  TransitionContext<Dependencies>,
  Payload,
  TransitionResult
>;
  • Guards stay boolean admission checks. Guard and onTransition contexts expose the allowed context.destinations; there is no toState, because a branching destination is unknown until the operation returns.
  • The lifecycle is unchanged: guard, source onExit, onTransition, commit the destination, destination onEnter. A false guard stops before onExit.
  • The selected destination is checkpointed with the callback's completion before the state commits, so a restart resumes the same choice without running the callback again.
  • Throwing, returning nothing or returning an undeclared destination is a failure handled by recovery; it never selects a branch implicitly. Returning an authored rejection destination is a successful business result.
  • While a transition runs, the snapshot keeps the source state and reports status: { kind: "running", transition, executionId } for UI progress.
  • applied dispatch results carry destination: the state the dispatch's execution recorded; use snapshot for the current condition.

A <FinalState> has no callbacks and no outgoing transitions. Committing it also sets status.kind to completed, atomically. Completed says nothing about business success. A new dispatch against a completed instance resolves to the completed outcome without running callbacks.

A service registers each flow once, ensures instances by ID, and maps every dispatch outcome at compile time (ADR 0090):

import visitorAccess, {
  type Dependencies,
} from "@scope/handlers/visitor-access";
import {
  createRuntime,
  instanceId,
} from "@ai-digital-factory/state-flow-runtime";
import { sqliteStorage } from "@ai-digital-factory/state-flow-storage-sqlite";

await using runtime = await createRuntime({
  storage: sqliteStorage({ path: "state-flow.db" }),
  shutdownTimeoutMs: 10_000,
});
// Rejects with DefinitionError for an invalid module.
const flow = await runtime.createFlow(visitorAccess, dependencies);

// Opens the instance, or creates it once. Rejects with DefinitionMismatchError when the stored
// instance belongs to another definition or has unresolved work from other handler code.
const instance = await flow.ensureInstance({
  instanceId: instanceId("visitor-1"),
});

// when → transition → [tags] → payload → run (ADR 0107, 0110). `when` offers only States with
// outgoing Transitions, `transition` only those leaving it, and the payload is typed for it.
// `run` resolves to the applied outcome; every refusal needs a handler, or `otherwise`, so a new
// refusal is a compile error until it is handled.
const result = await instance
  .when("guest")
  .transition("unlock-succeeds")
  .payload({ operatorSessionCookie: "…" })
  .run({
    blocked: () => ({ ok: false, reason: "blocked" }) as const,
    "invalid-payload": ({ issues }) =>
      ({ ok: false, reason: "invalid", issues }) as const,
    otherwise: ({ outcome }) => ({ ok: false, reason: outcome }) as const,
  });
if (!("ok" in result)) {
  // Applied: the State this dispatch recorded.
  console.log(result.destination);
}

// Runtime cleanup is awaited automatically when this scope exits.

ensureInstance is the only way to acquire an instance. A service that must not create one (for example, a webhook for an order that should already exist) checks first: await runtime.inspector.getSnapshot(instanceId) resolves to null for an unknown ID. Programmer and infrastructure errors (an unknown transition, a closed runtime, a failing disk, refusal handlers that miss a refusal) reject run; they are not outcomes. A builder that never reaches run dispatches nothing; the state-flow/dispatch-must-run lint rule flags it.

Across process boundaries (ADR 0108)

State Flow guarantees what happens inside one process. Reaching a server Flow from a browser or another service goes through the application's own route, queue or RPC; State Flow provides the values and types to carry across it:

import type {
  PayloadOf,
  RefusalOf,
  ResultOf,
} from "@ai-digital-factory/state-flow-runtime";

// The application's route: it carries the caller's tags into the dispatch.
app.post("/api/loans/:id/submit", async (req) => {
  const application = await applications.ensureInstance({
    instanceId: instanceId(req.params.id),
  });
  return application
    .when("draft")
    .transition("submit-application") // a resend after it committed is `state-mismatch`
    .tags({ traceId: req.header("x-trace-id") }) // typed by src/tags.ts; Cloud searches by it
    .payload(
      req.body.payload as PayloadOf<
        typeof loanApplication,
        "submit-application"
      >,
    )
    .run((refusal) => ({
      status: refusal.kind === "retry" ? 503 : 409,
      outcome: refusal.outcome,
    }));
});
  • Tags: a package declares the labels its calls carry in src/tags.ts (export const tagsSchema = z.strictObject({ traceId: z.string().optional() }): string fields, at most 10, never private or secret). ensureInstance({ tags }) and .tags(...) take them, typed and required as the schema says. Each call carries its own: every callback of the work it starts, including recovery, nested scopes and completion, receives them as context.tags, the history records them, and Cloud finds instances by them. Nothing carries over to a later call. Values fixed for an instance belong in its input.

  • State Flow owns the dispatch identity (ADR 0110): there is no request ID. Effects receive context.executionId, stable across recovery attempts, to use as the idempotency key for whatever they call.

  • Every refusal has a kind: retry (busy, recovery-pending: the same dispatch may be sent again later), failed, or rejected (everything else).

  • Applied outcomes carry the recorded Transition result; ResultOf<typeof module, "transition"> types it, and PayloadOf and RefusalOf type a route's request and refusals with import type only.

  • One owner per storage. A second runtime on the same storage rejects with OwnershipError; a crashed process releases it.

  • Recovery runs in the background with at most 4 attempts per callback (waits of 1 s, 5 s, 30 s). Budgets survive restarts. Opening an instance resumes interrupted work. When attempts run out:

    • an External Transition commits its unresolved State;
    • a safe step before the commit answers failed and the source State stays;
    • onEnter or children after the commit keep the applied State and record the failure;
    • resolveStartState falls back to the initial State.
  • Observation: await getSnapshot(), subscribe() and paged await history() per instance; runtime.inspector lists instances. Every read is asynchronous on the server; the browser client host keeps synchronous snapshots. State Flow Cloud shows them across services, read-only.

  • Handler changes: unresolved work started under different handler code (handlers, local helpers, dependencies.ts, declared dependencies) is not resumed (definition-mismatch with reason: "handler-revision"). Finish it with the previous build before deploying.

  • Stalls: if an infrastructure error stops execution, snapshot.stall shows it; fix the cause and call instance.handleRestart({ restarted, "not-restarted" }).restart() (or runtime.controls.restartRecovery(id)).

  • Shutdown: close({ timeoutMs }) rejects with ShutdownTimeoutError if callbacks ignore their AbortSignal; the storage stays owned until they settle or the process exits.

See ADR 0075 for the exact rules and what is not covered yet.

Composition: nested scopes (ADR 0095, 0096)

A Flow that places other Flows needs them registered first, each with its own dependencies:

await runtime.createFlow(fileUpload, uploadDependencies);
await runtime.createFlow(placeOrder, orderDependencies);
const workspaces = await runtime.createFlow(
  workspaceSession,
  workspaceDependencies,
);
const session = await workspaces.ensureInstance({
  instanceId: instanceId("user-1"),
});

const signedIn = session.scope("signed-in"); // compound State: its name
const upload = signedIn.scope("uploading", "report.pdf"); // FlowList member by key
const order = signedIn.scope("order-desk:order"); // parallel region: state:region

await upload
  .when("queued")
  .transition("send-file")
  .payload(null)
  .run({
    interrupted: () => "a parent Transition interrupted this request",
    inactive: () => "no active upload with that key",
    otherwise: ({ outcome }) => outcome,
  });
  • Each nested activation is a durable scope with its own State, executions and recovery; regions and members progress independently. (await session.getSnapshot()).scopes lists active scopes and exited ones that still retain unresolved work.
  • Scope handles resolve the current activation on every call. Their refusals add interrupted (a parent interrupt fenced this execution) and inactive (no activation at that path).
  • childWork="block" parent Transitions answer busy while descendant work is running or unresolved; nothing queues. While a parent execution runs, its descendants answer busy.
  • childWork="interrupt" aborts the descendants' context.signal and proceeds; interrupted safe work is dropped and never replayed. While a descendant runs an External Transition, an interrupt parent answers busy, so an external effect is never cut off midway.
  • A root's handler revision covers every placed Flow.

Schema contracts

Every durable transition module exports a Zod payloadSchema; use z.null() for an explicitly empty payload. Compile derives the service payload type from the schema and rejects missing declarations or mismatched handlers. The compiled module carries the schema so State Flow validates dynamic input before running a handler. Consumers must handle invalid-payload alongside every other dispatch outcome. The invalid-payload context exposes the rejected payload as unknown.

Use validation-only schemas. Async refinements are supported; State Flow rechecks admission after validation yields. Schema output must preserve the JSON input; coercion, defaults, transformations and silently stripped fields are rejected when they change that input. Schema refinements should be side-effect free; external I/O belongs in checkpointed handler callbacks. Domain-specific refinements belong in the handlers package; State Flow performs validation and maps its errors. Zod does not replace graph membership, freshness, authorization, or safe-replay decisions.

Scoped runtime lifetime

import { withRuntime } from "@ai-digital-factory/state-flow-runtime";

await withRuntime(
  {
    storage: sqliteStorage({ path: "state-flow.db" }),
    shutdownTimeoutMs: 5000,
  },
  async (runtime) => {
    const flow = await runtime.createFlow(compiled, dependencies);
    // Ensure instances and dispatch within this managed scope.
  },
);

The helper awaits application work and closes the runtime in finally, including when startup or response mapping fails. If work and shutdown both fail, an AggregateError preserves both failures. Applications decide their lifetime and signal handling; the library does not install global process handlers. Shutdown timeout retains ownership until active work settles.

Unresolved outcomes

An <ExternalTransition name="submit-order" unresolved="unconfirmed"> commits unconfirmed when its outcome cannot be established. The snapshot shows an ordinary State and history records outcome-unresolved. The application then checks the external system in its own code and dispatches an authored Transition out of unconfirmed, such as confirm-placed or confirm-not-placed. There is no operator action, resolve API or terminate.

handleRestart({ restarted, "not-restarted" }).restart() requires both explicit restart outcomes. runtime.controls holds only restartRecovery.

Infrastructure failures inside execution remain visible stalls requiring explicit intervention; restarting does not reset durable callback budgets. A storage failure stops the runtime instead (see Storage).

Exporting to State Flow Cloud

import { exportToCloud } from "@ai-digital-factory/state-flow-runtime";

const cloud = exportToCloud(runtime, {
  endpoint: "https://cloud.example.com/api/ingest",
  apiKey: process.env.STATE_FLOW_CLOUD_KEY!, // per Cloud environment, created in the Cloud UI
  service: "broker",
  replica: "infra",
  release: "v1.4.0",
  onError: (error) => logger.warn(error),
});
// On shutdown: await cloud.flush(); await cloud.stop();

The application pushes; Cloud never calls it (ADR 0105). Every Flow registered with createFlow is sent once so Cloud can draw it, including Flows registered after export starts. The runtime's own history is the outbox: a cursor stored in the same database advances only when Cloud stores a batch, so nothing is lost while Cloud is down and nothing waits for it. Export runs beside execution and never throws into the application. Fields declared private are redacted and secret fields are never recorded, so they never leave the service.

Deployment gate

Unfinished execution never resumes under different handler code (ADR 0076), so deploying over it would strand it. Run the deployment gate before a new build replaces the old one (ADR 0091, 0094). Instances that are Running or Recovering block a deployment; Ready instances waiting for their next event and Completed instances do not. These are State Flow Cloud's status filters: an empty result for those two filters is what the gate checks, but only the gate's check is protected against new work starting.

The running application performs the gate with runtime.handover():

// Called by the deployment system, for example through an authenticated admin endpoint.
app.post("/admin/deployment/handover", async (_request, response) => {
  try {
    const gate = await runtime.handover({ timeoutMs: 10_000 });
    switch (gate.outcome) {
      case "blocked":
        // Nothing changed: this build keeps running so the work can finish or be resolved.
        return response.status(409).json({ blockers: gate.blockers });
      case "handed-over":
        // The runtime is closed and the database released; stop this process now.
        response.status(200).json({ outcome: "handed-over" });
        setImmediate(() => process.exit(0));
        return;
    }
  } catch (error) {
    // A failed check or a timed-out shutdown is never permission to deploy.
    response.status(503).json({ error: String(error) });
    if (error instanceof ShutdownTimeoutError) {
      // The runtime admits no more work but still owns the database: exit so the supervisor
      // restarts this build, which recovers the interrupted work.
      setImmediate(() => process.exit(1));
    }
  }
});
# Deployment script: deploy only after a 200 response.
curl --fail -X POST https://app.internal/admin/deployment/handover || exit 1
start-new-build || start-old-build   # an abandoned deployment restarts the old build
  • blocked lists every blocking instance (ID, flow, state, status, reason) read from storage, including instances this process has not opened and beyond any listing page. It changes nothing: no waiting or budget reset.
  • Storage is read first; the decision is then made in one step from memory for every instance this runtime has opened, so work admitted while storage was read still blocks. When nothing blocks, handover stops admission and starts closing in that same step, so no dispatch, creation or recovery can start between the check and the handover. Later calls reject with RuntimeClosedError. It resolves handed-over once the storage is released. If the deployment is then abandoned, start the old build again; every remaining instance is Ready or Completed, so nothing needs repair.
  • It rejects when the check fails, and with ShutdownTimeoutError when the close times out (the storage stays owned until the process exits). Neither permits a deployment. createRuntime's shutdownTimeoutMs applies when timeoutMs is omitted.

There is no offline check (ADR 0109). After a crash or a manual stop, the next build opens the storage and calls handover() itself, or simply starts: opening an instance resumes its interrupted work.

There is no bypass, and nothing can stay blocked forever: recovery is bounded, and when attempts run out the work ends in an unresolved State, a failed dispatch or a recorded failure, all of which are Ready.

The deployment system must call the gate; the library cannot stop a process from being replaced without it. Passing the gate does not waive definition checks: a Ready instance still opens only under a compatible Flow definition.

Restarts and their limits

After a restart, callbacks durably recorded as completed are never run again and their results are reused; a callback that had started but not completed recovers by its shape (reconcile for an External Transition, replay for a safe callback) under the same operation ID, with the interrupted run counted against its attempt budget; callbacks that had not started run normally (ADR 0093). State Flow does not provide exactly-once external effects: an effect can complete before its callback's completion is recorded, which is what reconciliation is for. It does not infer business expiry from a restart or a delay; validity checks belong in handlers.

Consumer linting

Use serviceConfig or handlersConfig from the corresponding @ai-digital-factory/eslint-plugin-state-flow/eslint.*.config.js entrypoint and run lint in CI alongside compile and typecheck. These type-aware configurations enforce promise observation, require automatic runtime ownership through await using or withRuntime for services, prevent legacy execution bypasses, and keep runtime construction out of handlers. Explicit framework/operator lifecycle adapters may override the constructor restriction. Prepared dispatchers and unrelated transport methods are permitted. Fire-and-forget work requires explicit rejection handling; void alone does not satisfy the lint rule.

flow.ensureInstance({ instanceId }) opens an existing instance or reserves and creates it once, including for overlapping callers, and starts interrupted recovery. A Flow that declares inputSchema (src/<flow-id>/input.ts) takes its invocation input there, ensureInstance({ instanceId, input }): it is validated before anything is created, recorded with the instance and read by callbacks as context.input. Acquiring the same identity with different input rejects with InputError; omitting it opens the instance as recorded (ADR 0102). Its snapshot may be running, recovering or completed; acquiring an instance does not imply it is ready. Pending recovery continues independently while the runtime remains open, and dispatch does not retry caller requests or wait for background recovery.

await createRuntime({ storage, shutdownTimeoutMs }) opens the storage, rejecting with OwnershipError while another runtime owns it, and returns a standalone runtime. Use await using runtime = await createRuntime(...) to call operations sequentially and automatically await shutdown on normal completion or exceptions. TypeScript projects should include ESNext.Disposable in compilerOptions.lib. The configured shutdown timeout applies to disposal and to runtime.close(); explicit close({ timeoutMs }) overrides it. withRuntime remains the callback-style alternative. Applications with an existing framework lifecycle can explicitly close the runtime, with a deliberate override of the managed-runtime lint rule.

runtime.createFlow(compiled, dependencies) validates the module, including every handler's shape, and registers it before any handler runs. It rejects with DefinitionError for an invalid module and InputError for a duplicate registration; a failed registration does not reserve the flow name.

License

Proprietary software. All third-party use requires prior written permission from [email protected]. See LICENSE.