@ironflow/core
Shared types, schemas, constants, and utilities for the Ironflow JavaScript SDK.
Note: You typically don’t need to install this package directly. It’s automatically included as a dependency of
@ironflow/browserand@ironflow/node.
Installation
Section titled “Installation”npm install @ironflow/coreImport type definitions for type-safe development:
import type { // Event types IronflowEvent, EventFilter, EventSourceType,
// Function types IronflowFunction, FunctionConfig, FunctionContext, FunctionHandler, Trigger, RetryConfig, ConcurrencyConfig, ExecutionMode,
// Step types StepClient, Duration, ParallelOptions,
// Run types Run, RunInfo, RunStatus, ListRunsOptions, ListRunsResult,
// Trigger & emit types TriggerResult, InvokeResult, TriggerSyncOptions, TriggerSyncResult, EmitOptions, EmitResult, EmitSyncResult,
// Subscription types Subscription, SubscribeOptions, SubscriptionCallbacks, SubscriptionEvent, SubscriptionErrorInfo, EventMetadata, ConnectionState, BufferConfig, AckHandle, AckableSubscription,
// Consumer group types AckMode, BackpressureMode, ConsumerGroupConfig, ConsumerGroup, ConsumerGroupStatus,
// KV types KVBucketConfig, KVBucketInfo, KVEntry, KVPutResult, KVListKeysResult, KVListBucketsResult, KVWatchEvent, KVWatchCallbacks, KVWatchOptions, KVWatcher,
// Config types ConfigResponse, ConfigEntry, ConfigSetResult, ConfigWatchCallbacks,
// Branded ID types RunId, FunctionId, StepId, EventId,
// Logger Logger,
// Server types ServerCapabilities,} from "@ironflow/core";IronflowEvent<T>
Section titled “IronflowEvent<T>”Represents an event in the system.
interface IronflowEvent<T = unknown> { id: string; name: string; version: number; data: T; timestamp: Date; idempotencyKey?: string; source?: string; metadata?: Record<string, unknown>;}The metadata field carries user-defined key-value pairs attached at emit time (via the metadata option in client.emit() or the REST API). It is available in function handlers as event.metadata and in subscription events when includeMetadata is enabled.
Represents a workflow run.
interface Run { id: string; functionId: string; eventId: string; status: RunStatus; attempt: number; maxAttempts: number; input?: unknown; output?: unknown; error?: { message: string; code?: string; }; startedAt?: Date; endedAt?: Date; createdAt: Date; updatedAt: Date;}RunStatus
Section titled “RunStatus”type RunStatus = | "pending" | "running" | "completed" | "failed" | "cancelled" | "paused";FunctionConfig
Section titled “FunctionConfig”Configuration for an Ironflow function.
interface FunctionConfig { id: string; name?: string; description?: string; // Human-readable description shown in the dashboard triggers: Trigger[]; retry?: RetryConfig; timeout?: number; // milliseconds (default: 600000) concurrency?: ConcurrencyConfig; debounce?: DebounceConfig; // Collapse rapid-fire events into a single invocation mode?: ExecutionMode; // "push" | "pull" actorKey?: string; schema?: ZodType; // Zod schema for type-safe event validation secrets?: string[]; // Secret names this function requires stepTimeout?: string; // Default timeout for step.run() calls ("30s", "5m") recording?: boolean; // Enable audit recording recordingRetention?: string; // Retention period ("7d", "30d", "90d", "forever") pauseBehavior?: "hold" | "release"; // Pause behavior for history editing (scoped injection) compensateOnCancel?: boolean; // Run compensations in reverse order when a pull-mode run is cancelled cancelOn?: CancelOnConfig[]; // Auto-cancel running runs when matching events arrive metadata?: Record<string, unknown>; // Custom metadata (e.g., service, team, owner)}StepClient
Section titled “StepClient”Client for recorded execution (durable steps).
interface StepClient { run<T>(name: string, fn: () => Promise<T>, options?: StepRunOptions): Promise<T>; sleep(name: string, duration: Duration): Promise<void>; sleepUntil(name: string, until: Date | string): Promise<void>; waitForEvent<T>(name: string, filter: EventFilter): Promise<IronflowEvent<T>>; parallel<T extends unknown[]>( name: string, branches: { [K in keyof T]: (step: StepClient) => Promise<T[K]> }, options?: ParallelOptions, ): Promise<T>; map<T, R>( name: string, items: T[], fn: (item: T, step: StepClient, index: number) => Promise<R>, options?: ParallelOptions, ): Promise<R[]>; compensate(stepName: string, fn: () => Promise<void>): void; invoke<T = unknown>(functionId: string, input?: unknown, options?: { timeout?: string }): Promise<T>; invokeAsync(functionId: string, input?: unknown): Promise<{ runId: string }>; publish(topic: string, data: unknown): Promise<PublishResult>;}Logger
Section titled “Logger”Logger interface used throughout the SDK.
interface Logger { debug(message: string, data?: Record<string, unknown>): void; info(message: string, data?: Record<string, unknown>): void; warn(message: string, data?: Record<string, unknown>): void; error(message: string, data?: Record<string, unknown>): void;}KVBucketConfig
Section titled “KVBucketConfig”Configuration for creating a KV bucket.
interface KVBucketConfig { name: string; description?: string; ttlSeconds?: number; maxValueSize?: number; maxBytes?: number; history?: number;}KVEntry
Section titled “KVEntry”A key-value entry returned by get.
interface KVEntry { key: string; value: unknown; revision: number; created_at: string; operation: string; // "put" | "delete"}KVWatchEvent
Section titled “KVWatchEvent”A change event delivered over WebSocket.
interface KVWatchEvent { type: "kv_update"; key: string; value: string; revision: number; operation: "put" | "delete"; bucket: string;}KVWatchCallbacks
Section titled “KVWatchCallbacks”interface KVWatchCallbacks { onUpdate: (event: KVWatchEvent) => void; onError?: (error: Error) => void; onClose?: () => void;}EmitOptions
Section titled “EmitOptions”Options for emitting events.
interface EmitOptions { version?: number; // Event schema version (default: 1) idempotencyKey?: string; metadata?: Record<string, unknown>; namespace?: string; // default: "default"}EmitSyncResult
Section titled “EmitSyncResult”Return type of emitSync(). Contains the final state of the triggered run after it completes (or fails).
interface EmitSyncResult { runId: string; // ID of the triggered run functionId: string; // ID of the function that handled the event status: string; // Final run status output: unknown; // Function return value durationMs: number; // Wall-clock time from trigger to completion}Throws RunFailedError if the run failed, or RunCancelledError if it was cancelled.
InvokeResult
Section titled “InvokeResult”Return type of the browser client invoke() method. Returned immediately after the event is accepted — the run may still be in progress.
interface InvokeResult { runIds: string[]; // IDs of created runs eventId: string; // ID of the stored event}Note:
TriggerResultis a deprecated alias forInvokeResultand will be removed in a future release.
Schemas (Zod)
Section titled “Schemas (Zod)”Runtime validation schemas using Zod:
import { // Push mode schemas PushRequestSchema, PushRequestEventSchema, CompletedStepSchema, ResumeContextSchema,
// Response schemas RunStatusSchema, TriggerResponseSchema, TriggerSyncResponseSchema, RunResponseSchema, ListRunsResponseSchema, HealthResponseSchema, ErrorResponseSchema,
// Consumer group schemas ConsumerGroupResponseSchema, ListConsumerGroupsResponseSchema,
// Worker schemas JobAssignmentSchema, JobEventSchema,
// WebSocket schemas WSServerMessageSchema, WSEventMessageSchema,
// Validation helpers parseAndValidate, validate,} from "@ironflow/core";
// Type-safe parsing with error handlingconst result = RunStatusSchema.safeParse(rawStatus);if (result.success) { console.log(result.data);}Constants
Section titled “Constants”Default configuration values:
import { DEFAULT_SERVER_URL, // 'http://localhost:9123' DEFAULT_WS_URL, // 'ws://localhost:9123/ws' DEFAULT_PORT, // 9123 DEFAULT_HOST, // 'localhost' DEFAULT_RECONNECT, // { ENABLED, MAX_ATTEMPTS, ... } DEFAULT_WORKER, // { MAX_CONCURRENT_JOBS, ... } DEFAULT_TIMEOUTS, // { CLIENT, FUNCTION, TRIGGER_SYNC } DEFAULT_RETRY, // { MAX_ATTEMPTS, INITIAL_DELAY_MS, ... } RUN_STATUS, // { PENDING, RUNNING, COMPLETED, FAILED, CANCELLED, PAUSED } STEP_STATUS, // { COMPLETED, FAILED, WAITING } ENV_VARS, // { SERVER_URL, SIGNING_KEY, API_KEY, LOG_LEVEL }} from "@ironflow/core";| Constant | Value | Description |
|---|---|---|
DEFAULT_SERVER_URL | 'http://localhost:9123' | Default Ironflow server URL |
DEFAULT_WS_URL | 'ws://localhost:9123/ws' | Default WebSocket URL |
DEFAULT_RECONNECT.ENABLED | true | Auto-reconnect enabled by default |
DEFAULT_RECONNECT.MAX_ATTEMPTS | 10 | Maximum reconnection attempts |
DEFAULT_RECONNECT.INITIAL_DELAY_MS | 1000 | Initial backoff delay |
DEFAULT_RECONNECT.MAX_DELAY_MS | 30000 | Maximum backoff delay |
DEFAULT_WORKER.MAX_CONCURRENT_JOBS | 10 | Default concurrent job limit |
DEFAULT_WORKER.HEARTBEAT_INTERVAL_MS | 30000 | Worker heartbeat interval |
DEFAULT_TIMEOUTS.CLIENT | 30000 | Client request timeout |
DEFAULT_TIMEOUTS.FUNCTION | 600000 | Function execution timeout |
Error Classes
Section titled “Error Classes”Built-in error types with error code classification:
import { IronflowError, ConnectionError, SubscriptionError, ValidationError, SchemaValidationError, SignatureError, TimeoutError, StepError, StepTimeoutError, FunctionNotFoundError, RunNotFoundError, RunFailedError, RunCancelledError, NonRetryableError, NotConfiguredError, UnauthenticatedError, UnauthorizedError, EnterpriseRequiredError, InvokeError, InvokeTimeoutError, AgentInvokeTimeoutError, NoRunCreatedError, MemoryCatchupTimeoutError, isRetryable, isIronflowError, toError,} from "@ironflow/core";
try { await someOperation();} catch (error) { if (error instanceof IronflowError) { console.log(error.code); // Error code console.log(error.message); // Error message console.log(error.retryable); // Whether retryable
if (isRetryable(error)) { // Retry the operation } }}Error Types
Section titled “Error Types”| Error Class | Description |
|---|---|
IronflowError | Base error class with code, retryable, details |
ConnectionError | WebSocket/HTTP connection failures (retryable) |
SubscriptionError | Subscription-related errors |
ValidationError | Invalid input or schema validation failures |
SchemaValidationError | Zod schema validation failures |
SignatureError | Webhook signature verification failures |
TimeoutError | Operation timeout with timeoutMs property |
StepError | Step execution failures with stepId and stepName |
StepTimeoutError | step.run() exceeded its timeout; has stepName and timeout (string) properties (retryable) |
FunctionNotFoundError | Function not found with functionId property |
RunNotFoundError | Run not found with runId property |
RunFailedError | Thrown by emitSync() when the triggered run fails; has runId and output properties |
RunCancelledError | Thrown by emitSync() when the triggered run is cancelled; has runId property |
NonRetryableError | Permanent failures that should not be retried |
NotConfiguredError | Client not configured (call configure() first) |
UnauthenticatedError | HTTP 401 — missing or invalid API key |
UnauthorizedError | HTTP 403 — API key lacks required permissions |
EnterpriseRequiredError | Operation requires an Enterprise license tier |
InvokeError | step.invoke() failed; has functionId, childRunId, and errorCause properties |
InvokeTimeoutError | step.invoke() timed out; extends InvokeError, adds timeoutMs property |
AgentInvokeTimeoutError | Agent invoke() exceeded its wait deadline |
NoRunCreatedError | Trigger/invoke returned no run IDs — no function matched the event |
MemoryCatchupTimeoutError | Agent run timed out catching up its memory stream during resume |
toError()
Section titled “toError()”Normalizes any thrown value to an Error instance. Useful in catch blocks where the caught value may be a string, number, or plain object rather than an Error.
function toError(error: unknown): Errortry { await riskyOperation();} catch (err) { const error = toError(err); // always an Error instance console.error(error.message);}Utilities
Section titled “Utilities”ID Generation
Section titled “ID Generation”import { generateId, createRunId, createStepId, createEventId, createFunctionId,} from "@ironflow/core";
// Generate unique IDs with prefixesconst id = generateId("run"); // 'run_abc123...'
// Create branded IDs for type safetyconst runId = createRunId("run_abc123");const stepId = createStepId("step_def456");Duration Parsing
Section titled “Duration Parsing”import { parseDuration } from "@ironflow/core";
parseDuration("30s"); // 30000 (ms)parseDuration("5m"); // 300000parseDuration("2h"); // 7200000parseDuration("1d"); // 86400000Logging
Section titled “Logging”import { createLogger, createNoopLogger } from "@ironflow/core";
// Create a logger with prefixconst logger = createLogger({ prefix: "[myapp]" });logger.info("Starting...");logger.debug("Debug info", { data: 123 });
// Create a no-op logger (disables logging)const noopLogger = createNoopLogger();Other Utilities
Section titled “Other Utilities”import { calculateBackoff, sleep, createDeferred, safeJsonParse, isObject, deepMerge,} from "@ironflow/core";Event Versioning
Section titled “Event Versioning”Utilities for event schema evolution:
import { createUpcasterRegistry, defineEvent, createEventDefinitionRegistry,} from "@ironflow/core";import type { UpcasterFn, EventDefinition } from "@ironflow/core";
// Define versioned eventsconst orderCreatedV1 = defineEvent({ name: "order.created", version: 1 });const orderCreatedV2 = defineEvent({ name: "order.created", version: 2, upcast: (data: any) => ({ ...data, address: null }),});
// Registry applies upcasters in chainconst registry = createEventDefinitionRegistry();registry.register(orderCreatedV1);registry.register(orderCreatedV2);
// Upcast v1 event data to latest versionconst upcasted = registry.upcastEvent("order.created", oldData, 1);
// Pass to serve() or createWorker() for automatic upcasting// See @ironflow/node docs for serve({ eventDefinitions: registry })Generated Protobuf/ConnectRPC Code
Section titled “Generated Protobuf/ConnectRPC Code”Access generated service definitions and message schemas:
import { // Service definitions IronflowService, PubSubService, WorkerService,
// Message schemas RunSchema as ProtoRunSchema, EventSchema as ProtoEventSchema,} from "@ironflow/core/gen";See Also
Section titled “See Also”- JavaScript SDK Overview
- Browser Package
- Node Package
- Config Management Guide - Environment-scoped configuration
- KV Store Guide - Key-value storage