@asaidimu/utils-pipeline 1.0.0 → 1.0.1

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.
package/index.d.mts CHANGED
@@ -282,94 +282,6 @@ type PipelineStepDefinition = Omit<PipelineStep, "order">;
282
282
  * Outer array index → stage `order`. Inner arrays → parallel slots within a stage.
283
283
  */
284
284
  type PipelineDefinition = Array<PipelineStepDefinition | PipelineStepDefinition[]>;
285
- /**
286
- * Returned by a routing step action to redirect execution to another step.
287
- * Use the `routeTo()` helper to construct this.
288
- */
289
- interface RoutingInstruction {
290
- /** Key of the step to jump to. May refer to any registered step, including earlier ones. */
291
- next: string;
292
- /** Value to place in the carry under the target step's key before jumping. */
293
- value: any;
294
- /** Maximum number of times this loop point may be visited before the engine hard-fails. */
295
- maxIterations?: number;
296
- /**
297
- * Optional guard evaluated after each iteration increment.
298
- * Return false to terminate the loop cleanly (emits `loop:terminated` with reason
299
- * `"condition_failed"` and exits with the last successful carry).
300
- */
301
- condition?: (carry: StageCarry, iteration: number) => boolean | Promise<boolean>;
302
- }
303
- /**
304
- * Context injected into every routing step action.
305
- * Analogous to `ArtifactFactoryContext` — the step interacts with the engine through this.
306
- */
307
- interface PipelineStepContext {
308
- /**
309
- * Abort signal scoped to this execution run.
310
- * Check this inside long-running actions to respect cancellation.
311
- */
312
- signal: AbortSignal;
313
- /**
314
- * Reads a value from the current carry AND registers a dependency edge in the
315
- * execution graph so the engine knows which carry keys this step depends on.
316
- *
317
- * Steps with no `use()` calls have no declared dependencies and will always
318
- * re-execute when their stage is revisited — the safe conservative fallback.
319
- *
320
- * @param key The carry key to read (always the key of a previous step).
321
- * @returns The value stored under that key in the current carry.
322
- */
323
- use<K extends string>(key: K): StageCarry[K];
324
- /**
325
- * The number of times this specific step has been executed in the current
326
- * routing chain. Zero on first execution, increments on each re-visit.
327
- * Useful for backoff logic or conditional behaviour without external state.
328
- */
329
- iteration: number;
330
- }
331
- /**
332
- * A single executable step in a routing pipeline.
333
- * May return a plain result OR a `RoutingInstruction` to redirect execution.
334
- *
335
- * @template TIn Shape of the incoming StageCarry this step expects to read.
336
- * @template TOut Value type this step produces on a non-routing success.
337
- */
338
- interface RoutingPipelineStep<TIn extends StageCarry = StageCarry, TOut = any> {
339
- /** Unique identifier. Used as the carry key for this step's output. */
340
- key: string;
341
- /** Execution order. Steps sharing the same order run concurrently. */
342
- order: number;
343
- /**
344
- * Business logic for this step.
345
- * @param input Accumulated carry from all previous stages.
346
- * @param ctx Engine-provided context: signal, use(), iteration.
347
- * @returns A Result wrapping either a plain output value or a RoutingInstruction.
348
- */
349
- action: (input: TIn, ctx: PipelineStepContext) => Promise<Result<TOut | RoutingInstruction>>;
350
- }
351
- /** Step definition without an explicit `order` — derived from array position. */
352
- type RoutingPipelineStepDefinition = Omit<RoutingPipelineStep, "order">;
353
- /**
354
- * Declarative routing pipeline shape passed to the constructor.
355
- * Outer array index → stage `order`. Inner arrays → parallel slots within a stage.
356
- */
357
- type RoutingPipelineDefinition = Array<RoutingPipelineStepDefinition | RoutingPipelineStepDefinition[]>;
358
- /** Per-step loop tracking state, maintained inside a RoutingExecutionContext. */
359
- interface LoopContext {
360
- /** Number of times this step has been visited in the current routing chain. */
361
- iteration: number;
362
- /** Hard ceiling on iterations for this step (if specified via routeTo options). */
363
- maxIterations?: number;
364
- /** Timestamp of the first visit — useful for timeout / telemetry. */
365
- startTime: number;
366
- /** History of values and source steps passed through this loop point. */
367
- history: Array<{
368
- value: any;
369
- fromStep: string | undefined;
370
- timestamp: number;
371
- }>;
372
- }
373
285
 
