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

@ironflow/node

v0.60.0

Published

Node.js SDK for Ironflow event-driven backend platform - workers, serve handlers, and step execution

Readme

@ironflow/node

Node.js SDK for Ironflow, an event-driven backend platform. Provides workers (pull mode), serve handlers (push mode), step execution, projections, entity streams, subscriptions, KV store, file storage, config management, webhooks, auth management, agent primitives, and testing utilities.

Published as a public npm package under a commercial license — see LICENSE.

OpenTelemetry tracing

Install the optional @opentelemetry/api peer (^1.9.0) and configure your application's OpenTelemetry tracer provider and context manager before starting workers or serve(). The SDK uses the API only. It does not install an exporter or configure global tracing. Node.js 22 or later is required.

REST polling and streaming workers continue each job's W3C traceparent and tracestate. Push handlers read these fields from HTTP headers. Each execution creates a process consumer span, and each executed step.run creates a child step.run span. Memoized steps do not create spans. Parallel branches retain their execution ancestry. A poll request's ambient span never becomes the job's parent. Invalid parents start a new trace; valid unsampled parents still propagate.

Failures set error status. Yields and worker cancellation end spans without error status. Spans contain no baggage, payloads, secrets, or exception messages. Step names are recorded as ironflow.step.name; avoid putting sensitive data in step names. Span names and error events use bounded SDK labels.

Without the optional peer, import and execution continue normally without spans. Use your application's OpenTelemetry setup to select sampling and exporters.

Correlated application logs

ctx.logger adds five reserved fields to each call in push, polling, and streaming execution. run_id is the full dispatch run ID, function_id is the dispatch function ID, and attempt is the engine run attempt. step_id is the allocated memoization key inside an active callback, including escaped names and branch scope, or an empty string outside it. trace_id is the valid current execution trace ID, including unsampled traces, or an empty string without one. Step correlation works without OpenTelemetry installed.

The default console output prints all five fields and the full run ID prefix. Pass a Logger as userLogger to serve(), createWorker(), or createStreamingWorker() to use your application's sink. Its filtering, formatting, exceptions, and silence remain yours. userLogger: false silences execution logs. The existing logger option controls transport diagnostics. Execution-step diagnostics still share ctx.logger with callback logs and keep their existing messages and levels. Application attributes survive, with the five reserved fields taking precedence over collisions.

const worker = createWorker({
  functions: [processOrder],
  userLogger: applicationLogger,
});
// In processOrder's callback:
// logger.info('charged', { orderId: event.data.orderId });

For an explicit OTel Logs route, install your application's Logs SDK and the optional @opentelemetry/api peer. Obtain a logger from your provider and adapt it once. Tested versions are @opentelemetry/api 1.9.0 and @opentelemetry/api-logs and @opentelemetry/sdk-logs 0.220.0 on Node.js 22+.

import { createOTelLogger, createWorker } from '@ironflow/node';
import { LoggerProvider, SimpleLogRecordProcessor } from '@opentelemetry/sdk-logs';

// exporter is created and managed by your application.
const provider = new LoggerProvider({
  processors: [new SimpleLogRecordProcessor({ exporter })],
});
const worker = createWorker({
  functions: [processOrder],
  userLogger: createOTelLogger(provider.getLogger('my-app')),
});

The adapter emits once per call, with the original message body, mapped DEBUG/INFO/WARN/ERROR severity, application attributes, and explicit current OTel context for intrinsic trace/span correlation. It works without a global context manager. It has no console tee and imports no Logs package. Application providers control filtering, limits, timestamps after processing, and export. Use OTel-compatible attribute values. Explicit Error attributes become { name, message } without automatically including stacks. There is no implicit exception capture. Native custom sinks receive explicit errors unchanged.

Applications own provider setup, exporters, flush, shutdown, and destinations. Configuring tracing alone does not enable Logs export. Ironflow introduces no log collection, storage, network export, or provider setup. Do not bridge an already bridged sink a second time for the same destination.

Memoized callbacks do not run or log again. Other callback logs can repeat on resume. Logs are not checkpointed or deduplicated. Detached async work retains its inherited trace context but loses the step label after callback exit, cancellation, or timeout, even if user code keeps running. Arbitrary console calls and independently created loggers are not enriched.

Installation

npm install @ironflow/node

Requires Node.js 22+.

Table of Contents

  1. Defining Functions
  2. Step Primitives
  3. Saga Compensation
  4. Push Mode (serve)
  5. Pull Mode (createWorker)
  6. Streaming Worker
  7. Server-Side Client
  8. Entity Streams
  9. KV Store
  10. File Storage
  11. Config Management
  12. Auth Management
  13. Subscriptions
  14. Projections
  15. Webhooks
  16. Event Versioning (Upcasters)
  17. Error Handling
  18. Environment Variables
  19. Agent Primitives
  20. Testing

Defining Functions

Use createFunction(config, handler) to define a workflow function. The function is triggered by events and executes durable steps.

Basic function (untyped)

import { createFunction } from '@ironflow/node';

const processOrder = createFunction(
  {
    id: 'process-order',
    triggers: [{ event: 'order.placed' }],
  },
  async ({ event, step }) => {
    const validated = await step.run('validate', async () => {
      return validateOrder(event.data);
    });
    return { success: true, orderId: validated.orderId };
  }
);

With Zod schema validation

When you provide a schema, event.data is fully typed from the schema.

import { createFunction } from '@ironflow/node';
import { z } from 'zod';

const OrderSchema = z.object({
  orderId: z.string(),
  amount: z.number(),
  customerId: z.string(),
});

const processOrder = createFunction(
  {
    id: 'process-order',
    triggers: [{ event: 'order.placed' }],
    schema: OrderSchema,
  },
  async ({ event, step }) => {
    // event.data is typed as { orderId: string; amount: number; customerId: string }
    const receipt = await step.run('charge', async () => {
      return chargeCard(event.data.customerId, event.data.amount);
    });
    return { receiptId: receipt.id };
  }
);

FunctionConfig reference

All fields on the config object:

| Field | Type | Description | |-------|------|-------------| | id | string | Required. Unique function identifier. | | name | string | Display name. Defaults to id. | | description | string | Human-readable description shown in the dashboard. | | triggers | Trigger[] | Required. Array of event triggers (can be empty for invoke-only functions). | | retry | RetryConfig | Retry policy for failed runs. Sent to the server only for the fields you set. | | circuitBreaker | CircuitBreakerConfig | Push-endpoint circuit breaker overrides. | | throttle | ThrottleConfig | Soft start-rate limit. Runs over the limit wait in the queue. | | timeout | number | Function timeout in milliseconds. Unset means no per-function budget; a push request then uses the engine push timeout (10 s). | | concurrency | ConcurrencyConfig | Concurrency control. | | debounce | DebounceConfig | Debounce configuration — collapses rapid-fire events into a single invocation. Fields: periodMs, key?, maxWaitMs?. | | mode | "push" \| "pull" | Preferred execution mode. | | actorKey | string | JSON path for an actor key (e.g., "event.data.customerId"). The server stores and returns it. Dispatch does not use it for routing yet. | | schema | ZodType | Zod schema for event data validation and type inference. | | secrets | string[] | Secret names this function requires (resolved by the engine). | | stepTimeout | string | Default timeout for all step.run() calls (e.g., "30s", "5m"). | | recording | boolean | Legacy audit toggle. true is equivalent to recordingProfile: "all". | | recordingProfile | "all" \| "run_lifecycle" \| "steps" | Workflow audit families to capture. A profile enables recording by itself. | | metadata | Record<string, unknown> | Arbitrary metadata attached to the function definition. | | cancelOn | CancelOnConfig[] | Auto-cancel in-flight runs when a matching event arrives. Each spec is { event: string; match: string }; OR semantics across specs. |

