flowcraft 1.0.0-beta.8 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +68 -200
  2. package/dist/builder/graph/graph.d.ts +57 -0
  3. package/dist/builder/graph/graph.js +21 -0
  4. package/dist/builder/graph/graph.js.map +1 -0
  5. package/dist/builder/graph/index.d.ts +8 -0
  6. package/dist/builder/graph/index.js +23 -0
  7. package/dist/builder/graph/index.js.map +1 -0
  8. package/dist/builder/graph/internal-nodes.d.ts +59 -0
  9. package/dist/builder/graph/internal-nodes.js +20 -0
  10. package/dist/builder/graph/internal-nodes.js.map +1 -0
  11. package/dist/builder/graph/runner.d.ts +51 -0
  12. package/dist/builder/graph/runner.js +21 -0
  13. package/dist/builder/graph/runner.js.map +1 -0
  14. package/dist/builder/graph/types.d.ts +3 -0
  15. package/dist/builder/graph/types.js +3 -0
  16. package/dist/builder/graph/types.js.map +1 -0
  17. package/dist/builder/index.d.ts +8 -0
  18. package/dist/builder/index.js +24 -0
  19. package/dist/builder/index.js.map +1 -0
  20. package/dist/builder/patterns.d.ts +136 -0
  21. package/dist/builder/patterns.js +19 -0
  22. package/dist/builder/patterns.js.map +1 -0
  23. package/dist/chunk-3YMBNZ77.js +441 -0
  24. package/dist/chunk-3YMBNZ77.js.map +1 -0
  25. package/dist/chunk-64DNBF5W.js +36 -0
  26. package/dist/chunk-64DNBF5W.js.map +1 -0
  27. package/dist/chunk-6QCXIRLA.js +18 -0
  28. package/dist/chunk-6QCXIRLA.js.map +1 -0
  29. package/dist/chunk-7XUN3OQT.js +3 -0
  30. package/dist/chunk-7XUN3OQT.js.map +1 -0
  31. package/dist/chunk-AOHBHYF6.js +7 -0
  32. package/dist/chunk-AOHBHYF6.js.map +1 -0
  33. package/dist/chunk-BRFMFLR6.js +85 -0
  34. package/dist/chunk-BRFMFLR6.js.map +1 -0
  35. package/dist/chunk-ELEHMJPM.js +13 -0
  36. package/dist/chunk-ELEHMJPM.js.map +1 -0
  37. package/dist/chunk-F2RSES6P.js +3 -0
  38. package/dist/chunk-F2RSES6P.js.map +1 -0
  39. package/dist/chunk-F6C6J7HK.js +3 -0
  40. package/dist/chunk-F6C6J7HK.js.map +1 -0
  41. package/dist/chunk-GMKJ34T2.js +3 -0
  42. package/dist/chunk-GMKJ34T2.js.map +1 -0
  43. package/dist/chunk-HEO3XL4Z.js +328 -0
  44. package/dist/chunk-HEO3XL4Z.js.map +1 -0
  45. package/dist/chunk-IIKTTIW5.js +56 -0
  46. package/dist/chunk-IIKTTIW5.js.map +1 -0
  47. package/dist/chunk-KOBEU2EM.js +3 -0
  48. package/dist/chunk-KOBEU2EM.js.map +1 -0
  49. package/dist/chunk-L5PK5VL2.js +178 -0
  50. package/dist/chunk-L5PK5VL2.js.map +1 -0
  51. package/dist/chunk-P3RPDZHO.js +36 -0
  52. package/dist/chunk-P3RPDZHO.js.map +1 -0
  53. package/dist/chunk-PNWOW52F.js +19 -0
  54. package/dist/chunk-PNWOW52F.js.map +1 -0
  55. package/dist/chunk-R27FIYR5.js +62 -0
  56. package/dist/chunk-R27FIYR5.js.map +1 -0
  57. package/dist/chunk-S4WFNGQG.js +17 -0
  58. package/dist/chunk-S4WFNGQG.js.map +1 -0
  59. package/dist/chunk-TS3M7MWA.js +3 -0
  60. package/dist/chunk-TS3M7MWA.js.map +1 -0
  61. package/dist/chunk-UY4PNPBX.js +156 -0
  62. package/dist/chunk-UY4PNPBX.js.map +1 -0
  63. package/dist/chunk-VMH2LRM6.js +114 -0
  64. package/dist/chunk-VMH2LRM6.js.map +1 -0
  65. package/dist/chunk-VZDHIOCH.js +76 -0
  66. package/dist/chunk-VZDHIOCH.js.map +1 -0
  67. package/dist/chunk-WGVHM7DU.js +66 -0
  68. package/dist/chunk-WGVHM7DU.js.map +1 -0
  69. package/dist/chunk-WR5PDOPP.js +91 -0
  70. package/dist/chunk-WR5PDOPP.js.map +1 -0
  71. package/dist/chunk-YR433ZDA.js +20 -0
  72. package/dist/chunk-YR433ZDA.js.map +1 -0
  73. package/dist/context.d.ts +113 -0
  74. package/dist/context.js +3 -0
  75. package/dist/context.js.map +1 -0
  76. package/dist/errors.d.ts +35 -0
  77. package/dist/errors.js +3 -0
  78. package/dist/errors.js.map +1 -0
  79. package/dist/executors/in-memory.d.ts +39 -0
  80. package/dist/executors/in-memory.js +6 -0
  81. package/dist/executors/in-memory.js.map +1 -0
  82. package/dist/executors/types.d.ts +3 -0
  83. package/dist/executors/types.js +3 -0
  84. package/dist/executors/types.js.map +1 -0
  85. package/dist/functions.d.ts +88 -0
  86. package/dist/functions.js +21 -0
  87. package/dist/functions.js.map +1 -0
  88. package/dist/index.d.ts +16 -1056
  89. package/dist/index.js +26 -5
  90. package/dist/index.js.map +1 -1
  91. package/dist/logger.d.ts +43 -0
  92. package/dist/logger.js +3 -0
  93. package/dist/logger.js.map +1 -0
  94. package/dist/types-U76Ukj96.d.ts +609 -0
  95. package/dist/types.d.ts +3 -0
  96. package/dist/types.js +3 -0
  97. package/dist/types.js.map +1 -0
  98. package/dist/utils/analysis.d.ts +75 -0
  99. package/dist/utils/analysis.js +3 -0
  100. package/dist/utils/analysis.js.map +1 -0
  101. package/dist/utils/index.d.ts +8 -0
  102. package/dist/utils/index.js +10 -0
  103. package/dist/utils/index.js.map +1 -0
  104. package/dist/utils/mermaid.d.ts +46 -0
  105. package/dist/utils/mermaid.js +4 -0
  106. package/dist/utils/mermaid.js.map +1 -0
  107. package/dist/utils/middleware.d.ts +11 -0
  108. package/dist/utils/middleware.js +3 -0
  109. package/dist/utils/middleware.js.map +1 -0
  110. package/dist/utils/sanitize.d.ts +19 -0
  111. package/dist/utils/sanitize.js +3 -0
  112. package/dist/utils/sanitize.js.map +1 -0
  113. package/dist/utils/sleep.d.ts +9 -0
  114. package/dist/utils/sleep.js +4 -0
  115. package/dist/utils/sleep.js.map +1 -0
  116. package/dist/workflow/AbstractNode.d.ts +3 -0
  117. package/dist/workflow/AbstractNode.js +4 -0
  118. package/dist/workflow/AbstractNode.js.map +1 -0
  119. package/dist/workflow/Flow.d.ts +3 -0
  120. package/dist/workflow/Flow.js +16 -0
  121. package/dist/workflow/Flow.js.map +1 -0
  122. package/dist/workflow/Node.d.ts +3 -0
  123. package/dist/workflow/Node.js +15 -0
  124. package/dist/workflow/Node.js.map +1 -0
  125. package/dist/workflow/index.d.ts +4 -0
  126. package/dist/workflow/index.js +18 -0
  127. package/dist/workflow/index.js.map +1 -0
  128. package/dist/workflow/node-patterns.d.ts +55 -0
  129. package/dist/workflow/node-patterns.js +16 -0
  130. package/dist/workflow/node-patterns.js.map +1 -0
  131. package/dist/workflow/registry.d.ts +17 -0
  132. package/dist/workflow/registry.js +3 -0
  133. package/dist/workflow/registry.js.map +1 -0
  134. package/package.json +30 -11