374
286
  /**
375
287
  * Isolated runtime for one sequential pipeline run.
@@ -499,4 +411,1197 @@ declare class Pipeline {
499
411
  private sortObjectKeys;
500
412
  }
501
413
 
502
- export { type LoopContext, Pipeline, type PipelineDefinition, type PipelineEventMap, type PipelineStep, type PipelineStepContext, type PipelineStepDefinition, Result, type RoutingInstruction, type RoutingPipelineDefinition, type RoutingPipelineStep, type RoutingPipelineStepDefinition, SequentialExecutionContext, type StageCarry, SystemError };
414
+ /**
415
+ * Utility type for representing partial updates to the state, allowing deep nesting.
416
+ * It makes all properties optional and applies the same transformation recursively
417
+ * to nested objects and array elements, allowing for selective updates while
418
+ * preserving the original structure. It also includes the original type T and
419
+ * undefined as possibilities for the top level and nested values.
420
+ */
421
+ type DeepPartial<T> = T extends object ? T extends readonly (infer U)[] ? readonly (DeepPartial<U> | undefined)[] | undefined | T : T extends (infer U)[] ? (DeepPartial<U> | undefined)[] | undefined | T : {
422
+ [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> | undefined : T[K] | undefined;
423
+ } | undefined | T : T | undefined | symbol;
424
+ /**
425
+ * Extended store state for monitoring the current execution status (e.g., if an update is in progress).
426
+ */
427
+ interface StoreExecutionState<T> {
428
+ /** Indicates if a state update process is currently executing. */
429
+ executing: boolean;
430
+ /** The changes (DeepPartial) currently being processed in the execution cycle. Null if none. */
431
+ changes: DeepPartial<T> | null;
432
+ /** A queue of pending state update functions/objects to be applied sequentially. */
433
+ pendingChanges: Array<StateUpdater<T>>;
434
+ /** Names of all currently registered middlewares. */
435
+ middlewares: string[];
436
+ /** Details of the middleware currently running. Null if none. */
437
+ runningMiddleware: {
438
+ id: string;
439
+ name: string;
440
+ startTime: number;
441
+ } | null;
442
+ /** Indicates if the store is currently within an active transaction block. */
443
+ transactionActive: boolean;
444
+ }
445
+ /**
446
+ * Event types emitted by the state store for observability and debugging.
447
+ */
448
+ type StoreEvent = "update:start" | "update:complete" | "middleware:start" | "middleware:complete" | "middleware:error" | "middleware:blocked" | "middleware:executed" | "transaction:start" | "transaction:complete" | "transaction:error" | "persistence:ready" | "persistence:queued" | "persistence:success" | "persistence:retry" | "persistence:failed" | "persistence:queue_cleared" | "persistence:init_error" | "action:start" | "action:complete" | "action:error" | "selector:accessed" | "selector:changed";
449
+ /**
450
+ * Represents a state update, which can be:
451
+ * 1. The full new state (`T`).
452
+ * 2. A partial update object (`DeepPartial<T>`).
453
+ * 3. A function that receives the current state and returns a partial update (sync or async).
454
+ */
455
+ type StateUpdater<T> = T | DeepPartial<T> | ((state: T) => DeepPartial<T> | Promise<DeepPartial<T>>);
456
+ /**
457
+ * Core types for the reactive data store
458
+ */
459
+ /**
460
+ * Type for a Transform Middleware function.
461
+ * It modifies (transforms) the incoming changes and must return a `DeepPartial<T>`.
462
+ */
463
+ type TransformMiddleware<T> = (state: T, changes: DeepPartial<T>) => Promise<DeepPartial<T>> | DeepPartial<T>;
464
+ /**
465
+ * Type for a Blocking Middleware function.
466
+ * It determines whether the state update should proceed or be blocked.
467
+ * It returns a boolean or an object containing a `block` boolean and an optional `error`.
468
+ */
469
+ type BlockingMiddleware<T> = (state: T, changes: DeepPartial<T>) => Promise<boolean | {
470
+ block: boolean;
471
+ error?: Error;
472
+ }> | boolean | {
473
+ block: boolean;
474
+ error?: Error;
475
+ };
476
+ /**
477
+ * Type representing the configuration object passed to the `use` method to register a middleware.
478
+ */
479
+ interface MiddlewareConfig<T> {
480
+ /** The middleware function (can be a transform or blocking middleware). */
481
+ action: TransformMiddleware<T> | BlockingMiddleware<T>;
482
+ /** An optional, human-readable name for the middleware. */
483
+ name?: string;
484
+ /** If true, the middleware is treated as a blocking middleware (must return a boolean or `{ block: boolean }`). */
485
+ block?: boolean;
486
+ }
487
+ /**
488
+ * Interface for a reactive selector result, providing access to the value and subscription capabilities.
489
+ */
490
+ interface ReactiveSelector<S> {
491
+ /** Unique identifier for the selector. */
492
+ id: string;
493
+ /** Function to get the current computed value of the selector. */
494
+ get: () => S;
495
+ /**
496
+ * Subscribes a callback function to run whenever the selector's result changes.
497
+ * Returns an unsubscribe function.
498
+ */
499
+ subscribe: (callback: (state: S) => void) => () => void;
500
+ }
501
+ interface ActionWatcher {
502
+ /** Unique identifier for the action */
503
+ name: string;
504
+ /** Function to get the current computed value of the action. */
505
+ status: () => boolean;
506
+ /**
507
+ * Subscribes a callback function to run whenever the action's status changes.
508
+ * Returns an unsubscribe function.
509
+ */
510
+ subscribe: (callback: () => void) => () => void;
511
+ }
512
+ interface TransactionOptions {
513
+ /** If true, blocks resolution until changes are fully committed to the database row */
514
+ flush?: boolean;
515
+ }
516
+ /**
517
+ * Interface defining the contract for the core data state store.
518
+ * T must be an object type.
519
+ */
520
+ interface DataStore<T extends object> {
521
+ /**
522
+ * Gets the current state of the store.
523
+ * @param clone If true, returns a deep clone of the state; otherwise, returns the internal state reference.
524
+ * @returns The current state T.
525
+ */
526
+ get(clone?: boolean): T;
527
+ /**
528
+ * Registers a named action function that can modify the state.
529
+ * @param action The action configuration object.
530
+ * @returns A function to unregister the action.
531
+ */
532
+ register<R extends any[]>(action: {
533
+ name: string;
534
+ fn: (state: T, ...args: R) => DeepPartial<T> | Promise<DeepPartial<T>>;
535
+ debounce?: {
536
+ delay: number;
537
+ condition?: (previous: R, current: R) => boolean;
538
+ };
539
+ }): () => void;
540
+ /**
541
+ * Executes (dispatches) a previously registered action by its name.
542
+ * @param name The name of the action.
543
+ * @param args The parameters to pass to the action function.
544
+ * @returns A promise that resolves to the final state after the action and subsequent updates are complete.
545
+ */
546
+ dispatch<R extends any[]>(name: string, ...args: R): Promise<T>;
547
+ /**
548
+ * Sets or updates the state using a StateUpdater.
549
+ * @param update The new state, partial state, or a function returning a partial state.
550
+ * @param options Configuration options for the set operation.
551
+ * @returns A promise that resolves to the current state when the update is complete.
552
+ */
553
+ set(update: StateUpdater<T>, options?: {
554
+ force?: boolean;
555
+ actionId?: string;
556
+ }): Promise<T>;
557
+ /**
558
+ * Creates a reactive selector that computes a derived value and tracks dependencies.
559
+ * @param selector A function to compute the derived state value S from the full state T.
560
+ * @returns A `ReactiveSelector<S>` object.
561
+ */
562
+ select<S>(selector: (state: T) => S): ReactiveSelector<S>;
563
+ /**
564
+ * Subscribes a callback to run when the data at the specified path(s) changes.
565
+ * @param path A single path string or an array of path strings to watch.
566
+ * @param callback The function to execute when a change occurs in the watched path(s).
567
+ * @param options Extra options to pass to the event bus
568
+ * @returns An unsubscribe function.
569
+ */
570
+ watch(path: string | Array<string>, callback: (state: T) => void, options?: SubscribeOptions): () => void;
571
+ /**
572
+ * Subscribes to execution‑status changes of a registered action.
573
+ *
574
+ * The provided callback is called **every time** the action transitions
575
+ * between idle and running (i.e. on `action:start`, `action:complete`, or
576
+ * `action:error` for the given name). The current status can also be read
577
+ * synchronously with `isActionRunning(name)`.
578
+ *
579
+ * **Deferred listener teardown**
580
+ * To avoid unnecessary churn when subscriptions are rapidly created and
581
+ * destroyed, the underlying event listeners are not removed immediately
582
+ * on unsubscribe. Instead, a *pending reset* is queued via `queueMicrotask`.
583
+ * If a new subscription for the same action arrives before that microtask
584
+ * executes, the reset is silently cancelled and the already‑established
585
+ * listeners are reused. This keeps the subscription infrastructure stable
586
+ * and prevents cascading notifications that could otherwise arise from
587
+ * repeated subscribe‑unsubscribe‑subscribe cycles.
588
+ *
589
+ * @param name - The name of the action to watch.
590
+ * @returns An ActionWatcher
591
+ */
592
+ watchAction(name: string): ActionWatcher;
593
+ /**
594
+ * Executes an operation function within a transaction block.
595
+ * All state updates (`set` or actions) within the transaction are batched and applied atomically (all or nothing).
596
+ * @param operation The function containing the state updates.
597
+ * @returns A promise that resolves to the return value of the operation function.
598
+ */
599
+ transaction<R>(operation: () => R | Promise<R>, options?: TransactionOptions): Promise<R>;
600
+ /**
601
+ * Registers a middleware function to intercept state updates.
602
+ * @param props The middleware configuration.
603
+ * @returns A function to unregister the middleware.
604
+ */
605
+ use(props: MiddlewareConfig<T>): () => boolean;
606
+ /**
607
+ * Subscribes a listener to a specific store event type.
608
+ * @param event The type of store event to listen for.
609
+ * @param listener The callback function to execute when the event fires.
610
+ * @returns An unsubscribe function.
611
+ */
612
+ on(event: StoreEvent, listener: (data: any) => void): () => void;
613
+ /**
614
+ * Returns the unique identifier of the store instance.
615
+ */
616
+ id(): string;
617
+ /**
618
+ * Checks whether the store is fully initialized and ready for use.
619
+ */
620
+ isReady(): boolean;
621
+ /**
622
+ * Returns a promise that resolves once the store is fully initialised.
623
+ * Safe to call multiple times — all callers share the same latch.
624
+ *
625
+ * @param timeout - Optional maximum wait time in milliseconds.
626
+ * @throws {TimeoutError} If the store does not become ready within the timeout.
627
+ *
628
+ * @example
629
+ * await store.ready();
630
+ * const state = store.get();
631
+ */
632
+ ready(timeout?: number): Promise<void>;
633
+ /**
634
+ * Returns a readonly snapshot of the current execution state of the store.
635
+ */
636
+ state(): Readonly<StoreExecutionState<T>>;
637
+ }
638
+
639
+ /**
640
+ * Defines the lifecycle and sharing strategy for an artifact within the container.
641
+ */
642
+
643
+ /**
644
+ * Defines the lifecycle and sharing strategy for an artifact.
645
+ */
646
+ type ArtifactScope =
647
+ /**
648
+ * **Singleton:** A single instance of the artifact is created and shared across all resolutions
649
+ * within the container. It is created once (often lazily) and reused until invalidated.
650
+ */
651
+ "singleton"
652
+ /**
653
+ * **Transient:** A new instance of the artifact is created every time it is resolved.
654
+ * Transient artifacts do not participate in caching or shared state management.
655
+ */
656
+ | "transient";
657
+ /**
658
+ * Represents a snapshot of an artifact's state and dependencies for debugging purposes.
659
+ * Provides insight into the artifact's current status and its position within the dependency graph.
660
+ */
661
+ interface ArtifactDebugNode {
662
+ /** The unique identifier (key) of the artifact. */
663
+ id: string;
664
+ /** The scope of the artifact (Singleton or Transient). */
665
+ scope: ArtifactScope;
666
+ /**
667
+ * The current status of the artifact, indicating its lifecycle phase.
668
+ * - `'active'`: The artifact is successfully built and its instance is available.
669
+ * - `'error'`: The artifact failed to build due to an external (runtime) error.
670
+ * - `'idle'`: The artifact has not yet been built (for lazy singletons) or has been disposed.
671
+ * - `'building'`: The artifact's factory is currently executing.
672
+ * - `'pending'`: The artifact is waiting to be built, often after an invalidation and before any debounce.
673
+ */
674
+ status: "active" | "error" | "idle" | "building" | "pending" | "debouncing";
675
+ /** A list of artifact keys that this artifact directly depends on. */
676
+ dependencies: string[];
677
+ /** A list of artifact keys that directly depend on this artifact (its consumers). */
678
+ dependents: string[];
679
+ /** A list of state paths (selectors) that this artifact depends on. */
680
+ stateDependencies: string[];
681
+ /** The number of times this artifact's factory has been successfully executed/rebuilt. */
682
+ buildCount: number;
683
+ }
684
+ /**
685
+ * Context provided to the `use` callback within an artifact factory.
686
+ * It allows an artifact to declare dependencies on other artifacts and state slices.
687
+ * @template TRegistry The type mapping artifact keys to their artifact types.
688
+ * @template TState The type of the global state managed by the DataStore.
689
+ */
690
+ interface UseDependencyContext<TRegistry extends Record<string, any>, TState extends object> {
691
+ /**
692
+ * Resolves another artifact from the container and registers a dependency on it.
693
+ * If the dependency changes, the current artifact will be invalidated and rebuilt.
694
+ * @template K The key of the artifact to resolve.
695
+ * @param key The key of the artifact to resolve.
696
+ * @param params Parameters with which to resolve the artifact
697
+ * @returns A Promise that resolves to a `ResolvedArtifact` containing the instance
698
+ * or an external error.
699
+ * @throws {SystemError} if the key is missing or if resolving creates a circular dependency.
700
+ */
701
+ resolve<K extends keyof TRegistry>(key: K, params?: any): Promise<ResolvedArtifact<TRegistry[K]>>;
702
+ /**
703
+ * Resolves another artifact from the container and registers a dependency on it.
704
+ * If the dependency changes, the current artifact will be invalidated and rebuilt.
705
+ * @template K The key of the artifact to resolve.
706
+ * @param key The key of the artifact to resolve.
707
+ * @param params Parameters with which to resolve the artifact
708
+ * @returns A Promise that resolves to a the resolved instance, unlike
709
+ * resolve, this will throw an error if resolution fails.
710
+ * @throws {SystemError} if any error occurs during resolution.
711
+ */
712
+ require<K extends keyof TRegistry>(key: K, params?: any): Promise<TRegistry[K]>;
713
+ /**
714
+ * Selects a slice of the global state and registers a dependency on it.
715
+ * If the selected state slice changes (based on a deep comparison), the current
716
+ * artifact will be invalidated and rebuilt.
717
+ * @template S The type of the selected state slice.
718
+ * @param selector A function that takes the full state and returns a slice of state.
719
+ * @returns The selected slice of state.
720
+ */
721
+ select<S>(selector: (state: TState) => S, options?: SubscribeOptions): S;
722
+ }
723
+ /**
724
+ * Context object provided to an artifact stream producer function (`ctx.stream` callback).
725
+ * It contains methods and properties necessary for managing the stream and communicating
726
+ * new artifact values to the container and its consumers.
727
+ *
728
+ * @template TState The type of the global state.
729
+ * @template TArtifact The type of the artifact being streamed.
730
+ */
731
+ type ArtifactStreamContext<TState, TArtifact> = {
732
+ /**
733
+ * The current value of the artifact. This is `undefined` before the first value is emitted.
734
+ * Useful for diffing or migrating state during an update.
735
+ * @returns The current artifact value or `undefined`.
736
+ */
737
+ value: () => TArtifact | undefined;
738
+ /**
739
+ * An AbortSignal that indicates if the stream has been cancelled or aborted
740
+ * from the consumer side (e.g., due to container disposal or artifact invalidation).
741
+ * Producers should check this signal and stop processing when it is set to prevent leaks.
742
+ */
743
+ signal: AbortSignal;
744
+ /**
745
+ * A function to asynchronously emit a new value of the artifact to the container.
746
+ * Calling this function updates the artifact's resolved value, triggers invalidation
747
+ * for its dependents, and updates the `value()` property for subsequent emissions.
748
+ *
749
+ * @param value The new artifact value to emit.
750
+ * @returns A Promise that resolves when the value has been sent and dependents have been notified.
751
+ */
752
+ emit: (value: TArtifact) => Promise<void>;
753
+ /**
754
+ * Dispatches a state update to the global store, analogous to a standard `setState`.
755
+ * **Note:** This does not automatically register a dependency for the current artifact.
756
+ * @param update A `StateUpdater` function or a partial state object.
757
+ * @param options Optional settings for the update, including `force` and `actionId`.
758
+ * @returns A Promise that resolves when the state update is complete.
759
+ */
760
+ set(update: StateUpdater<TState>, options?: {
761
+ force?: boolean;
762
+ actionId?: string;
763
+ }): Promise<any>;
764
+ };
765
+ /**
766
+ * The full context provided to an artifact's factory function.
767
+ * This context allows the artifact to interact with the container,
768
+ * declare dependencies, manage its lifecycle, and update its value.
769
+ * @template TRegistry The type mapping artifact keys to their artifact types.
770
+ * @template TState The type of the global state managed by the DataStore.
771
+ * @template TArtifact The type of the artifact being created by the factory.
772
+ */
773
+ type ArtifactFactoryContext<TRegistry extends Record<string, any>, TState extends object, TArtifact, TExtra extends Record<string, any> = {}> = TExtra & {
774
+ /**
775
+ * Returns the current global state object. This is a non-reactive read;
776
+ * changes to the state will not automatically invalidate the artifact
777
+ * unless explicitly selected via `ctx.use` and `ctx.select`.
778
+ * @returns The current global state.
779
+ */
780
+ state(): TState;
781
+ /**
782
+ * The previous instance of the artifact if it's a Singleton and is being rebuilt
783
+ * after an invalidation. This is `undefined` on the initial build.
784
+ * Useful for diffing, migrating state, or reusing resources during an update.
785
+ */
786
+ previous?: TArtifact;
787
+ /**
788
+ * Executes a callback within a dependency tracking context.
789
+ * Any `resolve` or `select` calls made inside this callback will register
790
+ * dependencies for the current artifact.
791
+ * @template R The return type of the callback.
792
+ * @param callback The function to execute to resolve dependencies.
793
+ * @returns A Promise resolving to the result of the callback.
794
+ */
795
+ use<R>(callback: (ctx: UseDependencyContext<TRegistry, TState>) => R | Promise<R>): Promise<R>;
796
+ /**
797
+ * Registers a cleanup function to be executed when the **current instance** of the
798
+ * artifact is invalidated and before its new instance is built. This is useful
799
+ * for releasing resources (e.g., event listeners) specific to the *previous* instance.
800
+ * @param cleanup The cleanup function.
801
+ */
802
+ onCleanup(cleanup: ArtifactCleanup): void;
803
+ /**
804
+ * Registers a dispose function to be executed when the artifact is
805
+ * permanently removed from the container or the container itself is disposed.
806
+ * This is for final, permanent resource release.
807
+ * @param callback The dispose function.
808
+ */
809
+ onDispose(callback: ArtifactCleanup): void;
810
+ /**
811
+ * Starts a streaming process for a Singleton artifact.
812
+ * The callback receives an `ArtifactStreamContext` to emit values and manage the
813
+ * stream's lifecycle. It can return a cleanup function (or a Promise resolving
814
+ * to one) to handle resource disposal.
815
+ * * @param callback - The streaming logic implementation. Can be synchronous or
816
+ * asynchronous, optionally returning a cleanup function.
817
+ * @throws {SystemError} If called on a Transient artifact, as they do not
818
+ * support persistent streaming states.
819
+ */
820
+ stream(callback: (ctx: ArtifactStreamContext<TState, TArtifact>) => (void | (() => void | Promise<void>)) | Promise<void | (() => void | Promise<void>)>): void;
821
+ stream(callback: (ctx: ArtifactStreamContext<TState, TArtifact>) => (void | (() => void | Promise<void>)) | Promise<void | (() => void | Promise<void>)>): void;
822
+ /**
823
+ * An AbortSignal that indicates if the artifacts has been unregistered
824
+ */
825
+ signal: AbortSignal;
826
+ /** For parameterized artifacts: the parameters that were passed during resolve/watch. */
827
+ params?: any;
828
+ };
829
+ /**
830
+ * A function that performs cleanup or disposal logic for an artifact, potentially asynchronously.
831
+ * Used for `onCleanup` and `onDispose` callbacks.
832
+ */
833
+ type ArtifactCleanup = () => void | Promise<void>;
834
+ /**
835
+ * Common properties shared across all possible states of a resolved artifact.
836
+ * @template TArtifact The type of the resolved artifact instance.
837
+ */
838
+ interface ResolvedArtifactBase {
839
+ /**
840
+ * A function to manually trigger cleanup associated with this specific
841
+ * resolved instance. This is typically only relevant for Transient artifacts
842
+ * where the consumer is responsible for cleanup.
843
+ */
844
+ cleanup?: ArtifactCleanup;
845
+ /**
846
+ * Manually invalidates this artifact, triggering its rebuild and
847
+ * cascading invalidations to its dependents.
848
+ * @param replace If `true`, forces immediate rebuild without debounce delay.
849
+ * @param fatal If `true`, the artifact will not be rebuilt until next resolve
850
+ * regardless of the lazy option during registration.
851
+ */
852
+ invalidate(replace?: boolean, fatal?: boolean): Promise<void>;
853
+ }
854
+ /**
855
+ * State of an artifact that is successfully built and ready for use.
856
+ * The instance is guaranteed to be present.
857
+ * @template TArtifact The type of the resolved artifact instance.
858
+ */
859
+ interface ReadyArtifact<TArtifact> extends ResolvedArtifactBase {
860
+ /** The successfully resolved instance of the artifact. */
861
+ instance: TArtifact;
862
+ /** Indicates whether the artifact is ready and has an instance. */
863
+ ready: true;
864
+ error?: undefined;
865
+ }
866
+ /**
867
+ * State of an artifact that failed to build due to an external error.
868
+ * The instance is guaranteed to be absent.
869
+ */
870
+ interface ErrorArtifact extends ResolvedArtifactBase {
871
+ instance?: undefined;
872
+ ready: false;
873
+ /**
874
+ * Any runtime or external error that occurred during the artifact's factory
875
+ * execution (e.g., network fetch failed).
876
+ */
877
+ error: any;
878
+ }
879
+ /**
880
+ * State of an artifact that is pending, idle, or currently building.
881
+ * Both instance and error are absent.
882
+ */
883
+ interface PendingArtifact extends ResolvedArtifactBase {
884
+ /** The instance is absent while pending or idle. Always undefined. */
885
+ instance?: undefined;
886
+ ready: false;
887
+ error?: undefined;
888
+ }
889
+ /**
890
+ * The result of an artifact resolution. This is a union type representing
891
+ * the artifact in one of three possible states: Ready, Error, or Pending/Idle.
892
+ *
893
+ * This structure allows consuming code to narrow the type based on the
894
+ * boolean flag `ready` or the presence of the `error` property.
895
+ *
896
+ * @template TArtifact The type of the resolved artifact instance.
897
+ */
898
+ type ResolvedArtifact<TArtifact> = ReadyArtifact<TArtifact> | ErrorArtifact | PendingArtifact;
899
+ type KeyedResolvedArtifact<TRegistry, K extends keyof TRegistry> = ResolvedArtifact<TRegistry[K]> & {
900
+ [P in K]?: TRegistry[K];
901
+ };
902
+ /**
903
+ * The factory function responsible for creating an artifact's instance.
904
+ * It receives an `ArtifactFactoryContext` to interact with the container
905
+ * and declare dependencies.
906
+ * @template TRegistry The type mapping artifact keys to their artifact types.
907
+ * @template TState The type of the global state managed by the DataStore.
908
+ * @template TArtifact The type of the artifact this factory produces.
909
+ * @param context The context for creating the artifact.
910
+ * @returns The artifact instance or a Promise resolving to it.
911
+ */
912
+ type ArtifactFactory<TRegistry extends Record<string, any>, TState extends object, TArtifact, TExtra extends Record<string, any> = {}> = (context: ArtifactFactoryContext<TRegistry, TState, TArtifact, TExtra>) => TArtifact | Promise<TArtifact>;
913
+ /**
914
+ * An interface for observing changes to an artifact without direct resolution,
915
+ * typically used for UI binding or monitoring.
916
+ * Provides a way to get the current resolved artifact and subscribe to updates.
917
+ * @template TArtifact The type of the artifact being watched.
918
+ */
919
+ interface ArtifactObserver<TRegistry, K extends keyof TRegistry> {
920
+ /** The unique identifier (key) of the artifact being watched. */
921
+ id: string;
922
+ /**
923
+ * Number of active references (watchers) to this observer instance.
924
+ * Incremented on each `watch()` call, decremented on each `dispose()` call.
925
+ */
926
+ count: number;
927
+ /**
928
+ * Retrieves the current `ResolvedArtifact` for the watched key.
929
+ * @param resolve Flag indicating whether we should resolve the artifact
930
+ * immediately. Defaults to `false`
931
+ * @returns The resolved artifact, including its instance and status.
932
+ */
933
+ get(resolve?: boolean): KeyedResolvedArtifact<TRegistry, K>;
934
+ /**
935
+ * Subscribes a callback function to be invoked whenever the artifact's
936
+ * state (instance, error, or readiness) changes.
937
+ * @param callback The function to call on updates. It receives the new `ResolvedArtifact`.
938
+ * @param eager a boolean indicating whether we should immediately call the
939
+ * callback after subscription. Defaults to `true`
940
+ * @returns A function to unsubscribe the callback and stop receiving updates.
941
+ */
942
+ subscribe(callback: (artifact: KeyedResolvedArtifact<TRegistry, K>) => void, eager?: boolean): () => void;
943
+ /**
944
+ * Resolves another artifact from the container and registers a dependency on it.
945
+ * If the dependency changes, the current artifact will be invalidated and rebuilt.
946
+ * @returns A Promise that resolves to a `ResolvedArtifact` containing the instance
947
+ * or an external error.
948
+ * @throws {SystemError} if resolution fails.
949
+ */
950
+ resolve(): Promise<KeyedResolvedArtifact<TRegistry, K>>;
951
+ }
952
+ /**
953
+ * Configuration options for defining an artifact. These options control
954
+ * its lifecycle, instantiation, and error handling behavior.
955
+ * @template TState The type of the global state.
956
+ * @template TArtifact The resolved type of the artifact instance.
957
+ * @template TRegistry The type mapping of all artifacts in the container.
958
+ */
959
+ interface ArtifactTemplate<TState extends object, TArtifact, TRegistry extends Record<string, any> = Record<string, any>, TExtra extends Record<string, any> = {}> {
960
+ /** The unique key identifying this artifact within the registry. */
961
+ key: keyof TRegistry;
962
+ /** The factory function responsible for creating the artifact's instance. */
963
+ factory: ArtifactFactory<TRegistry, TState, TArtifact, TExtra>;
964
+ /**
965
+ * The scope of the artifact, determining its lifecycle and sharing strategy.
966
+ * Defaults to `ArtifactScopes.Singleton`.
967
+ */
968
+ scope?: ArtifactScope;
969
+ /**
970
+ * If `true` (default), the artifact's factory is executed only when the artifact
971
+ * is first requested (lazy instantiation). If `false`, the artifact is built
972
+ * immediately upon registration (only applies to Singleton scopes).
973
+ */
974
+ lazy?: boolean;
975
+ /**
976
+ * Maximum time in milliseconds allowed for the artifact's factory function
977
+ * to complete execution. If exceeded, the factory will time out.
978
+ */
979
+ timeout?: number;
980
+ /**
981
+ * Number of times to retry the artifact's factory on failure due to an
982
+ * external (runtime) error (e.g., an exception in an async dependency).
983
+ * SystemErrors (e.g., key not found) are not retried. Defaults to `0`.
984
+ */
985
+ retries?: number;
986
+ /**
987
+ * Base debounce time in milliseconds for invalidation events originating
988
+ * from this artifact's dependencies. This delays the rebuild process to
989
+ * aggregate multiple rapid changes.
990
+ */
991
+ debounce?: number;
992
+ /** If defined, the artifact is parameterized. Receives the user‑supplied params and returns a unique string key. */
993
+ paramKey?: (params: Record<string, unknown>) => string;
994
+ virtual?: true;
995
+ }
996
+
997
+ /**
998
+ * A dependency injection container for managing the lifecycle, dependencies,
999
+ * and instances of "artifacts" (any JavaScript/TypeScript object or value).
1000
+ *
1001
+ * Separated concerns:
1002
+ * - ArtifactRegistry: Stores artifact templates (factories + options)
1003
+ * - ArtifactCache: Stores resolved singleton instances
1004
+ * - ArtifactDependencyGraph: Tracks artifact dependencies using DependencyGraph
1005
+ * - ArtifactManager: Handles lifecycle (build, invalidate, dispose)
1006
+ * - ArtifactObserverManager: Manages watchers and subscriptions
1007
+ *
1008
+ * @template TRegistry A type that maps artifact keys to their types
1009
+ * @template TState The type of the global state object
1010
+ */
1011
+ declare class ArtifactContainer<TRegistry extends Record<string, any> = Record<string, any>, TState extends object = any> {
1012
+ private readonly registry;
1013
+ private readonly cache;
1014
+ private readonly graph;
1015
+ private readonly manager;
1016
+ private readonly observer;
1017
+ private readonly store;
1018
+ /**
1019
+ * Creates a new ArtifactContainer instance.
1020
+ * @param store An object providing functions to interact with a global data store
1021
+ */
1022
+ constructor(store: Pick<DataStore<TState>, "watch" | "get" | "set">);
1023
+ /**
1024
+ * Provides debug information about all artifacts currently registered in this container.
1025
+ *
1026
+ * Status mapping:
1027
+ * - `"building"` — factory is currently executing (buildOnce.running())
1028
+ * - `"debouncing"` — invalidation is pending behind a debounce timer
1029
+ * - `"error"` — last build attempt failed
1030
+ * - `"active"` — successfully built and instance is available
1031
+ * - `"idle"` — not yet built (lazy) or has been disposed
1032
+ *
1033
+ * @returns An array of ArtifactDebugNode objects
1034
+ */
1035
+ debugInfo(): ArtifactDebugNode[];
1036
+ /**
1037
+ * Registers a new artifact with the container.
1038
+ * If an artifact with the same key already exists, it will be overwritten and disposed.
1039
+ * For Singleton, non-lazy artifacts, the factory will be immediately invoked.
1040
+ *
1041
+ * @param params The registration parameters
1042
+ * @returns A cleanup function that unregisters the artifact
1043
+ */
1044
+ register<K extends keyof TRegistry>(params: ArtifactTemplate<TState, TRegistry[K], TRegistry>): () => void;
1045
+ /**
1046
+ * Returns a boolean indicating whether a template exists for an artifact.
1047
+ *
1048
+ * @param key The unique identifier of the artifact.
1049
+ * @returns boolean.
1050
+ */
1051
+ has<K extends keyof TRegistry>(key: K): boolean;
1052
+ /**
1053
+ * Unregisters an artifact from the container, disposing of its current instance
1054
+ * and removing all associated resources and dependency links.
1055
+ *
1056
+ * Also evicts the observer watcher cache entry so singleton watchers do not
1057
+ * outlive the artifact's registration.
1058
+ *
1059
+ * @param key The unique identifier of the artifact
1060
+ */
1061
+ unregister<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>): Promise<void>;
1062
+ /**
1063
+ * Resolves an artifact by its key, returning its instance or an error.
1064
+ * Handles dependency resolution, cycle detection, caching, and retry logic.
1065
+ *
1066
+ * The keyed index property (`artifact[key]`) is set inside `cache.package()`
1067
+ * so it is always consistent with `artifact.instance`. No post-hoc mutation
1068
+ * is needed here.
1069
+ *
1070
+ * @param key The unique identifier for the artifact
1071
+ * @param params Parameters with which to resolve the artifact
1072
+ * @returns A Promise that resolves to a ResolvedArtifact
1073
+ * @throws {ArtifactNotFoundError} if the artifact is not found
1074
+ */
1075
+ resolve<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>): Promise<KeyedResolvedArtifact<TRegistry, K>>;
1076
+ /**
1077
+ * Resolves an artifact by its key, returning its instance directly.
1078
+ * Throws if resolution fails.
1079
+ *
1080
+ * @param key The unique identifier for the artifact
1081
+ * @param params Parameters with which to resolve the artifact
1082
+ * @returns A Promise that resolves to the artifact instance
1083
+ * @throws {ArtifactNotFoundError} if the artifact is not found
1084
+ * @throws the artifact's error if resolution failed
1085
+ */
1086
+ require<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>): Promise<TRegistry[K]>;
1087
+ /**
1088
+ * Returns an ArtifactObserver for a given artifact key.
1089
+ * The observer allows subscribing to changes in the artifact's resolved value.
1090
+ *
1091
+ * @param key The unique identifier for the artifact
1092
+ * @param params Parameters with which to resolve the artifact
1093
+ * @param ttl Delay before the watcher is cleaned up if we have no subscriber
1094
+ * @returns An ArtifactObserver instance
1095
+ */
1096
+ watch<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>, ttl?: number): ArtifactObserver<TRegistry, K>;
1097
+ /**
1098
+ * Peeks at the resolved instance of an artifact without triggering resolution
1099
+ * or registering a dependency.
1100
+ *
1101
+ * @param key The unique identifier for the artifact
1102
+ * @returns The artifact instance if already built, otherwise undefined
1103
+ */
1104
+ peek<K extends keyof TRegistry>(key: K, params?: Record<string, unknown>): TRegistry[K] | undefined;
1105
+ /**
1106
+ * Invalidates an artifact, triggering rebuild and cascade to dependents.
1107
+ *
1108
+ * @param key The artifact key to invalidate
1109
+ * @param options.replace If true, forces immediate rebuild bypassing debounce
1110
+ * @param options.params for parametized artifacts
1111
+ */
1112
+ invalidate<K extends keyof TRegistry>(key: K, options?: {
1113
+ replace?: boolean;
1114
+ params?: Record<string, unknown>;
1115
+ }): Promise<void>;
1116
+ /**
1117
+ * Notifies observers that an artifact has changed.
1118
+ * Called by ArtifactManager during stream propagation.
1119
+ *
1120
+ * @param key The artifact key
1121
+ */
1122
+ notifyObservers(key: string): void;
1123
+ /**
1124
+ * Checks if an artifact has active watchers.
1125
+ * Called by ArtifactManager to determine if lazy artifacts should rebuild.
1126
+ *
1127
+ * @param key The artifact key
1128
+ * @returns True if the artifact has active watchers
1129
+ */
1130
+ hasWatchers(key: string): boolean;
1131
+ /**
1132
+ * Disposes of the entire container and all artifacts registered within it.
1133
+ * Releases all resources, stops all watchers, and clears all internal state.
1134
+ *
1135
+ * Returns a Promise that resolves once all artifact teardowns have settled.
1136
+ * Callers should await this method to guarantee full resource release.
1137
+ */
1138
+ dispose(): Promise<void>;
1139
+ }
1140
+
1141
+ /**
1142
+ * @file routing-pipeline.ts
1143
+ * @description A production-grade, asynchronous, type-safe pipeline engine featuring conditional
1144
+ * routing, checkpoint-based pause/resume mechanisms, concurrent step/sub-pipeline execution,
1145
+ * atomic state transactions, and lifecycle event streaming.
1146
+ */
1147
+
1148
+ /** A generic state shape used by the pipeline. */
1149
+ interface State {
1150
+ [key: string]: any;
1151
+ }
1152
+ /**
1153
+ * Instructs the engine to pause the pipeline.
1154
+ * The `pause` field is the `stageId` at which the pipeline should resume.
1155
+ */
1156
+ interface PauseInstruction {
1157
+ readonly pause: string;
1158
+ }
1159
+ /**
1160
+ * All possible outcomes of a router:
1161
+ * - `string` → jump to a named stage
1162
+ * - `null` → terminate the pipeline
1163
+ * - `undefined` → advance to the next stage in order (or natural end)
1164
+ * - `PauseInstruction` → suspend and write a checkpoint
1165
+ */
1166
+ type RoutingInstruction = string | null | undefined | PauseInstruction;
1167
+ /** Type guard for a pause instruction. */
1168
+ declare function isPauseInstruction(v: RoutingInstruction): v is PauseInstruction;
1169
+ /**
1170
+ * Router used inside a **steps‑mode** stage.
1171
+ * Receives the full state and a record of step results keyed by step id.
1172
+ */
1173
+ type StepStageRouter<S extends object> = (state: S, results: Record<string, Result<DeepPartial<S>>>) => RoutingInstruction;
1174
+ /**
1175
+ * Router used inside a **pipelines‑mode** stage.
1176
+ * Receives the full state and a record of sub‑pipeline results keyed by
1177
+ * sub‑pipeline id.
1178
+ */
1179
+ type PipelineStageRouter<S extends object> = (state: S, results: Record<string, Result<PipelineRunResult<S>>>) => RoutingInstruction;
1180
+ /**
1181
+ * Persisted checkpoint written to the run's store under the internal key
1182
+ * `__pipeline_data__.<pipelineId>.<runId>`.
1183
+ *
1184
+ * The checkpoint is always written atomically with the state patches of the
1185
+ * stage that triggered the pause.
1186
+ */
1187
+ interface PipelineCheckpoint {
1188
+ readonly runId: string;
1189
+ readonly pipelineId: string;
1190
+ readonly resumeAt: EntryAddress;
1191
+ readonly pausedAtStageId: string;
1192
+ readonly pausedAtStageLabel: string;
1193
+ readonly pausedOn: string;
1194
+ }
1195
+ /** Engine‑internal namespace for all checkpoint data. */
1196
+ declare const PIPELINE_DATA_KEY: "__pipeline_data__";
1197
+ /**
1198
+ * Run-scoped context injected into every step action as a second argument.
1199
+ *
1200
+ * All fields are immutable and captured at step registration time. Steps can
1201
+ * use `runId` and `pipelineId` to initiate external async operations (e.g.
1202
+ * storing a callback reference for webhook-driven pause/resume). The `signal`
1203
+ * allows long-running async work inside a step to honour pipeline abort.
1204
+ *
1205
+ * For sub-pipeline steps, `pipelineId` reflects the sub-pipeline's own id,
1206
+ * not the root definition id.
1207
+ *
1208
+ * @example
1209
+ * ```ts
1210
+ * const step: Step<MyState> = {
1211
+ * id: "send-email",
1212
+ * label: "Send approval email",
1213
+ * action: async (ctx, pcxt) => {
1214
+ * await emailService.send({
1215
+ * to: ctx.state().approverEmail,
1216
+ * callbackToken: pcxt.runId, // stored so the webhook can resume
1217
+ * });
1218
+ * return {};
1219
+ * },
1220
+ * };
1221
+ * ```
1222
+ */
1223
+ interface PipelineContext {
1224
+ /** The unique identifier of the current run. */
1225
+ readonly runId: string;
1226
+ /**
1227
+ * The id of the pipeline definition this step belongs to.
1228
+ * For sub-pipeline steps this is the sub-pipeline's own id, not the root id.
1229
+ */
1230
+ readonly pipelineId: string;
1231
+ /** The id of the stage this step belongs to. */
1232
+ readonly stageId: string;
1233
+ /** The id of this step. */
1234
+ readonly stepId: string;
1235
+ /**
1236
+ * The AbortSignal for this run. Steps performing long-running async work
1237
+ * should check or pass this signal so they can be cancelled promptly
1238
+ * when `runContext.abort()` is called.
1239
+ */
1240
+ readonly signal: AbortSignal;
1241
+ }
1242
+ /**
1243
+ * A single unit of work.
1244
+ *
1245
+ * The `action` receives an {@link ArtifactFactoryContext} typed to the
1246
+ * pipeline's state shape `S`, and a {@link PipelineContext} carrying the
1247
+ * run-scoped identifiers and abort signal. It must return a partial state
1248
+ * patch on success, or throw on failure.
1249
+ *
1250
+ * The `PipelineContext` is captured at step registration time and is always
1251
+ * consistent with this step's position in the pipeline tree.
1252
+ */
1253
+ interface Step<S extends object = State> {
1254
+ id: string;
1255
+ label: string;
1256
+ scope?: ArtifactScope;
1257
+ timeout?: number;
1258
+ retries?: number;
1259
+ action: (ctx: ArtifactFactoryContext<{}, S, {}>, pcxt: PipelineContext) => Promise<DeepPartial<S>>;
1260
+ }
1261
+ /**
1262
+ * A stage groups steps (steps mode) or sub‑pipelines (pipelines mode).
1263
+ * Exactly one mode is active: if `pipelines` is non‑empty, steps are ignored.
1264
+ */
1265
+ interface Stage<S extends object = State> {
1266
+ id: string;
1267
+ order: number;
1268
+ label: string;
1269
+ timeout?: number;
1270
+ /** Steps defined for this stage. Used only when `pipelines` is empty. */
1271
+ steps?: Record<string, Step<S>>;
1272
+ /** Router for steps mode. */
1273
+ router?: StepStageRouter<S>;
1274
+ /** Sub‑pipelines for this stage. Non‑empty → pipelines mode. */
1275
+ pipelines?: RoutingPipelineDefinition<S>[];
1276
+ /** Router for pipelines mode. */
1277
+ pipelinesRouter?: PipelineStageRouter<S>;
1278
+ }
1279
+ /**
1280
+ * A pipeline definition is a collection of stages.
1281
+ * Every pipeline has a unique `id` and a human‑readable `label`.
1282
+ */
1283
+ interface RoutingPipelineDefinition<S extends object = State> {
1284
+ id: string;
1285
+ label: string;
1286
+ stages: Stage<S>[];
1287
+ }
1288
+ /**
1289
+ * Describes a specific entry point inside a sub‑pipeline.
1290
+ */
1291
+ interface SubPipelineAddress {
1292
+ /** Zero‑based index into the parent stage's `pipelines` array. */
1293
+ index: number;
1294
+ /** Stage id within the sub‑pipeline to start from. */
1295
+ stage: string;
1296
+ /** Optional step id to run (all other steps in the entry stage are skipped). */
1297
+ step?: string;
1298
+ }
1299
+ /**
1300
+ * Describes where in the pipeline tree execution should begin.
1301
+ * Everything after the entry point executes normally.
1302
+ */
1303
+ interface EntryAddress {
1304
+ /** Stage id to start from. All earlier stages are skipped. */
1305
+ stage: string;
1306
+ /** If provided, only this step runs in the entry stage. */
1307
+ step?: string;
1308
+ /** If provided, the stage must be in pipelines mode; only this sub‑pipeline is launched. */
1309
+ pipeline?: SubPipelineAddress;
1310
+ }
1311
+ /**
1312
+ * The outcome of a pipeline run, as a discriminated union on `status`.
1313
+ *
1314
+ * Each variant carries exactly the fields that are always present for that
1315
+ * outcome. Callers narrow with `result.status` and get full type-safety for
1316
+ * variant-specific fields without defensive optional checks.
1317
+ *
1318
+ * - `succeeded` — pipeline ran to completion; `finalState` reflects all committed patches.
1319
+ * - `paused` — a router issued a pause instruction; `checkpoint` encodes the resume address.
1320
+ * - `failed` — a step, router, or transaction threw; `error` carries the cause.
1321
+ */
1322
+ type PipelineRunResult<S extends object> = {
1323
+ status: "succeeded";
1324
+ runId: string;
1325
+ finalState: S;
1326
+ } | {
1327
+ status: "paused";
1328
+ runId: string;
1329
+ finalState: S;
1330
+ checkpoint: PipelineCheckpoint;
1331
+ } | {
1332
+ status: "failed";
1333
+ runId: string;
1334
+ finalState: S;
1335
+ error: SystemError;
1336
+ };
1337
+ /** A node in the event path tree. */
1338
+ type PathNode = {
1339
+ kind: "pipeline";
1340
+ id: string;
1341
+ label: string;
1342
+ } | {
1343
+ kind: "stage";
1344
+ id: string;
1345
+ label: string;
1346
+ } | {
1347
+ kind: "step";
1348
+ id: string;
1349
+ label: string;
1350
+ };
1351
+ /** Ordered list of ancestors from the root pipeline down to the event emitter. */
1352
+ type EventPath = readonly PathNode[];
1353
+ /**
1354
+ * All events emitted during a run.
1355
+ *
1356
+ * stage:paused (#6) is a dedicated event for stages that pause, distinct from
1357
+ * stage:success. Consumers should listen to both if they want to react to all
1358
+ * terminal stage outcomes. stage:success is only emitted when the stage
1359
+ * advances (or terminates) — never when it pauses.
1360
+ */
1361
+ interface RunEventMap<S extends object> {
1362
+ "pipeline:start": {
1363
+ path: EventPath;
1364
+ pipelineId: string;
1365
+ pipelineLabel: string;
1366
+ runId: string;
1367
+ };
1368
+ "pipeline:success": {
1369
+ path: EventPath;
1370
+ pipelineId: string;
1371
+ pipelineLabel: string;
1372
+ runId: string;
1373
+ finalState: S;
1374
+ };
1375
+ "pipeline:paused": {
1376
+ path: EventPath;
1377
+ pipelineId: string;
1378
+ pipelineLabel: string;
1379
+ runId: string;
1380
+ checkpoint: PipelineCheckpoint;
1381
+ finalState: S;
1382
+ };
1383
+ "pipeline:failure": {
1384
+ path: EventPath;
1385
+ pipelineId: string;
1386
+ pipelineLabel: string;
1387
+ runId: string;
1388
+ error: SystemError;
1389
+ };
1390
+ "stage:start": {
1391
+ path: EventPath;
1392
+ stageId: string;
1393
+ stageLabel: string;
1394
+ runId: string;
1395
+ mode: "steps" | "pipelines";
1396
+ };
1397
+ "stage:success": {
1398
+ path: EventPath;
1399
+ stageId: string;
1400
+ stageLabel: string;
1401
+ runId: string;
1402
+ nextInstruction: RoutingInstruction;
1403
+ };
1404
+ /** Emitted when a stage's router returns a pause instruction. Distinct from stage:success. */
1405
+ "stage:paused": {
1406
+ path: EventPath;
1407
+ stageId: string;
1408
+ stageLabel: string;
1409
+ runId: string;
1410
+ checkpoint: PipelineCheckpoint;
1411
+ };
1412
+ "stage:failure": {
1413
+ path: EventPath;
1414
+ stageId: string;
1415
+ stageLabel: string;
1416
+ runId: string;
1417
+ error: SystemError;
1418
+ };
1419
+ "router:evaluated": {
1420
+ path: EventPath;
1421
+ stageId: string;
1422
+ stageLabel: string;
1423
+ runId: string;
1424
+ instruction: RoutingInstruction;
1425
+ interpretation: "jump" | "terminate" | "advance" | "natural-end" | "pause";
1426
+ };
1427
+ "step:start": {
1428
+ path: EventPath;
1429
+ stepId: string;
1430
+ stepLabel: string;
1431
+ runId: string;
1432
+ };
1433
+ "step:success": {
1434
+ path: EventPath;
1435
+ stepId: string;
1436
+ stepLabel: string;
1437
+ runId: string;
1438
+ };
1439
+ "step:failure": {
1440
+ path: EventPath;
1441
+ stepId: string;
1442
+ stepLabel: string;
1443
+ runId: string;
1444
+ error: unknown;
1445
+ };
1446
+ "subpipeline:fork": {
1447
+ path: EventPath;
1448
+ stageId: string;
1449
+ stageLabel: string;
1450
+ runId: string;
1451
+ subPipelineIds: string[];
1452
+ };
1453
+ "subpipeline:join": {
1454
+ path: EventPath;
1455
+ stageId: string;
1456
+ stageLabel: string;
1457
+ runId: string;
1458
+ results: Record<string, Result<PipelineRunResult<S>>>;
1459
+ };
1460
+ }
1461
+ /** Callback type for event subscriptions. */
1462
+ type RunEventHandler<S extends object, K extends keyof RunEventMap<S>> = (payload: RunEventMap<S>[K]) => void;
1463
+ interface ScopedEventBus<S extends object> {
1464
+ emit<K extends keyof RunEventMap<S>>(event: K, payload: RunEventMap<S>[K]): void;
1465
+ on<K extends keyof RunEventMap<S>>(event: K, handler: RunEventHandler<S, K>): () => void;
1466
+ }
1467
+ /**
1468
+ * A unit of execution returned by {@link PipelineEngine.prepare} or
1469
+ * {@link PipelineEngine.resume}.
1470
+ *
1471
+ * Subscribe to lifecycle events via {@link on}, abort via {@link abort}, and
1472
+ * start execution with {@link run}.
1473
+ */
1474
+ interface RunContext<S extends object> {
1475
+ /** The unique identifier of this run (UUID v7). */
1476
+ readonly id: string;
1477
+ /**
1478
+ * Subscribe to lifecycle events for this run.
1479
+ * Sub‑pipeline events bubble here with full ancestry paths.
1480
+ * Returns an unsubscribe function.
1481
+ */
1482
+ on<K extends keyof RunEventMap<S>>(event: K, handler: RunEventHandler<S, K>): () => void;
1483
+ /** Cancel the run. Propagation occurs at the next stage boundary. */
1484
+ abort(): void;
1485
+ /**
1486
+ * Execute the pipeline from the configured entry point.
1487
+ *
1488
+ * Once‑gated: concurrent callers join the in‑flight promise.
1489
+ * A failed run is permanently sealed — obtain a new `RunContext` to retry.
1490
+ * Never throws; failures are returned in a `Result`.
1491
+ */
1492
+ run(): Promise<Result<PipelineRunResult<S>>>;
1493
+ }
1494
+ /** Minimal logger interface used by the engine. */
1495
+ interface EngineLogger {
1496
+ info: (msg: string, ctx?: any) => void;
1497
+ error: (msg: string, ctx?: any) => void;
1498
+ }
1499
+ /**
1500
+ * Configuration for {@link PipelineEngine}.
1501
+ *
1502
+ * @typeParam S - The shape of the state managed by the pipeline.
1503
+ */
1504
+ interface PipelineEngineOptions<S extends object = State> {
1505
+ /** Logger (defaults to a no‑op). */
1506
+ logger?: EngineLogger;
1507
+ /**
1508
+ * **Required.** A factory that, given a `runId`, returns a `DataStore<S>`.
1509
+ * The engine does **not** hold a global store; each run receives its own
1510
+ * isolated store instance.
1511
+ *
1512
+ * For a new run (`prepare`), the factory should return an empty store.
1513
+ * For a resumed run (`resume`), it must return the **same** store that was
1514
+ * used during the original run (so that state and checkpoints are preserved).
1515
+ */
1516
+ storeFactory: (runId: string) => Promise<DataStore<S>>;
1517
+ /**
1518
+ * Optional factory that produces the initial state for every **new** run.
1519
+ * The returned object is written to the store during `prepare()`.
1520
+ * If omitted, the store remains empty.
1521
+ */
1522
+ initialStateFactory?: () => S;
1523
+ }
1524
+ /**
1525
+ * The entry point for creating and resuming pipeline runs.
1526
+ *
1527
+ * @typeParam S - The shape of the state object.
1528
+ *
1529
+ * @example
1530
+ * ```ts
1531
+ * const engine = new PipelineEngine(myDefinition, {
1532
+ * storeFactory: (runId) => createMyStore(runId),
1533
+ * initialStateFactory: () => ({ counter: 0 }),
1534
+ * });
1535
+ *
1536
+ * const ctx = await engine.prepare({ stage: "validate" });
1537
+ * ctx.on("pipeline:success", (e) => console.log("done", e.finalState));
1538
+ * const result = await ctx.run();
1539
+ * ```
1540
+ */
1541
+ declare class PipelineEngine<S extends object> {
1542
+ private readonly definition;
1543
+ private readonly logger;
1544
+ private readonly storeFactory;
1545
+ private readonly initialStateFactory;
1546
+ private readonly index;
1547
+ /**
1548
+ * Constructs an engine tied to a fixed pipeline definition.
1549
+ *
1550
+ * @param definition - The pipeline topology (stages, steps, routers).
1551
+ * @param options - Engine configuration. `storeFactory` is mandatory.
1552
+ */
1553
+ constructor(definition: RoutingPipelineDefinition<S>, options: PipelineEngineOptions<S>);
1554
+ /**
1555
+ * Prepare an isolated {@link RunContext} for a **new** run.
1556
+ *
1557
+ * A fresh store is obtained via `storeFactory`, optionally seeded with the
1558
+ * initial state from `initialStateFactory`. No execution occurs until
1559
+ * `runContext.run()` is called.
1560
+ *
1561
+ * @param entry - Optional address describing where to start execution.
1562
+ * Omit to start from the lowest‑order stage.
1563
+ * @param runId - Optional run identifier (UUID v7). Generated if omitted.
1564
+ * @returns A promise that resolves with a ready‑to‑run `RunContext`.
1565
+ */
1566
+ prepare(entry?: EntryAddress, runId?: string): Promise<RunContext<S>>;
1567
+ /**
1568
+ * Reconstruct a {@link RunContext} for a previously paused run.
1569
+ *
1570
+ * The store for the given `runId` must still contain the checkpoint and
1571
+ * state at the time of the pause. The context is returned ready to run;
1572
+ * no state is altered until `runContext.run()` is called.
1573
+ *
1574
+ * @param runId - The identifier of the paused run.
1575
+ * @returns A result containing the `RunContext`, or a failure if no
1576
+ * checkpoint exists or the pipeline id does not match.
1577
+ */
1578
+ resume(runId: string): Promise<Result<RunContext<S>>>;
1579
+ /**
1580
+ * Constructs a {@link RunContextImpl} with all necessary dependencies.
1581
+ *
1582
+ * This method is package-internal. External callers use prepare() or resume().
1583
+ * Sub-pipelines access it through the {@link SubPipelineFactory} interface,
1584
+ * which is the only reference RunContextImpl holds to the engine.
1585
+ *
1586
+ * A single {@link ArtifactContainer} is created per run at root level and
1587
+ * shared across all sub-pipelines. Steps are registered under namespaced keys
1588
+ * encoding their full lineage (keyPrefix:stageId:stepId), ensuring cache
1589
+ * isolation without allocating separate containers per sub-pipeline.
1590
+ *
1591
+ * The {@link AbortController} is created here and its signal is immediately
1592
+ * threaded into {@link registerSteps} so that every step factory closure
1593
+ * captures the correct signal at registration time.
1594
+ *
1595
+ * @param runId - The run identifier (same for parent and sub‑pipelines).
1596
+ * @param pipeline - The pipeline (sub‑)definition.
1597
+ * @param entry - Entry address; `undefined` means start from the beginning.
1598
+ * @param store - The shared store instance for this run.
1599
+ * @param parentBus - Parent scoped bus for event bubbling (root runs pass undefined).
1600
+ * @param parentPath - Event path from the root.
1601
+ * @param container - Shared container (created once at root; passed down to sub-pipelines).
1602
+ * @param keyPrefix - Namespacing prefix for artifact keys within the shared container.
1603
+ */
1604
+ buildRunContext(runId: string, pipeline: RoutingPipelineDefinition<S>, entry: EntryAddress | undefined, store: DataStore<S>, parentBus: ScopedEventBus<S> | undefined, parentPath: EventPath, container?: ArtifactContainer<Record<string, DeepPartial<S>>, S>, keyPrefix?: string): RunContext<S>;
1605
+ }
1606
+
1607
+ export { type EngineLogger, type EntryAddress, type EventPath, PIPELINE_DATA_KEY, type PathNode, type PauseInstruction, Pipeline, type PipelineCheckpoint, type PipelineContext, type PipelineDefinition, PipelineEngine, type PipelineEngineOptions, type PipelineEventMap, type PipelineRunResult, type PipelineStageRouter, type PipelineStep, type PipelineStepDefinition, Result, type RoutingInstruction, type RoutingPipelineDefinition, type RunContext, type RunEventHandler, type RunEventMap, SequentialExecutionContext, type Stage, type StageCarry, type State, type Step, type StepStageRouter, type SubPipelineAddress, isPauseInstruction };