//#region src/core/event.d.ts declare const opaqueSymbol: unique symbol; type Callback = (evd: WorkflowEventData) => void; type Cleanup = () => void; type InferWorkflowEventData = T extends WorkflowEventData ? U : T extends WorkflowEvent ? U : never; /** * Represents event data flowing through a workflow. * * Event data is created when an event is instantiated with the `.with()` method. * It carries the actual payload and can be processed by event handlers. * * @typeParam Data - The type of data this event carries * @typeParam DebugLabel - Optional debug label for development/debugging * * @category Events * @public */ type WorkflowEventData = { get data(): Data; } & { readonly [opaqueSymbol]: DebugLabel; }; /** * Represents a workflow event type that can be instantiated with data. * * Events are the core building blocks of workflows. They define the structure * of data that flows through the system and can be used to trigger handlers. * * @typeParam Data - The type of data this event can carry * @typeParam DebugLabel - Optional debug label for development/debugging * * @example * ```typescript * // Create an event type * const UserLoginEvent = workflowEvent<{ userId: string; timestamp: Date }>(); * * // Create event data * const loginData = UserLoginEvent.with({ * userId: 'user123', * timestamp: new Date() * }); * * // Check if data belongs to this event type * if (UserLoginEvent.include(someEventData)) { * console.log('User ID:', someEventData.data.userId); * } * ``` * * @category Events * @public */ type WorkflowEvent = { /** * Optional label used for debugging and logging purposes. */ debugLabel?: DebugLabel; /** * Unique identifier for the event type, used for serialization and network communication. */ readonly uniqueId: string; /** * Creates event data with the provided payload. * * @param data - The data payload for this event instance * @returns Event data that can be sent through workflow contexts */ with(data: Data): WorkflowEventData; /** * Type guard to check if unknown event data belongs to this event type. * * @param event - Unknown event data to check * @returns True if the event data is of this event type */ include(event: unknown): event is WorkflowEventData; /** * Registers a callback to be called when this event type is instantiated. * * @param callback - Function to call when event is created * @returns Cleanup function to remove the callback */ onInit(callback: Callback): Cleanup; } & { readonly [opaqueSymbol]: DebugLabel; }; /** * Configuration options for creating workflow events. * * @typeParam DebugLabel - Optional debug label type * * @category Events * @public */ type WorkflowEventConfig = { /** Optional debug label for development and logging */ debugLabel?: DebugLabel; /** Optional unique identifier for the event type */ uniqueId?: string; }; /** * Creates a new workflow event type. * * This is the primary factory function for creating event types that can be used * in workflows. Each event type can carry specific data and be used to trigger * handlers throughout the workflow system. * * @typeParam Data - The type of data this event will carry (defaults to void) * @typeParam DebugLabel - Optional debug label type for development * * @param config - Optional configuration for the event type * @returns A new workflow event type that can be instantiated with data * * @example * ```typescript * // Create a simple event with no data * const StartEvent = workflowEvent(); * * // Create an event that carries user data * const UserEvent = workflowEvent<{ name: string; email: string }>({ * debugLabel: 'UserEvent' * }); * * // Create event instances * const start = StartEvent.with(); * const user = UserEvent.with({ name: 'John', email: 'john@example.com' }); * ``` * * @category Events * @public */ declare const workflowEvent: (config?: WorkflowEventConfig) => WorkflowEvent; declare const isWorkflowEvent: (instance: unknown) => instance is WorkflowEvent; declare const isWorkflowEventData: (instance: unknown) => instance is WorkflowEventData; declare const eventSource: (instance: unknown) => WorkflowEvent | undefined; type OrEvent[]> = WorkflowEvent & { _type: "or"; events: Events; }; declare const or: []>(...events: Events) => OrEvent; //#endregion //#region src/core/utils.d.ts type Subscribable = { subscribe: (callback: (...args: Args) => R) => () => void; publish: (...args: Args) => unknown[]; }; //#endregion //#region src/core/stream.d.ts declare class JsonEncodeTransform extends TransformStream, string> { constructor(); } /** * A reactive stream for processing workflow events. * * WorkflowStream extends the standard ReadableStream to provide specialized * methods for filtering, transforming, and consuming workflow events. * It supports reactive patterns and can be used to build complex event * processing pipelines. * * @typeParam R - The type of data flowing through the stream * * @example * ```typescript * // Get stream from workflow context * const stream = context.stream; * * // Filter for specific events * const userEvents = stream.filter(UserEvent); * * // Transform events * const processed = stream.map(event => ({ * type: event.constructor.name, * timestamp: Date.now(), * data: event.data * })); * * // Consume events * for await (const event of stream.take(10)) { * console.log('Received:', event); * } * ``` * * @category Streaming * @public */ declare class WorkflowStream extends ReadableStream implements AsyncIterable { #private; /** * Subscribe to specific workflow events. * * @param event - The event type to listen for * @param handler - Function to handle the event * @returns Unsubscribe function * * @example * ```typescript * const unsubscribe = stream.on(UserEvent, (event) => { * console.log('User event:', event.data); * }); * * // Later... * unsubscribe(); * ``` */ on(event: WorkflowEvent, handler: (event: WorkflowEventData) => void): () => void; constructor(subscribable: Subscribable<[R], void>, rootStream: ReadableStream); constructor(subscribable: Subscribable<[R], void>, rootStream: null); constructor(subscribable: null, rootStream: ReadableStream | null); /** * Create a WorkflowStream from a standard ReadableStream. * * @param stream - The ReadableStream to wrap * @returns A new WorkflowStream instance */ static fromReadableStream(stream: ReadableStream>): WorkflowStream; /** * Create a WorkflowStream from an HTTP Response. * * @param response - The HTTP Response containing workflow events * @param eventMap - Map of event unique IDs to event constructors * @returns A new WorkflowStream instance */ static fromResponse(response: Response, eventMap: Record>): WorkflowStream>; /** * Convert the stream to an HTTP Response. * * @param init - Optional ResponseInit parameters * @param transformer - Optional custom transformer (defaults to JSON encoding) * @returns HTTP Response containing the stream data */ toResponse(init?: ResponseInit, transformer?: JsonEncodeTransform): R extends WorkflowEventData ? Response : never; /** * Process each item in the stream with a callback function. * * @param callback - Function to call for each item * @returns Promise that resolves when all items are processed * * @example * ```typescript * await stream.forEach(event => { * console.log('Processing:', event); * }); * ``` */ forEach(callback: (item: R) => void): Promise; /** * Transform each item in the stream. * * @param callback - Function to transform each item * @returns A new WorkflowStream with transformed items * * @example * ```typescript * const timestamps = stream.map(event => ({ * ...event, * timestamp: Date.now() * })); * ``` */ map(callback: (item: R) => T): WorkflowStream; /** * Take only the first N items from the stream. * * @param limit - Maximum number of items to take * @returns A new WorkflowStream limited to the specified number of items * * @example * ```typescript * const firstTen = stream.take(10); * for await (const event of firstTen) { * console.log(event); * } * ``` */ take(limit: number): WorkflowStream; /** * Filter the stream to include only items matching the predicate. * * @param predicate - Event type, function, or value to filter by * @returns A new WorkflowStream containing only matching items * * @example * ```typescript * // Filter by event type * const userEvents = stream.filter(UserEvent); * * // Filter by function * const importantEvents = stream.filter(event => event.priority === 'high'); * * // Filter by specific value * const specificEvent = stream.filter(myEventInstance); * ``` */ filter(predicate: R extends WorkflowEventData ? WorkflowEvent> : never): WorkflowStream; filter(predicate: R): WorkflowStream; filter(predicate: (event: R) => boolean): WorkflowStream; /** * Continue the stream until the predicate is met, then terminate. * * @param predicate - Event type, function, or value to stop at * @returns A new WorkflowStream that terminates when the predicate is met * * @example * ```typescript * // Stop at completion event * const processingEvents = stream.until(CompletionEvent); * * // Stop when condition is met * const beforeError = stream.until(event => event.type === 'error'); * * // Stop at specific event instance * const beforeSpecific = stream.until(myEventInstance); * ``` */ until(predicate: R extends WorkflowEventData ? WorkflowEvent> : never): WorkflowStream; until(predicate: (item: R) => boolean): WorkflowStream; until(item: R): WorkflowStream; /** * Continue the stream until a matching event is found, then return that event. * * @param predicate - Event type, function, or value to wait for * @returns Promise resolving to the matching event * * @example * ```typescript * // Wait for completion event and return it directly * const result = await stream.untilEvent(CompletionEvent); * console.log('Final result:', result.data); * * // Wait for condition and return matching event * const errorEvent = await stream.untilEvent(event => event.type === 'error'); * ``` */ untilEvent(predicate: R extends WorkflowEventData ? WorkflowEvent> : never): Promise; untilEvent(predicate: (item: R) => boolean): Promise; untilEvent(item: R): Promise; /** * Collect all items from the stream into an array. * * @returns Promise resolving to an array of all stream items * * @example * ```typescript * const events = await stream.take(5).toArray(); * console.log('Collected events:', events); * ``` */ toArray(): Promise; } //#endregion //#region src/core/context.d.ts type Handler[], Result extends WorkflowEventData | void, Context extends WorkflowContext = WorkflowContext> = (context: Context, ...events: { [K in keyof AcceptEvents]: ReturnType }) => Result | Promise; type BaseHandlerContext = { abortController: AbortController; handler: Handler[], any>; inputEvents: WorkflowEvent[]; inputs: WorkflowEventData[]; outputs: WorkflowEventData[]; prev: HandlerContext; next: Set; root: HandlerContext; }; type SyncHandlerContext = BaseHandlerContext & { async: false; pending: null; }; type AsyncHandlerContext = BaseHandlerContext & { async: true; pending: Promise | void> | null; }; type HandlerContext = AsyncHandlerContext | SyncHandlerContext; /** * Execution context for workflow event processing. * * The workflow context provides the runtime environment for executing handlers * and managing event flow. It offers access to the event stream, abort signals, * and methods for sending events within the workflow. * * @example * ```typescript * // Use the current context (first parameter inside a handler) * const { sendEvent, stream, signal } = context; * * // Send events * sendEvent( * ProcessEvent.with({ step: 'validation' }), * LogEvent.with({ message: 'Processing started' }) * ); * * // Access the event stream * await stream.filter(CompletionEvent).take(1).toArray(); * * // Check for cancellation * if (signal.aborted) { * throw new Error('Operation cancelled'); * } * ``` * * @category Context * @public */ type WorkflowContext = { /** * Stream of all events flowing through this workflow context. * Can be used to listen for specific events or create reactive processing chains. */ get stream(): WorkflowStream>; /** * Abort signal that indicates if the workflow has been cancelled. * Handlers should check this periodically for long-running operations. */ get signal(): AbortSignal; /** * Sends one or more events into the workflow for processing. * Events will be delivered to all matching handlers asynchronously. * * @param events - Event data instances to send */ sendEvent: (...events: WorkflowEventData[]) => void; __internal__call_send_event: Subscribable<[event: WorkflowEventData, handlerContext: HandlerContext], void>; __internal__property_inheritance_handlers?: Map; }; type InheritanceTransformer = (handlerContext: WorkflowContext, originalDescriptor: PropertyDescriptor) => PropertyDescriptor; /** * @deprecated Use the context parameter directly from workflow handlers instead. * The context passed to handlers already includes all state properties. * * @example * ```ts * workflow.handle([startEvent], (context, event) => { * const { sendEvent } = context; * sendEvent(processEvent.with()); * }); * ``` */ declare function getContext(): WorkflowContext; /** * Use this function to add or extend properties of the root context. * Called by middleware's createContext to update the root context. * Handler-scoped contexts will automatically inherit these properties from the root context. * Never create a new object (e.g., using a spread `{...context}`) in your middleware's createContext. * * @param context The context to extend * @param properties The properties to add to the context * @param inheritanceTransformers The inheritance transformers to apply to existing properties (optional) */ declare function extendContext(context: WorkflowContext, properties: Record, inheritanceTransformers?: Record): void; //#endregion //#region src/core/workflow.d.ts /** * Represents a workflow that processes events through registered handlers. * * A workflow is the central orchestrator for event-driven processing, allowing * you to register handlers for specific events and create execution contexts * to process those events. * * @example * ```typescript * const workflow = createWorkflow(); * * // Register a handler for user events * workflow.handle([UserEvent], async (context, event) => { * console.log('Processing user:', event.data.name); * return ProcessedEvent.with({ status: 'complete' }); * }); * * // Create context and process events * const context = workflow.createContext(); * await context.send(UserEvent.with({ name: 'John' })); * ``` * * @category Workflow * @public */ type Workflow = { /** * Registers a handler function for one or more workflow events. * * The handler will be invoked whenever any of the accepted events are sent * through a workflow context. Handlers can process events and optionally * return new events to continue the workflow. * * @typeParam AcceptEvents - Array of event types this handler accepts * @typeParam Result - Return type of the handler (event data or void) * * @param accept - Array of event types that trigger this handler * @param handler - Function to execute when matching events are received * * @example * ```typescript * // Handle multiple event types * workflow.handle([StartEvent, RestartEvent], async (context, event) => { * if (StartEvent.include(event)) { * return ProcessEvent.with({ action: 'start' }); * } else { * return ProcessEvent.with({ action: 'restart' }); * } * }); * ``` */ handle[], Result extends ReturnType["with"]> | void>(accept: AcceptEvents, handler: Handler): void; /** * Creates a new workflow context for event processing. * * The context provides the runtime environment for executing handlers * and managing event flow. Each context maintains its own execution * state and event queue. * * @returns A new workflow context instance * * @example * ```typescript * const context = workflow.createContext(); * * // Send events through the context * await context.send(MyEvent.with({ data: 'hello' })); * * // Listen for specific events * const result = await context.waitFor(CompletionEvent); * ``` */ createContext(): WorkflowContext; }; /** * Creates a new workflow instance. * * This is the primary factory function for creating workflows. Each workflow * maintains its own registry of event handlers and can create multiple * independent execution contexts. * * @returns A new workflow instance * * @example * ```typescript * // Create a simple workflow * const workflow = createWorkflow(); * * // Register handlers * workflow.handle([InputEvent], async (context, event) => { * const processed = await processInput(event.data); * return OutputEvent.with(processed); * }); * * // Use the workflow * const context = workflow.createContext(); * const input = InputEvent.with({ text: 'Hello World' }); * await context.send(input); * ``` * * @category Workflow * @public */ declare const createWorkflow: () => Workflow; //#endregion export { Handler, InferWorkflowEventData, InheritanceTransformer, OrEvent, Workflow, WorkflowContext, WorkflowEvent, WorkflowEventConfig, WorkflowEventData, WorkflowStream, createWorkflow, eventSource, extendContext, getContext, isWorkflowEvent, isWorkflowEventData, or, workflowEvent }; //# sourceMappingURL=index.d.cts.map