Trigger fields:

| Field | Type | Description | |-------|------|-------------| | event | string | Event name pattern (e.g., "order.placed"). | | expression | string | Optional CEL expression for filtering. | | cron | string | Cron schedule (e.g., "0 9 * * *" for 9am daily). |

RetryConfig fields:

| Field | Type | Default | Description | |-------|------|---------|-------------| | maxAttempts | number | 25 | Total attempts, the first included. | | initialDelayMs | number | 1000 | Initial delay between retries. | | backoffFactor | number | 2.0 | Backoff multiplier. | | maxDelayMs | number | 300000 | Maximum delay between retries. | | onExhausted | "pause" \| "fail" | "pause" | What happens when a retryable failure has used every attempt. "pause" holds the run, with its completed steps, until you resume it. "fail" ends the run and runs its compensations. A non-retryable error always fails at once. |

The defaults are the server's (spec.engine.retry); a field you leave out is not sent, and the server applies its value when each run is created. A function registered by an earlier SDK version keeps the retry values stored with it until it registers again.

Throw RetryAfterError to ask for a specific delay, for example when an API answers 429 with Retry-After. The engine waits that long instead of the computed backoff, capped at maxDelayMs:

import { RetryAfterError } from '@ironflow/node';

await step.run('call-api', async () => {
  const res = await fetch(url);
  if (res.status === 429) {
    // Retry-After is delta-seconds or an HTTP-date; fall back to 30s if it is absent or unparseable.
    const header = res.headers.get('retry-after');
    const seconds = Number(header);
    const delayMs = header && Number.isFinite(seconds) ? seconds * 1000 : Date.parse(header ?? '') - Date.now();
    throw new RetryAfterError('rate limited', Number.isFinite(delayMs) ? delayMs : 30_000);
  }
  return res.json();
});

CircuitBreakerConfig fields (all optional; zero or unset keeps the server default):

| Field | Type | Default | Description | |-------|------|---------|-------------| | failureThreshold | number | 5 | Consecutive failed attempts that open the circuit. | | openDurationMs | number | 60000 | First open window. Each failed probe doubles it. | | maxOpenDurationMs | number | 600000 | Cap for the doubling window. Must be at least openDurationMs. |

ThrottleConfig fields:

| Field | Type | Description | |-------|------|-------------| | limit | number | Runs allowed to start per period. At least 1. | | periodMs | number | Window length in milliseconds. At least 1000. | | key | string | Path into the event data to throttle per value. Omit to throttle the whole function. |

A throttle delays the start of new runs only. Retries and resumed runs are not throttled, and no run is dropped.

ConcurrencyConfig fields:

| Field | Type | Description | |-------|------|-------------| | limit | number | Maximum concurrent executions. | | key | string | Path into the event data payload for grouping (e.g., "customerId"). |

Full config example

const processOrder = createFunction(
  {
    id: 'process-order',
    name: 'Process Order',
    triggers: [
      { event: 'order.placed' },
      { event: 'order.retry', expression: 'event.data.priority > 5' },
      { cron: '0 */6 * * *', event: 'scheduled.cleanup' },
    ],
    retry: { maxAttempts: 5, initialDelayMs: 2000, backoffFactor: 3 },
    timeout: 300000,
    concurrency: { limit: 10, key: 'customerId' }, // path into event.data
    mode: 'pull',
    actorKey: 'event.data.customerId',
    schema: OrderSchema,
    secrets: ['STRIPE_SECRET_KEY', 'SENDGRID_API_KEY'],
    stepTimeout: '30s',
    recordingProfile: 'steps',
  },
  async ({ event, step, secrets }) => {
    const apiKey = secrets.get('STRIPE_SECRET_KEY');
    // ...
  }
);

Step Primitives

Every step is durable and memoized. If the workflow retries, previously completed steps are skipped and their stored results are returned.

step.run(name, fn, options?)

Execute a memoized step. Use for any non-idempotent operation (API calls, payments, emails).

const processOrder = createFunction(
  { id: 'process-order', triggers: [{ event: 'order.placed' }] },
  async ({ event, step }) => {
    // Basic usage
    const result = await step.run('charge-card', async () => {
      return chargeCard(event.data.amount);
    });

    // With timeout override
    const enriched = await step.run('enrich-data', async () => {
      return callSlowApi(event.data.id);
    }, { timeout: '60s' });

    return { transactionId: result.id, enriched };
  }
);

Options:

| Field | Type | Description | |-------|------|-------------| | timeout | string | Step timeout (e.g., "30s", "5m", "1h"). Overrides function-level stepTimeout. |

step.sleep(name, duration)

Durable sleep that survives process restarts and server upgrades.

const delayedNotification = createFunction(
  { id: 'delayed-notify', triggers: [{ event: 'user.signup' }] },
  async ({ event, step }) => {
    await step.run('send-welcome', async () => {
      return sendWelcomeEmail(event.data.email);
    });

    // Durable sleep - workflow pauses and resumes after duration
    await step.sleep('wait-for-trial', '7d');

    await step.run('send-trial-ending', async () => {
      return sendTrialEndingEmail(event.data.email);
    });
  }
);

Duration formats: "30s", "5m", "1h", "7d", or milliseconds as a number.

step.sleepUntil(name, date)

Sleep until a specific point in time.

const scheduledTask = createFunction(
  { id: 'scheduled-task', triggers: [{ event: 'task.scheduled' }] },
  async ({ event, step }) => {
    // Sleep until a specific Date object
    await step.sleepUntil('wait-until-date', new Date('2025-12-31T00:00:00Z'));

    // Or an ISO string
    await step.sleepUntil('wait-until-deadline', event.data.deadline);

    await step.run('execute', async () => {
      return executeTask(event.data.taskId);
    });
  }
);

step.waitForEvent(name, filter)

Wait for an external event to arrive. The workflow pauses durably until a matching event is emitted.

An event stored after the run was created can satisfy this wait even if it arrives before the step parks. Ironflow checks retained events in the same environment, oldest first by server storage time, up to the wait deadline. An event consumed by an earlier completed wait in this run cannot satisfy a later gate. Neither can a same-name event stored before an earlier completed wait for that name ended. The event that started the run cannot satisfy its own wait. Events deleted by retention are unavailable to this check.