package/dist/index.d.ts CHANGED
@@ -1,1056 +1,16 @@
1
- /**
2
- * A type-safe, opaque key for storing and retrieving values from the Context.
3
- * Using a `ContextKey` provides compile-time safety for your workflow's state.
4
- * @template T The type of the value this key refers to.
5
- */
6
- type ContextKey<T> = symbol & {
7
- __type: T;
8
- };
9
- /**
10
- * Creates a new, unique `ContextKey` for type-safe access to the `Context`.
11
- * @template T The type of the value this key will hold.
12
- * @param description An optional description for debugging purposes (e.g., in logs or test snapshots).
13
- * @returns A unique `ContextKey<T>`.
14
- */
15
- declare const contextKey: <T>(description?: string) => ContextKey<T>;
16
- /**
17
- * Defines the interface for the shared context object passed through the workflow.
18
- * It acts as the shared memory for all nodes in a flow. It supports both
19
- * type-safe `ContextKey`s and flexible `string` keys.
20
- */
21
- interface Context {
22
- /** Retrieves a value from the context. */
23
- get: (<T>(key: ContextKey<T>) => T | undefined) & (<T = any>(key: string) => T | undefined);
24
- /** Stores a value in the context. */
25
- set: (<T>(key: ContextKey<T>, value: T) => this) & ((key: string, value: any) => this);
26
- /** Checks if a key exists in the context. */
27
- has: ((key: ContextKey<any>) => boolean) & ((key: string) => boolean);
28
- /** Returns an iterator of all [key, value] pairs in the context. */
29
- entries: () => IterableIterator<[any, any]>;
30
- }
31
- /**
32
- * The default, `Map`-based implementation of the `Context` interface.
33
- */
34
- declare class TypedContext implements Context {
35
- private data;
36
- /**
37
- * @param initialData An optional iterable (like an array of `[key, value]` pairs)
38
- * to initialize the context with.
39
- */
40
- constructor(initialData?: Iterable<readonly [ContextKey<any> | string, any]> | null);
41
- get(key: ContextKey<any> | string): any;
42
- set(key: ContextKey<any> | string, value: any): this;
43
- has(key: ContextKey<any> | string): boolean;
44
- entries(): IterableIterator<[any, any]>;
45
- }
46
- /** A function that takes a `Context` and returns a (potentially new) `Context`. */
47
- type ContextTransform = (ctx: Context) => Context;
48
- /**
49
- * A "lens" provides a way to "focus" on a single key in the `Context`,
50
- * creating reusable, type-safe functions to get, set, or update its value.
51
- * @template T The type of the value the lens focuses on.
52
- */
53
- interface ContextLens<T> {
54
- /** Retrieves the value for the key from the context. */
55
- get: (ctx: Context) => T | undefined;
56
- /** Returns a `ContextTransform` function that will set the key to the provided value. */
57
- set: (value: T) => ContextTransform;
58
- /** Returns a `ContextTransform` function that updates the key's value based on its current value. */
59
- update: (fn: (current: T | undefined) => T) => ContextTransform;
60
- }
61
- /**
62
- * Creates a `ContextLens` object for a specific `ContextKey`.
63
- * This is the entry point for functional context manipulation.
64
- *
65
- * @example
66
- * const NAME = contextKey<string>('name')
67
- * const nameLens = lens(NAME)
68
- * const setNameTransform = nameLens.set('Alice') // This is a function: (ctx) => ctx.set(NAME, 'Alice')
69
- *
70
- * @param key The `ContextKey` to focus on.
71
- * @returns A `ContextLens<T>` object with `.get()`, `.set()`, and `.update()` methods.
72
- */
73
- declare function lens<T>(key: ContextKey<T>): ContextLens<T>;
74
- /**
75
- * Composes multiple `ContextTransform` functions into a single `ContextTransform` function.
76
- * The transformations are applied in the order they are provided.
77
- *
78
- * @param transforms A sequence of `ContextTransform` functions.
79
- * @returns A single function that applies all transformations.
80
- */
81
- declare function composeContext(...transforms: ContextTransform[]): ContextTransform;
82
-
83
- /**
84
- * Defines the interface for a logger that can be used by the workflow engine.
85
- * This allows for plugging in any logging library (e.g., Pino, Winston).
86
- */
87
- interface Logger {
88
- debug: (message: string, context?: object) => void;
89
- info: (message: string, context?: object) => void;
90
- warn: (message: string, context?: object) => void;
91
- error: (message: string, context?: object) => void;
92
- }
93
- /**
94
- * A logger implementation that performs no action (a "no-op" logger).
95
- * This is the default logger used by the framework if none is provided,
96
- * making Flowcraft silent out-of-the-box.
97
- */
98
- declare class NullLogger implements Logger {
99
- debug(): void;
100
- info(): void;
101
- warn(): void;
102
- error(): void;
103
- }
104
- type LogLevel = 'debug' | 'info' | 'warn' | 'error';
105
- /**
106
- * A default logger implementation that writes messages to the `console`.
107
- * It supports a minimum log level to control verbosity.
108
- */
109
- declare class ConsoleLogger implements Logger {
110
- private minLevel;
111
- /**
112
- * @param options Configuration for the logger.
113
- * @param options.level The minimum level of messages to log. Defaults to 'info'.
114
- */
115
- constructor(options?: {
116
- level?: LogLevel;
117
- });
118
- private log;
119
- debug(message: string, context?: object): void;
120
- info(message: string, context?: object): void;
121
- warn(message: string, context?: object): void;
122
- error(message: string, context?: object): void;
123
- }
124
-
125
- /**
126
- * Defines the contract for a workflow execution engine.
127
- * An executor is responsible for taking a `Flow` definition and running it,
128
- * orchestrating the traversal of the node graph.
129
- */
130
- interface IExecutor {
131
- /**
132
- * Executes a given flow with a specific context and options.
133
- * @param flow The `Flow` instance to execute.
134
- * @param context The shared `Context` for the workflow run.
135
- * @param options Runtime options, which can include a logger, abort controller, or initial params.
136
- * @returns A promise that resolves with the final action of the workflow, or another result
137
- * depending on the executor's implementation (e.g., a job ID for a distributed executor).
138
- */
139
- run: <T>(flow: Flow<any, T>, context: Context, options?: RunOptions) => Promise<T>;
140
- }
141
- /**
142
- * Internal, normalized run options used by executors.
143
- * @internal
144
- */
145
- interface InternalRunOptions {
146
- logger: Logger;
147
- signal?: AbortSignal;
148
- params: Params;
149
- executor: IExecutor;
150
- }
151
-
152
- /** A generic type for key-value parameters. */
153
- type Params = Record<string, any>;
154
- /** The default action returned by a node for linear progression. */
155
- declare const DEFAULT_ACTION: unique symbol;
156
- /** The action returned by a `.filter()` node when the predicate fails. */
157
- declare const FILTER_FAILED: unique symbol;
158
- /**
159
- * The standard arguments object passed to a node's lifecycle methods.
160
- * @template PrepRes The type of the `prepRes` property.
161
- * @template ExecRes The type of the `execRes` property.
162
- * @template TParams The type for the node's static parameters.
163
- */
164
- interface NodeArgs<PrepRes = any, ExecRes = any, TParams extends Params = Params> {
165
- /** The shared, mutable context for the workflow run. */
166
- ctx: Context;
167
- /** The static parameters for the node, merged from the node and flow's `withParams`. */
168
- params: TParams;
169
- /** An `AbortController` to gracefully cancel the workflow. */
170
- controller?: AbortController;
171
- /** An `AbortSignal` for handling cancellation. */
172
- signal?: AbortSignal;
173
- /** The logger instance for the workflow run. */
174
- logger: Logger;
175
- /** The result of the `prep` phase. */
176
- prepRes: PrepRes;
177
- /** The result of the `exec` phase. */
178
- execRes: ExecRes;
179
- /** The final error object, available only in `execFallback`. */
180
- error?: Error;
181
- /** The name of the Node's constructor, for logging. */
182
- name?: string;
183
- /** A reference to the current `IExecutor` running the flow. */
184
- executor?: IExecutor;
185
- }
186
- /**
187
- * The context object passed to a node's internal `_run` method.
188
- * @internal
189
- */
190
- interface NodeRunContext {
191
- ctx: Context;
192
- params: Params;
193
- signal?: AbortSignal;
194
- logger: Logger;
195
- executor?: IExecutor;
196
- }
197
- /** Options for configuring a `Node` instance. */
198
- interface NodeOptions {
199
- /** The total number of times the `exec` phase will be attempted. Defaults to `1`. */
200
- maxRetries?: number;
201
- /** The time in milliseconds to wait between failed `exec` attempts. Defaults to `0`. */
202
- wait?: number;
203
- }
204
- /** Options for running a top-level `Flow`. */
205
- interface RunOptions {
206
- /** An `AbortController` to gracefully cancel the workflow. */
207
- controller?: AbortController;
208
- /** An `AbortSignal` for handling cancellation. */
209
- signal?: AbortSignal;
210
- /** A `Logger` instance to receive logs from the execution engine. */
211
- logger?: Logger;
212
- /** Top-level parameters to be merged into the context for the entire run. */
213
- params?: Params;
214
- /** A custom `IExecutor` instance to run the workflow. Defaults to `InMemoryExecutor`. */
215
- executor?: IExecutor;
216
- }
217
- /** The function signature for the `next` function passed to middleware. */
218
- type MiddlewareNext<T = any> = (args: NodeArgs) => Promise<T>;
219
- /** The function signature for a middleware function. */
220
- type Middleware<T = any> = (args: NodeArgs, next: MiddlewareNext<T>) => Promise<T>;
221
-
222
- /**
223
- * Defines the schema for all custom node types within a specific workflow application.
224
- *
225
- * It is a map where each key is a string identifier for a node `type`
226
- * (e.g., `'llm-process'`), and the value is an object defining the expected
227
- * shape of that node's `data` payload.
228
- *
229
- * By creating an application-specific interface that extends `NodeTypeMap`,
230
- * you enable compile-time validation and autocompletion for your declarative
231
- * graph definitions. This type is the central generic constraint used by
232
- * `TypedWorkflowGraph`, `TypedNodeRegistry`, and `GraphBuilder` to provide a
233
- * fully type-safe development experience.
234
- *
235
- * @example
236
- * // 1. Define the data payloads for your application's nodes.
237
- * interface MyAppNodeTypeMap extends NodeTypeMap {
238
- * 'api-call': { url: string; retries: number };
239
- * 'data-transform': { mode: 'uppercase' | 'lowercase' };
240
- * 'output': { destination: string };
241
- * }
242
- *
243
- * // 2. Use it to create a type-safe graph definition.
244
- * const myGraph: TypedWorkflowGraph<MyAppNodeTypeMap> = {
245
- * nodes: [
246
- * // TypeScript will validate that `data` matches the 'api-call' schema.
247
- * { id: 'fetch', type: 'api-call', data: { url: '/users', retries: 3 } },
248
- * // TypeScript would throw an error on the following line:
249
- * { id: 'bad', type: 'api-call', data: { path: '/users' } } // Missing 'url' and 'retries'
250
- * ],
251
- * edges: [],
252
- * };
253
- */
254
- interface NodeTypeMap {
255
- [key: string]: Record<string, any>;
256
- }
257
- /**
258
- * The standard options object passed to a Node's constructor by the `GraphBuilder`.
259
- * @template TData The type of the `data` payload for this specific node.
260
- * @template TContext The type of the dependency injection context.
261
- */
262
- interface NodeConstructorOptions<TData, _TContext = object> extends NodeOptions {
263
- /** The `data` payload from the graph definition, with `nodeId` injected for logging/debugging. */
264
- data: TData & {
265
- nodeId: string;
266
- };
267
- /** A context object containing any dependencies injected into the `GraphBuilder` constructor. */
268
- [key: string]: any;
269
- }
270
- /**
271
- * Represents a single, type-safe node within a declarative workflow graph.
272
- * This is a discriminated union based on the `type` property, ensuring that
273
- * the `data` payload matches the node's type as defined in the `TypedNodeRegistry`.
274
- * @template T The `NodeTypeMap` that defines all possible node types and their data schemas.
275
- */
276
- type TypedGraphNode<T extends {
277
- [K in keyof T]: Record<string, any>;
278
- }> = {
279
- [K in keyof T]: {
280
- /** A unique identifier for the node within the graph. */
281
- id: string;
282
- /** The type of the node, used to look up the corresponding Node class in the registry. */
283
- type: K;
284
- /** A flexible data object that must match the schema defined in the `NodeTypeMap` for this type. */
285
- data: T[K];
286
- /** A config object to configure the node's behavior. */
287
- config?: NodeOptions;
288
- };
289
- }[keyof T];
290
- /**
291
- * Represents a directed edge connecting two nodes in a workflow graph.
292
- */
293
- interface GraphEdge {
294
- /** The `id` of the source node. */
295
- source: string;
296
- /** The `id` of the target node. */
297
- target: string;
298
- /** The action from the source node that triggers this edge. Defaults to `DEFAULT_ACTION`. */
299
- action?: string;
300
- }
301
- /**
302
- * Defines the structure of a type-safe, declarative workflow graph.
303
- * @template T The `NodeTypeMap` that validates the graph's node definitions.
304
- */
305
- interface TypedWorkflowGraph<T extends {
306
- [K in keyof T]: Record<string, any>;
307
- }> {
308
- /** An array of node definitions. */
309
- nodes: TypedGraphNode<T>[];
310
- /** An array of edge definitions that connect the nodes. */
311
- edges: GraphEdge[];
312
- }
313
- /**
314
- * A type-safe registry that maps a node type string to its corresponding `Node` constructor.
315
- * @template TNodeMap The `NodeTypeMap` that defines all possible node types and their data schemas.
316
- * @template TContext The type of the dependency injection context passed to each constructor.
317
- */
318
- type TypedNodeRegistry<TNodeMap extends NodeTypeMap, TContext = object> = {
319
- [K in keyof TNodeMap as string extends K ? never : number extends K ? never : K]: new (options: NodeConstructorOptions<TNodeMap[K], TContext> & TContext) => AbstractNode;
320
- };
321
- /**
322
- * The result of a successful `GraphBuilder.build()` call.
323
- */
324
- interface BuildResult {
325
- /** The fully wired, executable `Flow` instance. */
326
- flow: Flow;
327
- /** A map of all created node instances, keyed by their `id` from the graph definition. */
328
- nodeMap: Map<string, AbstractNode>;
329
- /** A map of all node `id`s to their predecessor count. */
330
- predecessorCountMap: Map<string, number>;
331
- }
332
- /**
333
- * Represents a node within the workflow graph.
334
- * This is a simpler (UNTYPED) version of the `TypedGraphNode` type
335
- */
336
- interface GraphNode {
337
- /** A unique identifier for the node within the graph. */
338
- id: string;
339
- /** The type of the node, used to look up the corresponding Node class in the registry. */
340
- type: string;
341
- /** A flexible data object that must match the schema defined in the `NodeTypeMap` for this type. */
342
- data?: Record<string, any>;
343
- /** A config object to configure the node's behavior. */
344
- config?: NodeOptions;
345
- }
346
- /**
347
- * Defines the structure of a workflow graph.
348
- * This is a simpler (UNTYPED) version of the `TypedWorkflowGraph` type
349
- */
350
- interface WorkflowGraph {
351
- nodes: GraphNode[];
352
- edges: GraphEdge[];
353
- }
354
- /**
355
- * A permissive (UNTYPED) registry that maps a node type string to a constructor.
356
- * This is a simpler (UNTYPED) version of the `TypedNodeRegistry` type
357
- */
358
- type NodeRegistry = Map<string, new (...args: any[]) => AbstractNode>;
359
- interface GraphBuilderOptions {
360
- subWorkflowNodeTypes?: string[];
361
- }
362
-
363
- /**
364
- * The abstract base class for all executable units in a workflow.
365
- * It provides the core structure for connecting nodes into a graph.
366
- *
367
- * @template TPostRes The type for the action returned by the node's `post` method.
368
- * @template TParams The type for the node's static parameters.
369
- */
370
- declare abstract class AbstractNode<TPostRes = any, TParams extends Params = Params> {
371
- /** A unique identifier for this node instance, often set by the GraphBuilder. */
372
- id?: number | string;
373
- /** A key-value store for static parameters that configure the node's behavior. */
374
- params: TParams;
375
- /** A map of successor nodes, keyed by the action that triggers the transition. */
376
- successors: Map<string | typeof DEFAULT_ACTION | typeof FILTER_FAILED | TPostRes, AbstractNode<any, any>>;
377
- /** The original graph definition for this node, if created by a GraphBuilder. */
378
- graphData?: GraphNode;
379
- /**
380
- * Sets a unique identifier for this node instance.
381
- * Primarily used by the GraphBuilder for wiring and debugging.
382
- * @param id The unique ID for the node.
383
- * @returns The node instance for chaining.
384
- */
385
- withId(id: number | string): this;
386
- /**
387
- * Attaches the original graph definition data to the node instance.
388
- * @internal
389
- * @param data The graph node definition.
390
- * @returns The node instance for chaining.
391
- */
392
- withGraphData(data: GraphNode): this;
393
- /**
394
- * Sets or merges static parameters for the node. These parameters are available
395
- * via `args.params` in the node's lifecycle methods.
396
- * @param params The parameters to merge into the node's existing parameters.
397
- * @returns The node instance for chaining.
398
- */
399
- withParams(params: Partial<TParams>): this;
400
- /**
401
- * Defines the next node in the sequence for a given action.
402
- * This is the primary method for constructing a workflow graph.
403
- *
404
- * @param node The successor node to execute next.
405
- * @param action The action from this node's `post` method that triggers
406
- * the transition. Defaults to `DEFAULT_ACTION` for linear flows.
407
- * @returns The successor node instance, allowing for further chaining.
408
- */
409
- next<NextNode extends AbstractNode<any, any>>(node: NextNode, action?: TPostRes | string | typeof DEFAULT_ACTION | typeof FILTER_FAILED): NextNode;
410
- /**
411
- * The internal method that executes the node's full lifecycle.
412
- * It is called by an `IExecutor`.
413
- * @internal
414
- */
415
- abstract _run(ctx: NodeRunContext): Promise<TPostRes>;
416
- }
417
- /**
418
- * The fundamental building block of a workflow, representing a single unit of work.
419
- * It features a three-phase lifecycle, retry logic, and a fluent API for creating
420
- * data processing pipelines.
421
- *
422
- * @template PrepRes The type of data returned by the `prep` phase.
423
- * @template ExecRes The type of data returned by the `exec` phase.
424
- * @template PostRes The type of the action returned by the `post` phase.
425
- * @template TParams The type for the node's static parameters.
426
- */
427
- declare class Node<PrepRes = any, ExecRes = any, PostRes = any, TParams extends Params = Params> extends AbstractNode<PostRes, TParams> {
428
- /** The total number of times the `exec` phase will be attempted. */
429
- maxRetries: number;
430
- /** The time in milliseconds to wait between failed `exec` attempts. */
431
- wait: number;
432
- /**
433
- * @param options Configuration options for the node's behavior.
434
- * @param options.maxRetries Total number of `exec` attempts. Defaults to `1`.
435
- * @param options.wait Milliseconds to wait between failed `exec` attempts. Defaults to `0`.
436
- */
437
- constructor(options?: NodeOptions);
438
- protected _wrapError(e: any, phase: 'prep' | 'exec' | 'post'): Error;
439
- /**
440
- * (Lifecycle) Prepares data for execution. Runs once before `exec`.
441
- * This is the ideal place to read data from the `Context`.
442
- * @param args The arguments for the node, including `ctx` and `params`.
443
- * @returns The data required by the `exec` phase.
444
- */
445
- prep(args: NodeArgs<void, void, TParams>): Promise<PrepRes>;
446
- /**
447
- * (Lifecycle) Performs the core, isolated logic of the node.
448
- * This is the only phase that is retried on failure. It should not access the `Context` directly.
449
- * @param args The arguments for the node, including `prepRes`.
450
- * @returns The result of the execution.
451
- */
452
- exec(args: NodeArgs<PrepRes, void, TParams>): Promise<ExecRes>;
453
- /**
454
- * (Lifecycle) Processes results and determines the next step. Runs once after `exec` succeeds.
455
- * This is the ideal place to write data to the `Context`.
456
- * @param args The arguments for the node, including `execRes`.
457
- * @returns An "action" string to determine which successor to execute next. Defaults to `DEFAULT_ACTION`.
458
- */
459
- post(args: NodeArgs<PrepRes, ExecRes, TParams>): Promise<PostRes>;
460
- /**
461
- * (Lifecycle) A fallback that runs if all `exec` retries fail.
462
- * If not implemented, the final error will be re-thrown, halting the workflow.
463
- * @param args The arguments for the node, including the final `error` that caused the failure.
464
- * @returns A fallback result of type `ExecRes`, allowing the workflow to recover and continue.
465
- */
466
- execFallback(args: NodeArgs<PrepRes, void, TParams>): Promise<ExecRes>;
467
- /**
468
- * The internal retry-aware execution logic for the `exec` phase.
469
- * @internal
470
- */
471
- _exec(args: NodeArgs<PrepRes, void, TParams>): Promise<ExecRes>;
472
- /**
473
- * The internal method that executes the node's full lifecycle.
474
- * @internal
475
- */
476
- _run({ ctx, params, signal, logger, executor }: NodeRunContext): Promise<PostRes>;
477
- /**
478
- * Runs the node as a standalone unit, independent of a larger flow.
479
- * This is useful for testing individual nodes in isolation.
480
- *
481
- * @param ctx The shared workflow context.
482
- * @param options Runtime options like a logger or abort controller.
483
- * @returns The result of the node's `post` method (its action).
484
- */
485
- run(ctx: Context, options?: RunOptions): Promise<PostRes>;
486
- /**
487
- * Creates a new node that transforms the result of this node's `exec` phase.
488
- *
489
- * @remarks
490
- * This method returns a **new** `Node` instance and does not modify the original.
491
- * The new node inherits the original's `prep` method. The original `post` method
492
- * is discarded as it is incompatible with the new result type.
493
- *
494
- * @example
495
- * const fetchUserNode = new FetchUserNode() // returns { id: 1, name: 'Alice' }
496
- * const getUserNameNode = fetchUserNode.map(user => user.name) // returns 'Alice'
497
- *
498
- * @param fn A sync or async function to transform the execution result from `ExecRes` to `NewRes`.
499
- * @returns A new `Node` instance with the transformed output type.
500
- */
501
- map<NewRes>(fn: (result: ExecRes) => NewRes | Promise<NewRes>): Node<PrepRes, NewRes, any, TParams>;
502
- /**
503
- * Creates a new node that stores the result of this node's `exec` phase in the `Context`.
504
- * This is a common terminal operation for a data processing chain.
505
- *
506
- * @remarks
507
- * This method returns a **new** `Node` instance and does not modify the original.
508
- *
509
- * @example
510
- * const USER_NAME = contextKey<string>('user_name')
511
- * const workflow = new FetchUserNode()
512
- * .map(user => user.name)
513
- * .toContext(USER_NAME)
514
- *
515
- * @param key The type-safe `ContextKey` to use for storing the result.
516
- * @returns A new `Node` instance that performs the context update in its `post` phase.
517
- */
518
- toContext(key: ContextKey<ExecRes>): Node<PrepRes, ExecRes, any, TParams>;
519
- /**
520
- * Creates a new node that acts as a conditional gate based on the `exec` result.
521
- * If the predicate returns `true`, the node returns `DEFAULT_ACTION`.
522
- * If it returns `false`, the node returns `FILTER_FAILED`, enabling branching.
523
- *
524
- * @remarks
525
- * This method returns a **new** `Node` instance and does not modify the original.
526
- *
527
- * @example
528
- * const checkAdminNode = new FetchUserNode().filter(user => user.isAdmin)
529
- *
530
- * checkAdminNode.next(adminOnlyNode, DEFAULT_ACTION)
531
- * checkAdminNode.next(accessDeniedNode, FILTER_FAILED)
532
- *
533
- * @param predicate A sync or async function that returns `true` or `false`.
534
- * @returns A new `Node` instance that implements the filter logic.
535
- */
536
- filter(predicate: (result: ExecRes) => boolean | Promise<boolean>): Node<PrepRes, ExecRes, any, TParams>;
537
- /**
538
- * Creates a new node that performs a side effect with the `exec` result,
539
- * but passes the original result through unmodified. Ideal for logging or debugging.
540
- *
541
- * @remarks
542
- * This method returns a **new** `Node` instance and does not modify the original.
543
- *
544
- * @example
545
- * const workflow = new FetchUserNode()
546
- * .tap(user => console.log('Fetched User:', user))
547
- * .map(user => user.id)
548
- *
549
- * @param fn A function to call with the execution result for its side effect.
550
- * @returns A new `Node` instance that wraps the original.
551
- */
552
- tap(fn: (result: ExecRes) => void | Promise<void>): Node<PrepRes, ExecRes, PostRes, TParams>;
553
- /**
554
- * Creates a new node that applies a context mutation using a lens before executing.
555
- * This allows for declaratively setting or updating context as part of a fluent chain.
556
- *
557
- * @remarks
558
- * This method returns a **new** `Node` instance and does not modify the original.
559
- *
560
- * @example
561
- * const VALUE = contextKey<number>('value')
562
- * const valueLens = lens(VALUE)
563
- *
564
- * const nodeWithLens = new SomeNode().withLens(valueLens, 42) // Sets VALUE to 42 before SomeNode runs
565
- *
566
- * @param lens The `ContextLens` to use for the operation.
567
- * @param value The value to set in the context via the lens.
568
- * @returns A new `Node` instance that applies the context change.
569
- */
570
- withLens<T>(lens: ContextLens<T>, value: T): Node<PrepRes, ExecRes, PostRes, TParams>;
571
- }
572
- /**
573
- * A special type of `Node` that orchestrates a graph of other nodes.
574
- * It can contain its own middleware and can be composed within other flows.
575
- *
576
- * @template PrepRes The type of data returned by the `prep` phase.
577
- * @template ExecRes The type of data returned by the `exec` phase (the final action).
578
- * @template TParams The type for the flow's static parameters.
579
- */
580
- declare class Flow<PrepRes = any, ExecRes = any, TParams extends Params = Params> extends Node<PrepRes, ExecRes, ExecRes, TParams> {
581
- /** The first node to be executed in this flow's graph. */
582
- startNode?: AbstractNode<any, any>;
583
- /** An array of middleware functions to be applied to every node within this flow. */
584
- middleware: Middleware[];
585
- /**
586
- * @param start An optional node to start the flow with.
587
- */
588
- constructor(start?: AbstractNode<any, any>);
589
- protected _wrapError(e: any, phase: 'prep' | 'exec' | 'post'): Error;
590
- /**
591
- * Adds a middleware function to this flow. Middleware will be executed in the
592
- * order it is added, wrapping the execution of every node within this flow.
593
- * @param fn The middleware function to add.
594
- * @returns The `Flow` instance for chaining.
595
- */
596
- use(fn: Middleware): this;
597
- /**
598
- * Sets the starting node of the flow's graph.
599
- * @param start The node to start with.
600
- * @returns The start node instance, allowing for further chaining (`.next()`).
601
- */
602
- start<StartNode extends AbstractNode<any, any>>(start: StartNode): StartNode;
603
- /**
604
- * (Lifecycle) Executes this flow's internal graph when it is used as a sub-flow
605
- * (a node within a larger flow).
606
- * @internal
607
- * @param args The arguments for the node, passed down from the parent executor.
608
- * @returns The final action returned by the last node in this flow's graph.
609
- */
610
- exec(args: NodeArgs<any, any, TParams>): Promise<ExecRes>;
611
- /**
612
- * (Lifecycle) The post-execution step for a `Flow` node. It simply passes through
613
- * the final action from its internal graph execution (`execRes`).
614
- * @internal
615
- */
616
- post({ execRes }: NodeArgs<PrepRes, ExecRes, TParams>): Promise<ExecRes>;
617
- /**
618
- * Runs the entire flow as a top-level entry point.
619
- * @param ctx The shared workflow context.
620
- * @param options Runtime options like a logger, abort controller, or a custom executor.
621
- * @returns The final action returned by the last node in the flow.
622
- */
623
- run(ctx: Context, options?: RunOptions): Promise<ExecRes>;
624
- /**
625
- * Finds a node within the flow's graph by its unique ID.
626
- *
627
- * This method performs a breadth-first search starting from the `startNode`.
628
- * It is a convenient way to get a reference to a specific node instance
629
- * for debugging or dynamic modifications.
630
- *
631
- * @remarks
632
- * This performs a graph traversal on each call, which has a time complexity
633
- * proportional to the number of nodes and edges in the graph (O(V+E)). For
634
- * performance-critical applications or flows built with `GraphBuilder`,
635
- * it is more efficient to use the `nodeMap` returned by `GraphBuilder.build()`.
636
- *
637
- * @param id The unique ID of the node to find (set via `.withId()` or by the `GraphBuilder`).
638
- * @returns The `AbstractNode` instance if found, otherwise `undefined`.
639
- */
640
- getNodeById(id: string | number): AbstractNode<any, any> | undefined;
641
- }
642
-
643
- /**
644
- * Error thrown when a workflow is gracefully aborted via an `AbortSignal`.
645
- * This error is caught by the execution engine to halt the flow.
646
- */
647
- declare class AbortError extends Error {
648
- constructor(message?: string);
649
- }
650
- /**
651
- * A custom error class for failures within a workflow, providing additional
652
- * context about where and when the error occurred.
653
- */
654
- declare class WorkflowError extends Error {
655
- readonly nodeName: string;
656
- readonly phase: 'prep' | 'exec' | 'post';
657
- readonly originalError?: Error;
658
- /**
659
- * @param message The error message.
660
- * @param nodeName The name of the `Node` class where the error occurred.
661
- * @param phase The lifecycle phase (`'prep'`, `'exec'`, or `'post'`) where the error was thrown.
662
- * @param originalError The underlying error that was caught and wrapped.
663
- */
664
- constructor(message: string, nodeName: string, phase: 'prep' | 'exec' | 'post', originalError?: Error);
665
- }
666
-
667
- /**
668
- * A type-safe helper function for creating a `TypedNodeRegistry`.
669
- * This function preserves the strong typing of the registry object, enabling
670
- * compile-time validation of `TypedWorkflowGraph` definitions.
671
- *
672
- * @param registry The registry object, where keys are node types and values are `Node` constructors.
673
- * @returns The same registry object, correctly typed for use with `GraphBuilder`.
674
- */
675
- declare function createNodeRegistry<TNodeMap extends NodeTypeMap, TContext = object>(registry: TypedNodeRegistry<TNodeMap, TContext>): TypedNodeRegistry<TNodeMap, TContext>;
676
- /**
677
- * Constructs an executable `Flow` from a declarative `WorkflowGraph` definition.
678
- * @template TNodeMap A `NodeTypeMap` for validating type-safe graph definitions.
679
- * @template TContext The shape of the dependency injection context object.
680
- */
681
- declare class GraphBuilder<TNodeMap extends NodeTypeMap, TContext extends {
682
- registry?: any;
683
- } = object> {
684
- private nodeOptionsContext;
685
- private registry;
686
- private subWorkflowNodeTypes;
687
- private logger;
688
- /**
689
- * @param registry A type-safe object or a `Map` where keys are node `type` strings and
690
- * values are the corresponding `Node` class constructors. For type-safety, use `createNodeRegistry`.
691
- * @param nodeOptionsContext An optional object that is passed to every node's
692
- * constructor, useful for dependency injection (e.g., passing a database client or the builder itself).
693
- */
694
- constructor(registry: TypedNodeRegistry<TNodeMap, TContext>, nodeOptionsContext?: TContext, options?: GraphBuilderOptions, logger?: Logger);
695
- constructor(registry: NodeRegistry, nodeOptionsContext?: Record<string, any>, options?: GraphBuilderOptions, logger?: Logger);
696
- private _logMermaid;
697
- private _flattenGraph;
698
- /**
699
- * Builds a runnable `Flow` from a graph definition.
700
- * @param graph The `WorkflowGraph` object describing the flow.
701
- * @returns A `BuildResult` object containing the executable `flow` and a `nodeMap`.
702
- */
703
- build(graph: TypedWorkflowGraph<TNodeMap>): BuildResult;
704
- build(graph: WorkflowGraph): BuildResult;
705
- /**
706
- * Finds the first node where all parallel branches converge.
707
- * Uses a Breadth-First Search to guarantee finding the nearest convergence point.
708
- * @param parallelNodes - The set of nodes running in parallel.
709
- * @param edgeGroups - The map of all graph edges.
710
- * @returns The convergence node, or undefined if they never converge.
711
- * @private
712
- */
713
- private _findConvergenceNode;
714
- }
715
-
716
- /**
717
- * A type for a pure function that can be executed within a `Node`,
718
- * typically taking the node's `params` as input.
719
- * @template TIn The input type, corresponding to `params`.
720
- * @template TOut The output type, which becomes the node's `execRes`.
721
- */
722
- type NodeFunction<TIn = any, TOut = any> = (input: TIn) => TOut | Promise<TOut>;
723
- /**
724
- * A type for a function that operates on the shared `Context` in addition
725
- * to the node's `params`.
726
- * @template TIn The input type, corresponding to `params`.
727
- * @template TOut The output type, which becomes the node's `execRes`.
728
- */
729
- type ContextFunction<TIn = any, TOut = any> = (ctx: Context, input: TIn) => TOut | Promise<TOut>;
730
- /**
731
- * Creates a `Node` from a simple, pure function that transforms an input to an output.
732
- * The node's `params` object is passed as the input to the function.
733
- *
734
- * @example
735
- * const add = (n: number) => mapNode<{ value: number }, number>(params => params.value + n)
736
- * const add5Node = add(5) // A reusable node that adds 5 to its input parameter.
737
- *
738
- * @param fn A function that takes an input object and returns a result.
739
- * @returns A new `Node` instance that wraps the function.
740
- */
741
- declare function mapNode<TIn extends Params, TOut>(fn: NodeFunction<TIn, TOut>): Node<void, TOut, any, TIn>;
742
- /**
743
- * Creates a `Node` from a function that requires access to the shared `Context`.
744
- * Both the `Context` and the node's `params` are passed as arguments to the function.
745
- *
746
- * @example
747
- * const greeter = contextNode((ctx, params: { name: string }) => {
748
- * const language = ctx.get(LANGUAGE_KEY) || 'en'
749
- * return language === 'en' ? `Hello, ${params.name}` : `Hola, ${params.name}`
750
- * })
751
- *
752
- * @param fn A function that takes the context and an input object, and returns a result.
753
- * @returns A new `Node` instance that wraps the function.
754
- */
755
- declare function contextNode<TIn extends Params, TOut>(fn: ContextFunction<TIn, TOut>): Node<void, TOut, any, TIn>;
756
- /**
757
- * Creates a `Node` that declaratively applies a series of transformations to the `Context`.
758
- * This is a "side-effect" node used purely for state management; its logic runs in the `prep` phase,
759
- * and it does not produce an `exec` output.
760
- *
761
- * @example
762
- * const USER_ID = contextKey<string>('user_id')
763
- * const userLens = lens(USER_ID)
764
- * const setupUserContext = (userId: string) => transformNode(userLens.set(userId))
765
- *
766
- * @param transforms A sequence of `ContextTransform` functions (e.g., from a lens) to apply.
767
- * @returns A new `Node` instance that will mutate the context when executed.
768
- */
769
- declare function transformNode(...transforms: ContextTransform[]): Node;
770
- /**
771
- * A functional-style alias for `SequenceFlow`. It constructs a linear workflow
772
- * where each node executes in the order it is provided.
773
- *
774
- * @example
775
- * const mathPipeline = pipeline(addNode(5), multiplyNode(2))
776
- *
777
- * @param nodes A sequence of `Node` instances to chain together.
778
- * @returns A `Flow` instance representing the linear sequence.
779
- */
780
- declare function pipeline(...nodes: Node[]): Flow;
781
- /**
782
- * A classic functional composition utility. It takes two functions, `f` and `g`,
783
- * and returns a new function that computes `f(g(x))`.
784
- *
785
- * This is a general-purpose helper, not a `Node` builder itself, but it can be
786
- * used to create more complex `NodeFunction`s to pass to `mapNode`.
787
- *
788
- * @example
789
- * const add5 = (x: number) => x + 5
790
- * const multiply2 = (x: number) => x * 2
791
- * const add5ThenMultiply2 = compose(multiply2, add5) // equivalent to: x => (x + 5) * 2
792
- *
793
- * @param f The outer function, which receives the result of `g`.
794
- * @param g The inner function, which receives the initial input.
795
- * @returns A new `NodeFunction` that combines both operations.
796
- */
797
- declare function compose<A, B, C>(f: NodeFunction<B, C>, g: NodeFunction<A, B>): NodeFunction<A, C>;
798
-
799
- /**
800
- * A `Flow` that creates a linear workflow from a sequence of nodes,
801
- * automatically chaining them in order.
802
- */
803
- declare class SequenceFlow<PrepRes = any, ExecRes = any> extends Flow<PrepRes, ExecRes> {
804
- /**
805
- * @param nodes A sequence of `Node` or `Flow` instances to be executed in order.
806
- */
807
- constructor(...nodes: AbstractNode[]);
808
- }
809
- /**
810
- * A `Flow` that executes a collection of different nodes concurrently.
811
- * This is the core of the "fan-out, fan-in" pattern for structural parallelism.
812
- * After all parallel branches complete, the flow can proceed to a single successor.
813
- */
814
- declare class ParallelFlow extends Flow<any, void> {
815
- protected nodesToRun: AbstractNode[];
816
- /**
817
- * @param nodesToRun The array of nodes to execute concurrently.
818
- */
819
- constructor(nodesToRun: AbstractNode[]);
820
- /**
821
- * Orchestrates the parallel execution of all nodes.
822
- * @internal
823
- */
824
- exec({ ctx, params, signal, logger, executor }: NodeArgs): Promise<void>;
825
- }
826
- /**
827
- * An abstract `Flow` that processes a collection of items sequentially, one by one.
828
- * Subclasses must implement the `prep` method to provide the items and the
829
- * `nodeToRun` property to define the processing logic for each item.
830
- */
831
- declare abstract class BatchFlow<T = any> extends Flow<Iterable<T>, null> {
832
- /**
833
- * The `Node` instance that will be executed for each item in the batch.
834
- * This must be implemented by any subclass.
835
- */
836
- protected abstract nodeToRun: AbstractNode;
837
- constructor();
838
- /**
839
- * (Abstract) Prepares the list of items to be processed.
840
- * This method is called once before the batch processing begins.
841
- * @param _args The arguments for the node, including `ctx` and `params`.
842
- * @returns An array or iterable of parameter objects, one for each item.
843
- * The `nodeToRun` will be executed once for each of these objects.
844
- */
845
- prep(_args: NodeArgs): Promise<Iterable<any>>;
846
- /**
847
- * Orchestrates the sequential execution of `nodeToRun` for each item.
848
- * @internal
849
- */
850
- exec(args: NodeArgs): Promise<null>;
851
- }
852
- /**
853
- * An abstract `Flow` that processes a collection of items concurrently.
854
- * Subclasses must implement the `prep` method to provide the items and the
855
- * `nodeToRun` property to define the processing logic for each item.
856
- * This provides a significant performance boost for I/O-bound tasks.
857
- */
858
- declare abstract class ParallelBatchFlow<T = any> extends Flow<Iterable<T>, PromiseSettledResult<any>[]> {
859
- /**
860
- * The `Node` instance that will be executed concurrently for each item in the batch.
861
- * This must be implemented by any subclass.
862
- */
863
- protected abstract nodeToRun: AbstractNode;
864
- constructor();
865
- /**
866
- * (Abstract) Prepares the list of items to be processed.
867
- * This method is called once before the batch processing begins.
868
- * @param _args The arguments for the node, including `ctx` and `params`.
869
- * @returns An array or iterable of parameter objects, one for each item.
870
- * The `nodeToRun` will be executed concurrently for each of these objects.
871
- */
872
- prep(_args: NodeArgs): Promise<Iterable<any>>;
873
- /**
874
- * Orchestrates the parallel execution of `nodeToRun` for each item.
875
- * @internal
876
- */
877
- exec(args: NodeArgs<any, void>): Promise<PromiseSettledResult<any>[]>;
878
- }
879
- /**
880
- * Creates a flow that applies a mapping function to each item in a collection in parallel
881
- * and returns a new array containing the results.
882
- *
883
- * @example
884
- * const numbers = [1, 2, 3];
885
- * const double = (n: number) => n * 2;
886
- * const processingFlow = mapCollection(numbers, double);
887
- * // When run, processingFlow's result will be [2, 4, 6]
888
- *
889
- * @param items The initial array of items of type `T`.
890
- * @param fn An async or sync function that transforms an item from type `T` to type `U`.
891
- * @returns A `Flow` instance that, when run, will output an array of type `U[]`.
892
- */
893
- declare function mapCollection<T, U>(items: T[], fn: NodeFunction<T, U>): Flow<void, U[]>;
894
- /**
895
- * Creates a flow that filters a collection based on a predicate function,
896
- * returning a new array containing only the items that pass the predicate.
897
- * The predicate is applied to all items concurrently.
898
- *
899
- * @example
900
- * const users = [{ id: 1, admin: true }, { id: 2, admin: false }];
901
- * const isAdmin = async (user: { admin: boolean }) => user.admin;
902
- * const adminFilterFlow = filterCollection(users, isAdmin);
903
- * // When run, the result will be [{ id: 1, admin: true }]
904
- *
905
- * @param items The initial array of items of type `T`.
906
- * @param predicate An async or sync function that returns `true` or `false` for an item.
907
- * @returns A `Flow` instance that, when run, will output a filtered array of type `T[]`.
908
- */
909
- declare function filterCollection<T>(items: T[], predicate: (item: T) => boolean | Promise<boolean>): Flow<void, T[]>;
910
- /**
911
- * Creates a flow that reduces a collection to a single value by executing a
912
- * reducer function sequentially for each item, similar to `Array.prototype.reduce()`.
913
- *
914
- * @example
915
- * const numbers = [1, 2, 3, 4];
916
- * const sumReducer = (acc: number, val: number) => acc + val;
917
- * const sumFlow = reduceCollection(numbers, sumReducer, 0);
918
- * // When run, the result will be 10.
919
- *
920
- * @param items The array of items to be reduced.
921
- * @param reducer An async or sync function that processes the accumulator and the current item.
922
- * @param initialValue The initial value for the accumulator.
923
- * @returns A `Flow` instance that, when run, will output the final accumulated value of type `U`.
924
- */
925
- declare function reduceCollection<T, U>(items: T[], reducer: (accumulator: U, item: T) => U | Promise<U>, initialValue: U): Flow<void, U>;
926
-
927
- /**
928
- * The default executor that runs a workflow within a single, in-memory process.
929
- * This class contains the core logic for traversing a workflow graph, applying middleware,
930
- * and handling node execution.
931
- */
932
- declare class InMemoryExecutor implements IExecutor {
933
- /**
934
- * A stateless, reusable method that orchestrates the traversal of a graph.
935
- * It is called by `run()` for top-level flows and by `Flow.exec()` for sub-flows.
936
- * @param startNode The node where the graph traversal begins.
937
- * @param flowMiddleware The middleware array from the containing flow.
938
- * @param context The shared workflow context.
939
- * @param options The internal, normalized run options.
940
- * @returns The final action from the last executed node in the graph.
941
- * @internal
942
- */
943
- _orch<T = any>(startNode: AbstractNode, flowMiddleware: Middleware[], context: Context, options: InternalRunOptions): Promise<T>;
944
- /**
945
- * Executes a given flow with a specific context and options.
946
- * This is the main entry point for the in-memory execution engine.
947
- * @param flow The Flow instance to execute.
948
- * @param context The shared context for the workflow.
949
- * @param options Runtime options, including a logger, abort controller, or initial params.
950
- * @returns A promise that resolves with the final action of the workflow.
951
- */
952
- run<T>(flow: Flow<any, T>, context: Context, options?: RunOptions): Promise<T>;
953
- run(flow: Flow, context: Context, options?: RunOptions): Promise<any>;
954
- /**
955
- * Determines the next node to execute based on the action returned by the current node.
956
- * @internal
957
- */
958
- getNextNode(curr: AbstractNode, action: any, logger: Logger): AbstractNode | undefined;
959
- }
960
-
961
- /** The rich metadata object returned by the analyzeGraph function. */
962
- interface GraphAnalysis<T extends NodeTypeMap = any> {
963
- /** A map of all nodes, keyed by ID, augmented with their connection degrees. */
964
- nodes: Map<string, TypedGraphNode<T> & {
965
- inDegree: number;
966
- outDegree: number;
967
- }>;
968
- /** An array of all node IDs in the graph. */
969
- allNodeIds: string[];
970
- /** An array of node IDs that have no incoming edges. */
971
- startNodeIds: string[];
972
- /** A list of cycles found in the graph. Each cycle is an array of node IDs. */
973
- cycles: string[][];
974
- }
975
- /** A standard structure for reporting a single validation error. */
976
- interface ValidationError {
977
- /** The ID of the node where the error occurred, if applicable. */
978
- nodeId?: string;
979
- /** A category for the error, e.g., 'CycleDetected', 'ConnectionRuleViolation'. */
980
- type: string;
981
- /** A human-readable message explaining the validation failure. */
982
- message: string;
983
- }
984
- /**
985
- * A function that takes a graph analysis and the original graph,
986
- * and returns an array of validation errors.
987
- */
988
- type Validator<T extends NodeTypeMap = any> = (analysis: GraphAnalysis<T>, graph: TypedWorkflowGraph<T>) => ValidationError[];
989
- /**
990
- * A helper function that creates a type guard for filtering nodes by their type.
991
- * This simplifies writing type-safe validation rules by removing the need for
992
- * verbose, explicit type guard syntax.
993
- *
994
- * @param type The literal string of the node type to check for.
995
- * @returns A type guard function that narrows the node to its specific type.
996
- */
997
- declare function isNodeType<T extends NodeTypeMap, K extends keyof T>(type: K): (node: TypedGraphNode<T>) => node is TypedGraphNode<T> & {
998
- type: K;
999
- };
1000
- /**
1001
- * Analyzes a declarative workflow graph definition to extract structural metadata.
1002
- * This is a lightweight, static utility that does not instantiate any nodes.
1003
- *
1004
- * @param graph The WorkflowGraph object containing nodes and edges.
1005
- * @returns A GraphAnalysis object containing nodes with degree counts, start nodes, and any cycles.
1006
- */
1007
- declare function analyzeGraph<T extends NodeTypeMap>(graph: TypedWorkflowGraph<T>): GraphAnalysis<T>;
1008
- declare function analyzeGraph(graph: WorkflowGraph): GraphAnalysis;
1009
- /**
1010
- * Factory for creating a generic, reusable validator that checks node properties.
1011
- *
1012
- * @param description A human-readable description of the rule for error messages.
1013
- * @param filter A predicate to select which nodes this rule applies to.
1014
- * @param check A function that validates the properties of a selected node.
1015
- * @returns A Validator function.
1016
- */
1017
- declare function createNodeRule<T extends NodeTypeMap>(description: string, filter: (node: TypedGraphNode<T>) => boolean, check: (node: TypedGraphNode<T> & {
1018
- inDegree: number;
1019
- outDegree: number;
1020
- }) => {
1021
- valid: boolean;
1022
- message?: string;
1023
- }): Validator<T>;
1024
- declare function createNodeRule(description: string, filter: (node: GraphNode) => boolean, check: (node: GraphNode & {
1025
- inDegree: number;
1026
- outDegree: number;
1027
- }) => {
1028
- valid: boolean;
1029
- message?: string;
1030
- }): Validator;
1031
- /**
1032
- * A built-in validator that reports any cycles found in the graph.
1033
- */
1034
- declare const checkForCycles: Validator;
1035
-
1036
- /**
1037
- * Generates a Mermaid graph definition from a `Flow` instance.
1038
- * ...
1039
- */
1040
- declare function generateMermaidGraph(flow: Flow): string;
1041
-
1042
- /**
1043
- * An abortable `sleep` utility that pauses execution for a specified duration.
1044
- * It will reject with an `AbortError` if the provided `AbortSignal` is triggered.
1045
- * @param ms The number of milliseconds to sleep.
1046
- * @param signal An optional `AbortSignal` to listen for cancellation.
1047
- */
1048
- declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
1049
-
1050
- /**
1051
- * Composes a chain of middleware functions around a node's execution.
1052
- * @internal
1053
- */
1054
- declare function applyMiddleware<T = any>(middleware: Middleware<T>[], nodeToRun: AbstractNode): MiddlewareNext<T>;
1055
-
1056
- export { AbortError, AbstractNode, BatchFlow, type BuildResult, ConsoleLogger, type Context, type ContextFunction, type ContextKey, type ContextLens, type ContextTransform, DEFAULT_ACTION, FILTER_FAILED, Flow, type GraphAnalysis, GraphBuilder, type GraphBuilderOptions, type GraphEdge, type GraphNode, type IExecutor, InMemoryExecutor, type InternalRunOptions, type Logger, type Middleware, type MiddlewareNext, Node, type NodeArgs, type NodeConstructorOptions, type NodeFunction, type NodeOptions, type NodeRegistry, type NodeRunContext, type NodeTypeMap, NullLogger, ParallelBatchFlow, ParallelFlow, type Params, type RunOptions, SequenceFlow, TypedContext, type TypedGraphNode, type TypedNodeRegistry, type TypedWorkflowGraph, type ValidationError, type Validator, WorkflowError, type WorkflowGraph, analyzeGraph, applyMiddleware, checkForCycles, compose, composeContext, contextKey, contextNode, createNodeRegistry, createNodeRule, filterCollection, generateMermaidGraph, isNodeType, lens, mapCollection, mapNode, pipeline, reduceCollection, sleep, transformNode };
1
+ export { A as AbstractNode, B as BlueprintBuildResult, k as BuildResult, D as DEFAULT_ACTION, a as FILTER_FAILED, F as Flow, o as GraphBuilderOptions, G as GraphEdge, l as GraphNode, I as IExecutor, p as InternalRunOptions, e as Middleware, M as MiddlewareNext, N as Node, b as NodeArgs, g as NodeConstructorOptions, d as NodeOptions, n as NodeRegistry, c as NodeRunContext, f as NodeTypeMap, O as OriginalPredecessorIdMap, P as Params, j as PredecessorIdMap, R as RunOptions, S as SubWorkflowResolver, T as TypedGraphNode, i as TypedNodeRegistry, h as TypedWorkflowGraph, W as WorkflowBlueprint, m as WorkflowGraph } from './types-U76Ukj96.js';
2
+ export { ExecNode, PostNode, PreNode } from './workflow/node-patterns.js';
3
+ export { Context, ContextKey, ContextLens, ContextTransform, TypedContext, composeContext, contextKey, lens } from './context.js';
4
+ export { AbortError, FatalWorkflowError, WorkflowError } from './errors.js';
5
+ export { ConsoleLogger, Logger, NullLogger } from './logger.js';
6
+ export { GraphBuilder, createNodeRegistry } from './builder/graph/graph.js';
7
+ export { ConditionalJoinNode, InputMappingNode, OutputMappingNode, ParallelBranchContainer, SubWorkflowContainerNode } from './builder/graph/internal-nodes.js';
8
+ export { BlueprintExecutor } from './builder/graph/runner.js';
9
+ export { BatchFlow, ParallelBatchFlow, ParallelFlow, SequenceFlow, filterCollection, mapCollection, reduceCollection } from './builder/patterns.js';
10
+ export { InMemoryExecutor } from './executors/in-memory.js';
11
+ export { ContextFunction, NodeFunction, compose, contextNode, mapNode, pipeline, transformNode } from './functions.js';
12
+ export { GraphAnalysis, ValidationError, Validator, analyzeGraph, checkForCycles, createNodeRule, isNodeType } from './utils/analysis.js';
13
+ export { generateMermaidFromBlueprint, generateMermaidGraph } from './utils/mermaid.js';
14
+ export { applyMiddleware } from './utils/middleware.js';
15
+ export { sanitizeGraph } from './utils/sanitize.js';
16
+ export { sleep } from './utils/sleep.js';