const approvalWorkflow = createFunction(
  { id: 'approval-flow', triggers: [{ event: 'approval.requested' }] },
  async ({ event, step }) => {
    await step.run('notify-approver', async () => {
      return sendApprovalRequest(event.data.approverId);
    });

    // Wait for the approval event (default timeout: 7 days)
    const approval = await step.waitForEvent('wait-approval', {
      event: 'approval.received',
      match: 'data.requestId',  // JSON path for matching
      timeout: '48h',
    });

    if (approval.data.approved) {
      await step.run('process-approved', async () => {
        return processApproval(event.data.requestId);
      });
    }

    return { approved: approval.data.approved };
  }
);

EventFilter fields:

| Field | Type | Default | Description | |-------|------|---------|-------------| | event | string | -- | Event name to wait for. | | match | string | -- | JSON path for correlating events. | | matchValue | string | -- | Non-empty literal compared at match time. Omitted or empty snapshots the triggering event. Requires match. | | timeout | Duration | "7d" | How long to wait before timing out. | | onTimeout | "fail" \| "return-null" | "fail" | Return a memoized null on timeout when opted in. | | payload | unknown | -- | Stored as the waiting step's input, visible via getRunSteps and the dashboard. Does not affect matching. |

By default, waitForEvent returns the matching event and a deadline fails the run without resuming the handler. Set onTimeout: "return-null" to resume with a memoized null instead. The default type stays Promise<IronflowEvent<T>>; the opt-in type is Promise<IronflowEvent<T> | null>. The policy survives restarts. approve() keeps its fail-on-timeout default.

Yielding steps (sleep, sleepUntil, waitForEvent, invoke, invokeAsync) must propagate their internal signal. If a handler or parallel branch swallows it and returns or attempts another durable operation, the SDK fails nonretryably with an actionable error, including under allSettled. Catch ordinary errors inside the step.run callback. The guard cannot prevent arbitrary side effects performed directly inside the catch block before control returns to the SDK.

Function trigger events, getEvent(), streams.read(), and waitForEvent results expose emittedBy. It is the authenticated emitter that the engine recorded, for example apikey:<id> or user:<id>. The engine sets it from the credential of the caller, so the event body cannot change it. It is undefined when the engine reports none. An operator with runs:cancel can inject or patch a step output, so emittedBy proves the emitter only for a step that an event resolved.

step.invoke(functionId, input?, options?)

Call another Ironflow function and wait for its result. Creates a child run.

const orchestrator = createFunction(
  { id: 'orchestrator', triggers: [{ event: 'workflow.start' }] },
  async ({ event, step }) => {
    // Invoke and wait for result (default timeout: 30s)
    const result = await step.invoke('process-payment', {
      orderId: event.data.orderId,
      amount: event.data.amount,
    });

    // With custom timeout
    const report = await step.invoke('generate-report', {
      orderId: event.data.orderId,
    }, { timeout: '5m' });

    return { paymentResult: result, report };
  }
);

step.invokeAsync(functionId, input?)

Fire-and-forget: trigger another function without waiting for its result. Returns the child run ID.

invokeAsync is already durable. Call it directly, outside step.run, including when invoking children in a loop. A completed step.run skips its callback on replay, so the inner invocation counter stops advancing. Later iterations can reuse an earlier child's run ID without starting a new child. The same rule applies to spawn({ await: false }): call spawn outside step.run.

If upgrading from a version where spawn({ await: false }) used a step.run wrapper, finish or stop affected parent runs with the old worker before switching versions. Invocation IDs still use the same function counter, but removing the wrapper changes which calls advance that counter on replay. Existing partial fan-outs are not repaired automatically; reconcile their child runs before retrying work.

const orderPipeline = createFunction(
  { id: 'order-pipeline', triggers: [{ event: 'order.placed' }] },
  async ({ event, step }) => {
    // Fire and forget - does not block
    const { runId } = await step.invokeAsync('send-confirmation-email', {
      orderId: event.data.orderId,
      email: event.data.email,
    });

    return { emailRunId: runId };
  }
);

step.parallel(name, branches, options?)

Execute multiple branches in parallel. Each branch receives its own scoped step client with isolated step IDs.

const enrichUser = createFunction(
  { id: 'enrich-user', triggers: [{ event: 'user.created' }] },
  async ({ event, step }) => {
    const [profile, creditScore, preferences] = await step.parallel(
      'fetch-all',
      [
        async (s) => s.run('fetch-profile', () => fetchProfile(event.data.userId)),
        async (s) => s.run('fetch-credit', () => fetchCreditScore(event.data.userId)),
        async (s) => s.run('fetch-prefs', () => fetchPreferences(event.data.userId)),
      ]
    );

    return { profile, creditScore, preferences };
  }
);

ParallelOptions:

| Field | Type | Default | Description | |-------|------|---------|-------------| | concurrency | number | unlimited | Maximum concurrent branches. | | onError | "failFast" \| "allSettled" | "failFast" | "failFast": first failure cancels pending branches. "allSettled": all branches complete, errors in results. | | expectScopedClient | boolean | true | Set false for a fan-out that deliberately has nothing to memoize, to silence the "no branch used the scoped step client" warning. Suppresses the diagnostic only; durability is unchanged. |

// With concurrency limit and allSettled error handling
const results = await step.parallel(
  'batch-process',
  items.map((item) => async (s) => {
    return s.run(`process-${item.id}`, () => processItem(item));
  }),
  { concurrency: 5, onError: 'allSettled' }
);

step.map(name, items, fn, options?)

Parallel map over an array of items. Convenience wrapper around step.parallel.

const batchProcessor = createFunction(
  { id: 'batch-process', triggers: [{ event: 'batch.ready' }] },
  async ({ event, step }) => {
    const results = await step.map(
      'process-items',
      event.data.items,
      async (item, s, index) => {
        return s.run(`process-${index}`, () => processItem(item));
      },
      { concurrency: 3 }
    );

    return { processed: results.length };
  }
);

step.compensate(stepName, fn)

Register a compensation function (saga rollback) for a previously completed step. Compensations run automatically in reverse order on terminal (non-retryable) failures.

const transferFunds = createFunction(
  { id: 'transfer-funds', triggers: [{ event: 'transfer.requested' }] },
  async ({ event, step }) => {
    const debit = await step.run('debit', async () => {
      return debitAccount(event.data.fromAccount, event.data.amount);
    });
    step.compensate('debit', async () => {
      await creditAccount(event.data.fromAccount, event.data.amount);
    });

    const credit = await step.run('credit', async () => {
      return creditAccount(event.data.toAccount, event.data.amount);
    });
    step.compensate('credit', async () => {
      await debitAccount(event.data.toAccount, event.data.amount);
    });

    return { debitRef: debit.ref, creditRef: credit.ref };
  }
);

step.publish(topic, data, options?)

Publish a message to a developer pub/sub topic. The publish is memoized like any other step. options takes an idempotencyKey for server-side deduplication.

const orderProcessor = createFunction(
  { id: 'order-processor', triggers: [{ event: 'order.placed' }] },
  async ({ event, step }) => {
    const result = await step.run('process', async () => {
      return processOrder(event.data);
    });

    // Publish to a topic (does NOT trigger workflow functions)
    await step.publish('order-notifications', {
      orderId: event.data.orderId,
      status: 'processed',
    });

    return result;
  }
);

Saga Compensation

Compensations provide automatic rollback for distributed transactions. When a terminal (non-retryable) failure occurs, all registered compensations run in reverse order. Each compensation is itself a durable, memoized step.

import { createFunction, NonRetryableError } from '@ironflow/node';

const bookTrip = createFunction(
  { id: 'book-trip', triggers: [{ event: 'trip.requested' }] },
  async ({ event, step }) => {
    // Step 1: Book flight
    const flight = await step.run('book-flight', async () => {
      return bookFlight(event.data.flightId);
    });
    step.compensate('book-flight', async () => {
      await cancelFlight(flight.confirmationId);
    });

    // Step 2: Book hotel
    const hotel = await step.run('book-hotel', async () => {
      return bookHotel(event.data.hotelId, event.data.dates);
    });
    step.compensate('book-hotel', async () => {
      await cancelHotel(hotel.confirmationId);
    });

    // Step 3: Book car rental (if this fails with a non-retryable error,
    // both hotel and flight compensations run in reverse order)
    const car = await step.run('book-car', async () => {
      const result = await bookCar(event.data.carId);
      if (!result.available) {
        throw new NonRetryableError('Car not available');
      }
      return result;
    });
    step.compensate('book-car', async () => {
      await cancelCar(car.confirmationId);
    });

    return { flight, hotel, car };
  }
);

Key behaviors:

  • Compensations only run on terminal failures: a non-retryable error, or a retryable error on the last attempt when retry.onExhausted is "fail". With "pause" (the server default) the run is held for resume and nothing is undone. ctx.run.attempt, ctx.run.maxAttempts and ctx.run.onExhausted show which attempt this is.
  • They run in reverse registration order (last registered runs first).
  • Each compensation is recorded as a durable step (compensate:<stepName>).
  • If a compensation itself fails, the error is logged but remaining compensations still run.

Push Mode (serve)

The serve() function creates a universal HTTP handler for serverless deployment. It works with any framework that uses the Fetch Request/Response API or Node.js IncomingMessage/ServerResponse.

ServeConfig reference

| Field | Type | Description | |-------|------|-------------| | functions | IronflowFunction[] | Required. Functions to handle. | | projections | IronflowProjection[] | Logs a warning -- use createWorker for projections. | | signingKey | string | HMAC-SHA256 signing key for request verification. Verification needs the raw request body: do not run a JSON body parser such as express.json() before serve(). | | skipVerification | boolean | Skip signature verification (dev only). | | logger | Logger \| false | Transport diagnostic logger or false to disable. | | userLogger | Logger \| false | Application execution logger or false to silence it. | | environment | string | Target environment ID (default: IRONFLOW_ENV). Unset sends no environment header. | | eventDefinitions | EventDefinitionRegistry | Registry for automatic event upcasting. | | serverUrl | string | Ironflow server URL (for emitting webhook events). | | webhooks | IronflowWebhook[] | Webhook sources to handle. |

There is no apiKey field. Both authenticated hops out of serve() -- step callbacks such as step.publish, and the webhook transform result posted to /ironflow.v1.IronflowService/Emit -- read the IRONFLOW_API_KEY env var, matching the Go SDK's serve handler. Neither route is public, so without that variable set they fail outside dev mode.

Next.js App Router

// app/api/ironflow/route.ts
import { serve } from '@ironflow/node';
import { processOrder } from '@/functions/process-order';

export const POST = serve({
  functions: [processOrder],
  signingKey: process.env.IRONFLOW_SIGNING_KEY,
});

Express

import express from 'express';
import { serve } from '@ironflow/node';
import { processOrder } from './functions/process-order.js';

const app = express();

app.post('/api/ironflow', serve({
  functions: [processOrder],
  signingKey: process.env.IRONFLOW_SIGNING_KEY,
}));

app.listen(3000);

Hono

import { Hono } from 'hono';
import { serve } from '@ironflow/node';
import { processOrder } from './functions/process-order.js';

const app = new Hono();

const handler = serve({
  functions: [processOrder],
  signingKey: process.env.IRONFLOW_SIGNING_KEY,
});

// Hono passes a context, not a Request. Hand `serve` the raw Fetch Request.
app.post('/api/ironflow', (c) => handler(c.req.raw));

export default app;

Pull Mode (createWorker)

Workers poll the Ironflow server for jobs via REST HTTP. Use for long-running tasks with no timeout limits.

WorkerConfig reference

| Field | Type | Default | Description | |-------|------|---------|-------------| | serverUrl | string | http://localhost:9123 | Ironflow server URL. | | functions | IronflowFunction[] | -- | Required. Functions this worker handles. | | projections | IronflowProjection[] | -- | Projections to run alongside functions. | | maxConcurrentJobs | number | 10 | Maximum concurrent job executions. | | heartbeatInterval | number | 30000 | Heartbeat interval in ms. | | reconnectDelay | number | 5000 | Reconnect delay in ms. | | pollWaitSeconds | number | 20 | Seconds the server may hold an empty job poll open, so a new job reaches the worker at once. 0 disables long polling; the server caps it at 25. A proxy with a read timeout below this value must be raised, or this value lowered. REST polling worker only -- createStreamingWorker ignores it. | | labels | Record<string, string> | -- | Worker labels for routing. | | logger | Logger \| false | -- | Transport diagnostic logger or false to disable. | | userLogger | Logger \| false | -- | Application execution logger or false to silence it. | | environment | string | IRONFLOW_ENV | Target environment ID. Unset sends no environment header. | | eventDefinitions | EventDefinitionRegistry | -- | Registry for automatic event upcasting. | | apiKey | string | IRONFLOW_API_KEY env | API key for authentication. Empty or unset falls back to the env var. | | checkpointInterval | number | 1000 | Debounce window in ms for checkpointing completed steps to the server while a job is still running; 0 disables. Without it a killed worker loses all in-flight progress and the reclaimed run re-executes every step. REST polling worker only -- createStreamingWorker ignores it. | | drainTimeout | number | 30000 | How long drain() waits in ms for active jobs before it cancels them. 0 or less uses the default. On an engine shutdown message, createStreamingWorker uses the drain timeout in the message when the message has one. |

Worker interface

| Method | Description | |--------|-------------| | start() | Start the worker. Blocks until stopped. Auto-reconnects on failure. | | drain() | Stop polling, wait up to drainTimeout (default 30 seconds) for active jobs, then cancel the remainder. Then wait, with no time limit, for projection runners to save the events they accepted. Pull workers also drain on SIGINT and SIGTERM. When all workers in the process have drained, the process exits unless your app also listens for that signal. | | stop() | Force stop immediately. Cancels all active jobs. |

import { createWorker } from '@ironflow/node';
import { processOrder, sendNotification } from './functions.js';
import { orderTotals } from './projections.js';

const worker = createWorker({
  serverUrl: 'http://localhost:9123',
  functions: [processOrder, sendNotification],
  projections: [orderTotals],
  maxConcurrentJobs: 20,
  labels: { region: 'us-east-1' },
  apiKey: process.env.IRONFLOW_API_KEY,
});

// The pull worker drains automatically on SIGINT and SIGTERM, then exits.
await worker.start();

Streaming Worker

For low-latency bidirectional streaming via ConnectRPC. Same WorkerConfig as createWorker, but uses gRPC bidirectional streaming instead of HTTP polling.

Import from the separate @ironflow/node/worker-streaming entry point to avoid loading protobuf dependencies unless needed.

import { createStreamingWorker } from '@ironflow/node/worker-streaming';
import { processOrder } from './functions.js';

const worker = createStreamingWorker({
  serverUrl: 'http://localhost:9123',
  functions: [processOrder],
  maxConcurrentJobs: 10,
});

// The streaming worker also drains on SIGINT and SIGTERM, then exits.
await worker.start();

Requires optional dependencies: @bufbuild/protobuf, @connectrpc/connect, @connectrpc/connect-node.


Server-Side Client

The HTTP client for interacting with the Ironflow server from your backend code.

IronflowClientConfig

| Field | Type | Default | Description | |-------|------|---------|-------------| | serverUrl | string | IRONFLOW_SERVER_URL, then http://localhost:9123 | Server URL. | | apiKey | string | IRONFLOW_API_KEY env | API key for authentication. Empty or unset falls back to the env var. | | environment | string | -- | Sent as X-Ironflow-Environment-ID on REST and Connect requests. KV, config and secrets requests do not send it. Unset sends no header: the server uses the API key's environment, or the default one when auth is off. The client does not read IRONFLOW_ENV. | | timeout | number | 30000 | Request timeout in ms. | | onError | OnErrorHandler | -- | Global error handler (optional). | | retry | ClientRetryConfig | 3 attempts, 100 ms, factor 2, max 10 s | Retry with backoff. A call that changes nothing is retried on a network error, timeout, 408, 429 or 5xx; all other calls on 429 only. Honors Retry-After. maxAttempts: 1 disables. |

Creating a client

import { createClient } from '@ironflow/node';

const client = createClient({
  serverUrl: 'http://localhost:9123',
  apiKey: process.env.IRONFLOW_API_KEY,
});

Every HTTP request carries X-Ironflow-SDK: node/<version>, and so do the WebSocket handshakes of the KV watch, config watch and subscription clients. The server does not read it. When a newer SDK calls an older server that lacks the call, the SDK throws a non-retryable IronflowError with code SERVER_TOO_OLD that names the first server version that has it. Two calls do this: the Consumer Group Stream and the projection runner's lease (AcquireProjectionLease). The error is a ServerTooOldError. Each package entry bundles its own copy of the class, so match err.code === "SERVER_TOO_OLD" rather than instanceof.

emit(eventName, data, options?)

Emit an event to trigger workflow functions.

const result = await client.emit('order.placed', {
  orderId: '123',
  amount: 99.99,
});
console.log('Run IDs:', result.runIds);
console.log('Event ID:', result.eventId);

EmitOptions:

| Field | Type | Description | |-------|------|-------------| | version | number | Event schema version (default: 1). | | idempotencyKey | string | Prevent duplicate processing. | | metadata | Record<string, unknown> | Additional metadata. |

await client.emit('order.placed', { orderId: '123' }, {
  version: 2,
  idempotencyKey: 'order-123-placed',
  metadata: { source: 'api', traceId: 'abc' },
});

emitSync(eventName, data, options?)

Emit and wait for every run the event triggers. Returns EmitSyncResult[], one element per matched trigger; an event that matches nothing returns [].

Run outcomes are never thrown -- with N results there is no unambiguous choice of which failure to raise. Inspect status, error and waitTimedOut per element; transport, protocol and validation errors still throw. A wait timeout leaves the durable run active.

const results = await client.emitSync('order.placed', { orderId: '123' }, {
  timeout: 30000,
  idempotencyKey: 'order-123-placed',
});
for (const r of results) {
  console.log(r.runId, r.functionId, r.status, r.output, r.waitTimedOut);
}

invoke(functionId, options)

Run one function by ID and wait for its single result, over InvokeFunctionSync. Because there is exactly one run, this one does throw RunFailedError, RunCancelledError, or non-retryable RunWaitTimeoutError, imported from @ironflow/core (ADR 0067).

const result = await client.invoke('process-order', {
  data: { orderId: '123' },
  timeout: 30000,           // server-side wait budget, not a transport deadline
  idempotencyKey: 'order-123',
});
console.log(result.runId, result.status, result.output, result.durationMs);

Aborting the call, or dropping the connection, cancels the run server-side. Node's built-in fetch enforces a ~300 s undici headers timeout that no AbortController overrides, so a wait budget above ~295 s dies at the socket and the run is cancelled -- use emit() plus a subscription for waits that long.

triggerBatch(events)

Emit many events in one round trip. Returns one TriggerBatchResult per event, in order. A failed item carries error (code and message) and no event ID; the other items still emit.

const results = await client.triggerBatch([
  { event: 'order.placed', data: { orderId: '1' } },
  { event: 'order.placed', data: { orderId: '2' }, idempotencyKey: 'order-2' },
]);

Reading stored events

// Keyset-paginated page of the event log
const page = await client.listEvents({ name: 'order.placed', limit: 50 });
console.log(page.events, page.nextCursor);

// One stored event
const event = await client.getEvent('evt_abc123');

// Distinct event names with counts
const { names } = await client.listEventNames();

getRun(runId)

Get a run by its ID.

const run = await client.getRun('run_abc123');
console.log(run.status);    // "completed" | "running" | "failed" | "cancelled" | ...
console.log(run.output);    // Function return value (if completed)
console.log(run.error);     // { message, code } (if failed)

listRuns(options?)

List runs with optional filtering and pagination.

const result = await client.listRuns({
  functionId: 'process-order',
  status: 'failed',
  limit: 25,
  cursor: 'next_page_cursor',
});
console.log(result.runs);       // Run[]
console.log(result.totalCount); // number
console.log(result.nextCursor); // string | undefined

cancelRun(runId, reason?)

Cancel a running workflow.

const run = await client.cancelRun('run_abc123', 'no longer needed');

resumeRun(runId, fromStep?)

Resume a paused or failed run.

await client.resumeRun('run_abc123');
await client.resumeRun('run_abc123', 'charge-card');

deleteRun(runId) / deleteRuns(filter)

Permanently delete terminal runs and their steps. Irreversible; requires the runs:delete action (admin by default). A run still in flight is refused with failed_precondition — cancel it first.

await client.deleteRun('run_abc123');

// Bulk delete; at least one filter field is required. The server stops at
// 10,000 per call — re-issue the same filter until it returns 0.
const deleted = await client.deleteRuns({
  functionId: 'process-order',
  status: 'completed',
  until: new Date('2026-01-01'),
});

redactEvent(eventId) / redactStep(stepId) / redactRun(runId)

Irreversibly replace a stored payload with a {"$redacted": true, ...} placeholder, keeping the row's id, ordering and version. Requires events:redact (admin by default). redactStep and redactRun need a terminal run; stepId is the step's row id, not its name. Use isRedacted(data) (re-exported from @ironflow/core) in reducers before trusting a payload.

await client.redactEvent('evt_abc123');
await client.redactStep('step_xyz');
await client.redactRun('run_abc123');

Error envelopes are replaced whole. Run redaction scrubs the run and child step errors while leaving step outputs unchanged. Step redaction scrubs its error and the parent run error; sibling errors stay. Stored error placeholders survive later whole-row saves.

patchStep(stepId, output, reason?)

Hot-patch a step's output. Useful for debugging or correcting bad data.

await client.patchStep('step_xyz', { correctedValue: 42 }, 'fix bad data');

getRunSteps(runId) / getRunStreams(runId)

const { steps, count } = await client.getRunSteps('run_abc123');
const { entityIds } = await client.getRunStreams('run_abc123');

Time-travel debugging

Requires recordingProfile: "all" (or legacy recording: true) on the function. Reconstructs historical run state from the audit record.

const snapshot = await client.getRunStateAt('run_abc123', new Date(Date.now() - 3600_000));
const timeline = await client.getRunTimeline('run_abc123');
const output   = await client.getStepOutputAt('run_abc123', 'step_xyz', new Date());

getAuditTrail(runId) / listAuditEvents(options?)

const trail   = await client.getAuditTrail('run_abc123');           // one run: { events, totalCount, nextCursor }
const page    = await client.listAuditEvents({ eventType: 'run.failed', limit: 50 });

Scoped Injection

Pause running workflows at step boundaries, inspect and modify step outputs, then resume:

// Pause a running workflow
const result = await client.pauseRun("run_abc123");
console.log(result.status); // "pause_requested" or "paused"

// View completed steps while paused
const state = await client.getPausedState("run_abc123");
for (const step of state.steps) {
  console.log(step.name, step.output, step.injected);
}

// Inject modified output for a step
await client.injectStepOutput("run_abc123", "step_xyz", { corrected: true }, "Manual fix");

// Resume the workflow
await client.resumeRun("run_abc123");

listFunctions()

List all registered functions.

const functions = await client.listFunctions();

listWorkers()

List all connected workers.

const workers = await client.listWorkers();

Function lifecycle and versioning

Every registerFunction writes a new version, so a bad deploy can be rolled back from the registry without redeploying code.

await client.registerFunction({
  id: 'process-order',
  triggers: [{ event: 'order.placed' }],
  preferredMode: 'pull',
});

const fn = await client.getFunction('process-order');
await client.updateFunctionStatus('process-order', 'paused');   // pause dispatch
await client.deleteFunction('process-order');

const history = await client.listFunctionHistory('process-order', { limit: 20 });
const older   = await client.getFunctionAtVersion('process-order', 3);
await client.rollbackFunction('process-order', 3, 'bad concurrency key');

Consumer groups (client.consumerGroups)

Manage the durable group definition; join it from a subscription client.

const group = await client.consumerGroups.create({
  name: 'order-processors',
  pattern: 'events:order.*',
  ackMode: 'manual',
  maxInflight: 50,
});

const groups = await client.consumerGroups.list();
const one    = await client.consumerGroups.get('order-processors');
await client.consumerGroups.update('order-processors', { maxInflight: 100 });
await client.consumerGroups.delete('order-processors');

health()

Server health check. Returns the status string.

const status = await client.health();
console.log(status); // "healthy"

ready()

Readiness probe. health() is liveness; ready() reads GET /ready, which checks the database, NATS and the engine streams. A server that is not ready makes it throw an IronflowError with code NOT_READY, status 503 and the failing dependencies in details.issues, such as stream:PUBSUB. It makes one attempt and does not retry.

const { status, warnings } = await client.ready();
console.log(status); // "ready"

publish(topic, data, options?)

Publish a message to a developer pub/sub topic. Unlike emit(), this does not trigger workflow functions.

const result = await client.publish('notifications', {
  userId: '123',
  message: 'Hello!',
});
console.log(result.eventId);  // string
console.log(result.sequence); // number

PublishOptions:

| Field | Type | Description | |-------|------|-------------| | idempotencyKey | string | Prevent duplicate publishing. |

listTopics()

List all active developer pub/sub topics.

const topics = await client.listTopics();
for (const t of topics) {
  console.log(t.name, t.messageCount, t.consumerCount);
}

getTopicStats(topic)

Get detailed statistics for a specific topic.

const stats = await client.getTopicStats('notifications');
console.log('Messages:', stats.messageCount);
console.log('Lag:', stats.lag);
console.log('Consumers:', stats.consumerCount);
console.log('First seq:', stats.firstSeq, 'Last seq:', stats.lastSeq);

Projection administration

Read materialized state, list/inspect projection status, and drive rebuilds.

// Get current state of a managed projection
const { state, version, lastEventTime } = await client.projections.get<MyState>('order-summary');

// Per-partition projections
const partitioned = await client.projections.get('order-detail-view', { partition: 'order-123' });

// Operational status
const statuses = await client.projections.list();
const status   = await client.projections.getStatus('order-summary');

// Partitions of a partitioned projection
const parts = await client.projections.listPartitions('order-detail-view', { limit: 50 });

// Lifecycle
await client.projections.pause('order-summary');
await client.projections.resume('order-summary');
await client.projections.delete('order-summary');

// Rebuild
const job   = await client.projections.rebuild('order-summary');
const jobNow = await client.projections.getRebuildJob('order-summary');
await client.projections.cancelRebuild('order-summary');

// Archived definitions, newest first. The current definition is not in the history.
const history = await client.projections.listHistory('order-summary', { limit: 20 });
const revision = await client.projections.getRevision('order-summary', 3);

// Read-your-writes — wait until a projection has caught up.
// `streams.append` returns no NATS sequence under the transactional outbox;
// resolve eventId → seq with waitForEvent first, then wait on that seq.
const { eventId } = await client.streams.append(orderId, event);
const { targetSeq } = await client.projections.waitForEvent(eventId, 'order-detail-view', { timeoutMs: 5000 });
await client.projections.waitForCatchup('order-detail-view', {
  minSeq: targetSeq,
  partition: orderId,
  timeoutMs: 5000,
});

// Batched catch-up wait (max 16 items, single deadline)
await client.projections.waitForCatchupBatch(
  [{ name: 'order-detail-view', minSeq: targetSeq, partition: orderId }],
  { timeoutMs: 5000 }
);

// Wait for a specific event to be processed (server resolves eventId → seq)
await client.projections.waitForEvent(eventId, 'order-detail-view', { timeoutMs: 5000 });

SQL projections (client.sqlProjections)

Materialize event streams into queryable SQL tables. Handlers are parameterized SQL strings evaluated server-side.

await client.sqlProjections.create({
  name: 'board',
  tableSql: 'CREATE TABLE proj_board (id TEXT PRIMARY KEY, title TEXT, status TEXT)',
  eventHandlers: {
    'issue.created':         "INSERT INTO proj_board (id, title, status) VALUES (:entity_id, :data.title, 'OPEN')",
    'issue.status_changed':  'UPDATE proj_board SET status = :data.to WHERE id = :entity_id',
  },
  events: ['issue.created', 'issue.status_changed'],
});

const result = await client.sqlProjections.query('board', {
  where: "status = 'OPEN'",
  orderBy: 'title ASC',
  limit: 50,
});

Secrets management (client.secrets)

await client.secrets.set('stripe-key', 'sk_live_…');
const secret = await client.secrets.get('stripe-key');
await client.secrets.update('stripe-key', 'sk_live_new');
await client.secrets.patch('stripe-key', { description: 'Payments production key' });
const all = await client.secrets.list();    // names only, no values
await client.secrets.delete('stripe-key');

Projects and environments

const project = await client.projects.create({ name: 'my-service' });
await client.projects.update(project.id, { name: 'renamed-service' });
await client.projects.list();
await client.projects.delete(project.id);

const env = await client.environments.create({ name: 'staging', project_id: project.id });
await client.environments.update(env.id, { name: 'staging-v2' });
await client.environments.list();
await client.environments.delete(env.id);

Event schemas (client.schemas)

await client.schemas.register({
  name: 'order.placed',
  version: 2,
  schema: { type: 'object', properties: { orderId: { type: 'string' } } },
});

const latest = await client.schemas.get('order.placed');
const v1     = await client.schemas.getVersion('order.placed', 1);
await client.schemas.list();
await client.schemas.delete('order.placed', 1);

// Server-side upcast test (use SDK-side defineEvent for runtime upcasting)
const out = await client.schemas.testUpcast({
  eventName: 'order.placed',
  fromVersion: 1,
  toVersion: 2,
  data: { orderId: '123' },
});

// Archived definitions, newest first. beforeRevision is an exclusive cursor:
// pass the previous page's nextBeforeRevision (0 means no more pages).
const history = await client.schemas.listHistory('order.placed', 2, { limit: 20 });
const revision = await client.schemas.getRevision('order.placed', 2, 1);

Webhook sources (client.webhooks) — server-side registry

Manage webhook sources registered with the Ironflow server (used by the dashboard and delivery tracking). For defining a webhook handler in code, use createWebhook() and pass it to serve().

// The ID is server-generated; `name` is the required display label.
const source = await client.webhooks.create({
  name: 'Stripe production',
  eventPrefix: 'stripe',
  verifyHeader: 'stripe-signature',
  verifyAlgorithm: 'hmac-sha256',
  verifySecret: process.env.STRIPE_WEBHOOK_SECRET,
});
source.ingestToken;  // write-once (ADR 0048) — capture it now

const sources = await client.webhooks.listSources();
const current = await client.webhooks.getSource(source.id);

// Full-replace, not patch: omitted fields are cleared server-side.
await client.webhooks.updateSource({
  id: current.id,
  name: 'Stripe production (EU)',
  verifyHeader: current.verifyHeader,
  verifyAlgorithm: current.verifyAlgorithm,
  metadata: current.metadata,
  expectedUpdatedAt: current.updatedAt,
});

// graceSeconds is tri-state: omit = server default, 0 = instant cutover, N = seconds.
await client.webhooks.rotateSecret({ id: source.id, verifySecret: 'whsec_new' });
await client.webhooks.expireSecretPrev(source.id);
await client.webhooks.disableSignatureVerification({ id: source.id, graceSeconds: 0 });
await client.webhooks.rotateIngestToken(source.id);

await client.webhooks.deleteSource(source.id);

const { deliveries } = await client.webhooks.listDeliveries({
  sourceId: source.id,
  status: 'failed',
  limit: 25,
});

Users and tenants

// User management
const user = await client.users.create({ email: '[email protected]', password: 'secret', roles: ['admin'] });
await client.users.list();
await client.users.get(user.id);
await client.users.update(user.id, { name: 'Alice' });
await client.users.delete(user.id);

// Tenant listing. Both tenant calls require the `users:manage` permission.
const tenants = await client.tenants.list();

Deployments, capacity and debounce

// Register stages an immutable deployment. It never changes which code serves new runs.
const { deployment, created } = await client.deployments.register({
  functionId: 'process-order',
  deploymentId: '2026-10-16-a',
  artifactDigest: `sha256:${digestHex}`,
  snapshot: { triggers: [{ event: 'order.placed' }], timeoutMs: 30000 },
  mode: 'pull',
});
await client.deployments.get('process-order', '2026-10-16-a');
await client.deployments.list('process-order', { limit: 20 });
await client.deployments.getExecutionRouting('process-order'); // 'legacy' | 'adopting' | 'versioned'

// Capacity views need platform credentials (an ifplatform_ key). A tenant key gets 403.
await client.capacity.listQueue({ limit: 50 });
await client.capacity.stats();

// cancel() takes the raw debounce key.
await client.debounce.list();
await client.debounce.cancel('env_default', 'process-search', 'user-42');

client.capacity also has listLanes, listLeases, listBuckets, listSessions and listCredits. See the Node reference for the full set.

Command idempotency (client.commandDedup)

Atomic command reservation and result caching backed by NATS KV. Reuse one instance across requests. A reservation does not prove that the command completed.

type Entry<T> = { status: 'claimed' } | { status: 'done'; result: T };
const dedup = client.commandDedup<Entry<OrderResult>>('order-commands');

const prior = await dedup.tryClaim(commandId, { status: 'claimed' });
if (prior !== null) {
  if (prior.status === 'done') return prior.result;
  throw new Error('Command is pending; reconcile its effects before retrying');
}

let result: OrderResult;
try {
  result = await runHandler(); // Effects must support idempotent retries.
} catch (err) {
  await dedup.release(commandId).catch(() => {}); // Only the claim winner reaches here.
  throw err;
}
await dedup.finalize(commandId, { status: 'done', result });
return result;

A prior entry can be pending. This example rejects pending entries instead of reporting success. Recover them through application-specific reconciliation and idempotent effects. For entity streams, see the CQRS walkthrough.

tryClaim retries up to 3 times when the winner releases between your write and read, then throws IronflowError with code COMMAND_DEDUP_RACE.

To let a retry recognize its own orphaned claim, put a token that stays the same across retries in the claim and pass isOwner as the third argument:

const prior = await dedup.tryClaim(
  commandId,
  { token, status: 'claimed' },
  (p) => p.token === token && p.status === 'claimed',
);

isOwner runs only on a prior entry. It must return false for a finalized result, or a finished command replays. Run one retry lineage at a time: two concurrent callers with the same token both win.


Entity Streams

Event sourcing primitives via client.streams. Append domain events per entity, read them back, and use optimistic concurrency.

streams.append(entityId, input, options?)

Append an event to an entity stream.

const client = createClient({ serverUrl: 'http://localhost:9123' });

const result = await client.streams.append('order-123', {
  name: 'item.added',
  data: { sku: 'ABC', qty: 2 },
  entityType: 'order',
});
console.log(result.entityVersion); // number
console.log(result.eventId);      // string

Optimistic concurrency with expectedVersion

// Read current version (returns null if no events have been written yet)
const info = await client.streams.getInfo('order-123');

// Append with version check (fails if another writer modified the stream)
try {
  await client.streams.append('order-123', {
    name: 'item.removed',
    data: { sku: 'ABC' },
    entityType: 'order',
  }, { expectedVersion: info ? info.version : 0 });
} catch (err) {
  console.error('Concurrent modification detected');
}

AppendOptions:

| Field | Type | Description | |-------|------|-------------| | expectedVersion | number | Optimistic concurrency check. | | idempotencyKey | string | Prevent duplicate appends. | | version | number | Event schema version (default: 1). | | metadata | Record<string, unknown> | Additional metadata stored with the event. |

List all streams or read an entity's unified history:

const streams = await client.streams.listStreams();
const history = await client.streams.getEntityHistory('order-123');

streams.read(entityId, options?)

Read events from an entity stream.

const { events, totalCount } = await client.streams.read('order-123', {
  direction: 'forward',  // "forward" | "backward"
  fromVersion: 0,
  limit: 50,
});

for (const event of events) {
  console.log(event.name, event.data, event.entityVersion);
}

streams.getInfo(entityId)

Get metadata about an entity stream. Returns null if no events have been written to this stream yet — safe to pass expectedVersion: 0 to append() in that case.

const info = await client.streams.getInfo('order-123');
if (info) {
  console.log(info.entityId);    // "order-123"
  console.log(info.entityType);  // "order"
  console.log(info.version);     // current version number
  console.log(info.eventCount);  // total events
  console.log(info.createdAt);   // ISO string
  console.log(info.updatedAt);   // ISO string
}

Returns: Promise<StreamInfo | null>

streams.createSnapshot / streams.getSnapshot

Speed up state reconstruction for long-lived streams by snapshotting the materialized state at a version.

await client.streams.createSnapshot('order-123', {
  entityType: 'order',
  entityVersion: 1000,
  state: { /* materialized */ },
});

const snap = await client.streams.getSnapshot('order-123');
// optional: only consider snapshots at or before a version
const old  = await client.streams.getSnapshot('order-123', { beforeVersion: 500 });

streams.listStreams / streams.getEntityHistory

const streams = await client.streams.listStreams();
const events  = await client.streams.getEntityHistory('order-123');

// All pages, oldest first; `from` / `to` are inclusive time bounds, `limit` caps the entries
const asOf = await client.streams.getEntityHistory('order-123', { to: '2026-10-06T23:59:59.999999999Z' });

streams.delete(entityId, options?)

Delete an entity stream: appends a $stream.deleted tombstone and drops its snapshots; later appends fail with failed_precondition. { purge: true } also deletes every event below the tombstone. Irreversible; requires streams:delete (admin by default). Returns the tombstone's version.

const { entityVersion } = await client.streams.delete('order-123');
await client.streams.delete('order-123', { purge: true });

KV Store

Distributed key-value storage with bucket management, CAS (compare-and-swap), TTL, and wildcard key listing.

Getting a KV client

const client = createClient({ serverUrl: 'http://localhost:9123' });
const kv = client.kv();

Bucket management

// Create a bucket with TTL
await kv.createBucket({ name: 'sessions', ttlSeconds: 3600 });

// List all buckets
const buckets = await kv.listBuckets();

// Get bucket info
const info = await kv.getBucketInfo('sessions');

// Delete a bucket
await kv.deleteBucket('sessions');

KVBucketConfig:

| Field | Type | Description | |-------|------|-------------| | name | string | Bucket name. | | description | string | Optional description. | | ttlSeconds | number | Time-to-live for keys in seconds. | | maxValueSize | number | Maximum value size in bytes. | | maxBytes | number | Maximum total bucket size. | | history | number | Number of historical revisions to keep. |

Key operations

const bucket = kv.bucket('sessions');

// Put a value (unconditional write)
const { revision } = await bucket.put('user-123', { token: 'abc', role: 'admin' });

// Read decoded JSON with the revision for CAS
const entry = await bucket.getJSON('user-123');
console.log(entry.value);    // The stored JSON object, typed as unknown
console.log(entry.revision); // revision number for CAS

// Create only if key doesn't exist (throws HTTP 412 on conflict)
await bucket.create('user-456', { token: 'def' });

// Compare-and-swap update (throws HTTP 412 on revision mismatch)
await bucket.update('user-123', { token: 'xyz', role: 'admin' }, entry.revision);

// Soft delete (tombstone)
await bucket.delete('user-123');

// Purge key and all history
await bucket.purge('user-123');

// List keys with optional wildcard filter
const keys = await bucket.listKeys('user-*');
const allKeys = await bucket.listKeys();

// Watch for changes over WebSocket (optionally a single key); stop() closes it
const watcher = bucket.watch({ onUpdate: (e) => console.log(e.key, e.revision) }, { key: 'user-123' });
watcher.stop();

getJSON() decodes base64 as UTF-8 JSON and preserves the entry metadata. Use get() for the raw base64 value. Decoded values are typed as unknown; validate their shape before use. Invalid base64, UTF-8, or JSON throws IronflowError with code INVALID_KV_JSON. Plain string writes are raw text and are not automatically JSON-quoted.


File Storage

client.files()

Get a files client for buckets, files, signed URLs and events.

const files = client.files();                        // files() is a METHOD, not a property
await files.createBucket("inbox", { emitEvents: true, allowSignedUrls: true });

const inbox = files.bucket("inbox");
const info = await inbox.put("scans/a.pdf", bytes, { contentType: "application/pdf" });
const file = await inbox.get("scans/a.pdf", { ifMatch: info.etag });
const text = await file.text();                      // or arrayBuffer(), or read file.body

FilesClient methods:

| Method | Description | | :--- | :--- | | createBucket(name, config?) | Create a bucket. config: maxObjectBytes, allowedContentTypes, emitEvents, allowSignedUrls. | | listBuckets() | FileBucketInfo[]. | | getBucket(name) | One bucket's configuration. | | updateBucket(name, config) | Change the set fields. The change applies to new writes only. | | deleteBucket(name) | Delete an empty bucket. A bucket with files throws ConflictError. | | bucket(name) | A FileBucketHandle. |

FileBucketHandle methods:

| Method | Description | | :--- | :--- | | put(path, body, { contentType, contentLength?, metadata?, ifMatch?, ifNoneMatch? }) | Upload. Returns FileInfo. | | get(path, { ifMatch?, range? }) | { body, contentType, etag, size, arrayBuffer(), text() }. | | info(path) | A file's metadata, without the bytes. | | list({ prefix?, delimiter?, cursor?, limit? }) | { files, prefixes, nextCursor }. | | delete(path) | Delete a file. A missing path is not an error. | | move(from, to, { toBucket?, ifMatch? }) | Rename one file. | | copy(from, to, { toBucket? }) | Copy one file. | | movePrefix(from, to) | Move every file under a prefix (both end in /). Returns the count. | | signUpload(path, { ttlSeconds?, maxBytes?, contentType?, createOnly? }) | { url, expiresAt } for a credential-free upload. createOnly makes the PUT fail with 412 if the path exists. | | signDownload(path, ttlSeconds?) | { url, expiresAt } for a credential-free download. |

body is a Uint8Array, ArrayBuffer, Blob or string. It can also be a Node Readable or a ReadableStream. A stream needs contentLength. A stream upload is sent once: it is not retried after a 503. The other bodies are retried. put has no fixed timeout.

Errors: PreconditionFailedError (412), PayloadTooLargeError (413), UnsupportedMediaTypeError (415) and ConflictError (409). A 404 is an IronflowError with code not_found. Import the three file error classes from @ironflow/node.


Config Management

Centralized configuration store with set, create, get, patch (shallow merge), list, and delete. update, patchIf and deleteIf are compare-and-swap variants.

const client = createClient({ serverUrl: 'http://localhost:9123' });
const c