@bluelibs/runner 4.9.0 → 5.1.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.
@@ -1,15 +1,212 @@
1
+ import * as lru_cache from 'lru-cache';
1
2
  import { Readable } from 'stream';
2
3
  export { Readable } from 'stream';
3
4
  import * as http from 'http';
4
5
  import { IncomingMessage, ServerResponse } from 'http';
5
- export { EJSON } from '@bluelibs/ejson';
6
+ import { AsyncLocalStorage } from 'node:async_hooks';
7
+ import { Request, Router } from 'express';
6
8
 
7
- interface Serializer {
9
+ /**
10
+ * Type definitions for the Serializer class
11
+ */
12
+ /**
13
+ * Definition for a custom type that can be serialized/deserialized
14
+ */
15
+ interface TypeDefinition<TInstance = unknown, TSerialized = unknown> {
16
+ /** Unique identifier for the type */
17
+ id: string;
18
+ /** Predicate function to check if an object matches this type */
19
+ is: (obj: unknown) => obj is TInstance;
20
+ /** Function to serialize the object */
21
+ serialize: (obj: TInstance) => TSerialized;
22
+ /** Function to deserialize the data back to the original object */
23
+ deserialize: (data: TSerialized) => TInstance;
24
+ /** Optional factory used to create a placeholder during deserialization */
25
+ create?: () => TInstance;
26
+ /** Serialization strategy: 'value' (inline, no identity) or 'ref' (graph node, identity preserved). Default: 'ref' */
27
+ strategy?: "value" | "ref";
28
+ }
29
+ /** Reference to another object in the serialization */
30
+ interface ObjectReference {
31
+ /** Reference to object ID */
32
+ __ref: string;
33
+ }
34
+ /**
35
+ * Discriminated union describing the serialized graph payload.
36
+ * Each node captures either an array, plain object, or typed payload.
37
+ */
38
+ type SerializedNode = {
39
+ kind: "array";
40
+ value: SerializedValue[];
41
+ } | {
42
+ kind: "object";
43
+ value: Record<string, SerializedValue>;
44
+ } | {
45
+ kind: "type";
46
+ type: string;
47
+ value: SerializedValue;
48
+ };
49
+ /**
50
+ * Serialization context for tracking object references
51
+ */
52
+ interface SerializationContext {
53
+ /** Map of objects to their IDs */
54
+ objectIds: WeakMap<object, string>;
55
+ /** Counter for generating unique IDs */
56
+ idCounter: number;
57
+ /** Number of graph nodes recorded */
58
+ nodeCount: number;
59
+ /** Nodes collected during serialization (id -> serialized node) */
60
+ nodes: Record<string, SerializedNode>;
61
+ }
62
+ /**
63
+ * Deserialization context used when materialising a graph payload.
64
+ */
65
+ interface DeserializationContext {
66
+ nodes: Record<string, SerializedNode>;
67
+ resolved: Map<string, unknown>;
68
+ resolving: Set<string>;
69
+ /**
70
+ * Tracks reference ids that were requested while still being resolved.
71
+ * Used to detect circular references that rely on placeholders.
72
+ */
73
+ resolvingRefs: Set<string>;
74
+ }
75
+ /**
76
+ * Union type for serialized values
77
+ */
78
+ type JsonPrimitive = string | number | boolean | null;
79
+ interface SerializedTypeRecord {
80
+ __type: string;
81
+ value: SerializedValue;
82
+ }
83
+ type SerializedValue = JsonPrimitive | ObjectReference | SerializedTypeRecord | SerializedValue[] | {
84
+ [key: string]: SerializedValue;
85
+ };
86
+ declare enum SymbolPolicy {
87
+ AllowAll = "AllowAll",
88
+ WellKnownOnly = "WellKnownOnly",
89
+ Disabled = "Disabled"
90
+ }
91
+ /**
92
+ * Main serializer options
93
+ */
94
+ interface SerializerOptions {
95
+ /** Whether to pretty-print JSON (for debugging) */
96
+ pretty?: boolean;
97
+ /** Maximum recursion depth allowed during serialize/deserialize */
98
+ maxDepth?: number;
99
+ /** Restrict deserialization to this list of type IDs */
100
+ allowedTypes?: readonly string[];
101
+ /** Controls which Symbol payloads may be deserialized */
102
+ symbolPolicy?: SymbolPolicy;
103
+ /** Maximum accepted RegExp pattern length during deserialization */
104
+ maxRegExpPatternLength?: number;
105
+ /** Allow RegExp patterns that fail the safety heuristic */
106
+ allowUnsafeRegExp?: boolean;
107
+ }
108
+ /**
109
+ * Minimal serializer contract used across transports and persistence.
110
+ * Implementations must be able to round-trip JSON-compatible payloads and
111
+ * should support custom value types via `addType`.
112
+ */
113
+ interface SerializerLike {
8
114
  stringify(value: unknown): string;
9
115
  parse<T = unknown>(text: string): T;
10
- addType?<TJson = unknown, T = unknown>(name: string, factory: (json: TJson) => T): void;
116
+ addType?<TJson = unknown, TInstance = unknown>(name: string, factory: (json: TJson) => TInstance): void;
117
+ }
118
+
119
+ /**
120
+ * Graph-aware serializer/deserializer with circular reference
121
+ * handling and pluggable type support.
122
+ *
123
+ * Internal protocol reference: `readmes/SERIALIZER_PROTOCOL.md`.
124
+ */
125
+
126
+ declare class Serializer {
127
+ /** Type registry for managing custom types */
128
+ private readonly typeRegistry;
129
+ private readonly runtimeOptions;
130
+ /** JSON indentation width when pretty printing is enabled */
131
+ private readonly indent;
132
+ /** Maximum recursion depth allowed */
133
+ private readonly maxDepth;
134
+ /** Maximum allowed RegExp pattern length during deserialization */
135
+ private readonly maxRegExpPatternLength;
136
+ /** Allow RegExp patterns that fail the safety heuristic */
137
+ private readonly allowUnsafeRegExp;
138
+ /** Disallowed keys that can lead to prototype pollution */
139
+ private readonly unsafeKeys;
140
+ constructor(options?: SerializerOptions);
141
+ /**
142
+ * Alias of `serialize()` to match the historical tunnel serializer surface.
143
+ */
144
+ stringify<T>(value: T): string;
145
+ /**
146
+ * Alias of `deserialize()` to match the historical tunnel serializer surface.
147
+ */
148
+ parse<T = unknown>(payload: string): T;
149
+ /**
150
+ * Serialize an arbitrary value into a JSON string.
151
+ */
152
+ serialize<T>(value: T, context?: SerializationContext): string;
153
+ /**
154
+ * Deserialize a JSON string back to its original value.
155
+ */
156
+ deserialize<T = unknown>(payload: string): T;
157
+ /**
158
+ * Register a custom type for serialization/deserialization.
159
+ */
160
+ addType<TInstance, TSerialized>(typeDef: TypeDefinition<TInstance, TSerialized>): void;
161
+ addType<TJson = unknown, TInstance = unknown>(name: string, factory: (json: TJson) => TInstance): void;
162
+ /**
163
+ * @internal - Exposed for testing RegExp safety validation
164
+ */
165
+ readonly isRegExpPatternSafe: (pattern: string) => boolean;
166
+ /**
167
+ * @internal - Exposed for testing quantifier detection
168
+ */
169
+ readonly isQuantifierAt: (pattern: string, index: number) => boolean;
170
+ /**
171
+ * @internal - Exposed for testing quantifier character detection
172
+ */
173
+ readonly isQuantifierChar: (char: string, pattern: string, index: number) => boolean;
174
+ /**
175
+ * @internal - Exposed for testing bounded quantifier detection
176
+ */
177
+ readonly isBoundedQuantifier: (pattern: string, index: number) => boolean;
178
+ /**
179
+ * @internal - Exposed for test compatibility
180
+ */
181
+ toNodeRecord(nodes: Record<string, SerializedNode>): Record<string, SerializedNode>;
182
+ /**
183
+ * @internal - Exposed for test compatibility
184
+ */
185
+ deserializeValue(value: SerializedValue, context: DeserializationContext, depth?: number): unknown;
186
+ /**
187
+ * @internal - Exposed for test compatibility
188
+ */
189
+ resolveReference(id: string, context: DeserializationContext, depth?: number): unknown;
190
+ /**
191
+ * @internal - Exposed for test compatibility
192
+ */
193
+ mergePlaceholder(placeholder: unknown, result: unknown): unknown;
194
+ /**
195
+ * @internal - Exposed for test compatibility
196
+ */
197
+ isSerializedTypeRecord(value: unknown): value is {
198
+ __type: string;
199
+ value: unknown;
200
+ };
201
+ private jsonStringify;
11
202
  }
12
203
 
204
+ /**
205
+ * Main export module for the Serializer
206
+ */
207
+
208
+ declare function getDefaultSerializer(): Serializer;
209
+
13
210
  declare const CONTRACT: unique symbol;
14
211
  type CONTRACT = typeof CONTRACT;
15
212
  interface IContractable<TConfig = any, TInput = void, TOutput = void> {
@@ -89,7 +286,7 @@ interface IAsyncContextMeta extends IMeta {
89
286
  interface ITaggable {
90
287
  tags: TagType[];
91
288
  }
92
- interface ITagDefinition<TConfig = void, TEnforceInputContract = void, TEnforceOutputContract = void> {
289
+ interface ITagDefinition<TConfig = void, _TEnforceInputContract = void, _TEnforceOutputContract = void> {
93
290
  id: string;
94
291
  meta?: ITagMeta;
95
292
  configSchema?: IValidationSchema<TConfig>;
@@ -120,7 +317,7 @@ interface ITag<TConfig = void, TEnforceInputContract = void, TEnforceOutputContr
120
317
  [symbolFilePath]: string;
121
318
  [symbolTag]: true;
122
319
  }
123
- type ITagWithOptionalConfig<TValue, TEnforceInputContract, TEnforceOutputContract> = ITag<any, TEnforceInputContract, TEnforceOutputContract> & {
320
+ type ITagWithOptionalConfig<_TValue, TEnforceInputContract, TEnforceOutputContract> = ITag<any, TEnforceInputContract, TEnforceOutputContract> & {
124
321
  readonly __configHasOnlyOptionalKeys: true;
125
322
  };
126
323
  interface ITagConfigured<TConfig = void, TEnforceInputContract = void, TEnforceOutputContract = void> extends ITag<TConfig, TEnforceInputContract, TEnforceOutputContract> {
@@ -139,6 +336,8 @@ declare const symbolTask: unique symbol;
139
336
  /** Marks a task as a phantom task (no-op run; meant to be tunneled/routed). */
140
337
  declare const symbolPhantomTask: unique symbol;
141
338
  declare const symbolResource: unique symbol;
339
+ /** @internal Marks forked resources and records fork provenance */
340
+ declare const symbolResourceForkedFrom: unique symbol;
142
341
  declare const symbolResourceWithConfig: unique symbol;
143
342
  declare const symbolEvent: unique symbol;
144
343
  /** @internal Marks an error helper definition */
@@ -162,9 +361,107 @@ declare const symbolFilePath: unique symbol;
162
361
  /** @internal Marks an async context definition */
163
362
  declare const symbolAsyncContext: unique symbol;
164
363
 
364
+ interface IResourceMiddlewareDefinition<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> {
365
+ id: string;
366
+ /** Static or lazy dependency map. */
367
+ dependencies?: TDependencies | ((config: TConfig) => TDependencies);
368
+ /**
369
+ * Optional validation schema for runtime config validation.
370
+ * When provided, middleware config will be validated when .with() is called.
371
+ */
372
+ configSchema?: IValidationSchema<TConfig>;
373
+ /**
374
+ * The middleware body, called with resource execution input.
375
+ */
376
+ run: (input: IResourceMiddlewareExecutionInput<TEnforceInputContract extends void ? any : TEnforceInputContract, TEnforceOutputContract extends void ? any : TEnforceOutputContract>, dependencies: DependencyValuesType<TDependencies>, config: TConfig) => Promise<any>;
377
+ meta?: IMiddlewareMeta;
378
+ tags?: TagType[];
379
+ everywhere?: boolean | ((resource: IResource<any, any, any, any, any>) => boolean);
380
+ }
381
+ interface IResourceMiddleware<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> extends IResourceMiddlewareDefinition<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>, IContractable<TConfig, TEnforceInputContract, TEnforceOutputContract> {
382
+ [symbolResourceMiddleware]: true;
383
+ id: string;
384
+ dependencies: TDependencies | ((config: TConfig) => TDependencies);
385
+ /** Current configuration object (empty by default). */
386
+ config: TConfig;
387
+ /** Configure the middleware and return a marked, configured instance. */
388
+ with: (config: TConfig) => IResourceMiddlewareConfigured<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
389
+ [symbolFilePath]: string;
390
+ tags: TagType[];
391
+ }
392
+ interface IResourceMiddlewareConfigured<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> extends IResourceMiddleware<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies> {
393
+ [symbolMiddlewareConfigured]: true;
394
+ }
395
+ interface IResourceMiddlewareExecutionInput<TResourceConfig = any, TResourceOutput = any> {
396
+ /** Resource hook */
397
+ resource: {
398
+ definition: IResource<TResourceConfig, any, any, any, any>;
399
+ config: TResourceConfig;
400
+ };
401
+ next: (resourceConfig?: TResourceConfig) => Promise<TResourceOutput>;
402
+ }
403
+ type ResourceMiddlewareAttachmentType = IResourceMiddleware<void, any, any, any> | IResourceMiddleware<{
404
+ [K in any]?: any;
405
+ }, any, any, any> | IResourceMiddlewareConfigured<any, any, any, any>;
406
+
407
+ type ErrorReference = string | IErrorHelper<any>;
408
+ type ThrowsList = ReadonlyArray<ErrorReference>;
409
+ interface IErrorDefinition<TData extends DefaultErrorType = DefaultErrorType> {
410
+ id: string;
411
+ serialize?: (data: TData) => string;
412
+ parse?: (data: string) => TData;
413
+ format?: (data: TData) => string;
414
+ /**
415
+ * Validate error data on throw(). If provided, data is parsed first.
416
+ */
417
+ dataSchema?: IValidationSchema<TData>;
418
+ meta?: IErrorMeta;
419
+ }
420
+ interface IErrorDefinitionFinal<TData extends DefaultErrorType> extends IErrorDefinition<TData> {
421
+ format: (data: TData) => string;
422
+ }
423
+ type DefaultErrorType = Record<string, unknown>;
424
+ /**
425
+ * Runtime helper returned by defineError()/r.error().
426
+ * Contains helpers to throw typed errors and perform type-safe checks.
427
+ */
428
+ interface IErrorHelper<TData extends DefaultErrorType = DefaultErrorType> {
429
+ /** Unique id for registration and DI */
430
+ id: string;
431
+ /** Throw a typed error with the given data */
432
+ throw(data: TData): never;
433
+ /** Type guard for checking if an unknown error is this error */
434
+ is(error: unknown): boolean;
435
+ /** Brand symbol for runtime detection */
436
+ [symbolError]: true;
437
+ /** Return an optional dependency wrapper for this error */
438
+ optional(): IOptionalDependency<IErrorHelper<TData>>;
439
+ }
440
+
441
+ type ResourceForkRegisterMode = "keep" | "drop" | "deep";
442
+ interface ResourceForkOptions {
443
+ /**
444
+ * Control whether the fork keeps the base `register` list.
445
+ * - "keep" (default) keeps registration items
446
+ * - "drop" clears registration items
447
+ * - "deep" deep-forks registered resources with new ids (resource tree)
448
+ */
449
+ register?: ResourceForkRegisterMode;
450
+ /**
451
+ * Used with `register: "deep"` to derive ids for deep-forked resources.
452
+ * Defaults to `(id) => \`\${newId}.\${id}\``.
453
+ */
454
+ reId?: (id: string) => string;
455
+ }
456
+ interface ResourceForkInfo {
457
+ /** The id of the resource that was forked. */
458
+ readonly fromId: string;
459
+ /** Best-effort call-site file path for the fork operation. */
460
+ readonly forkedAtFilePath: string;
461
+ }
165
462
  type IsAny<T> = 0 extends 1 & T ? true : false;
166
463
  type IsUnspecified<T> = [T] extends [undefined] ? true : [T] extends [void] ? true : IsAny<T> extends true ? true : false;
167
- interface IResourceDefinition<TConfig = any, TValue extends Promise<any> = Promise<any>, TDependencies extends DependencyMapType = {}, TContext = any, THooks = any, TRegisterableItems = any, TMeta extends IResourceMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends ResourceMiddlewareAttachmentType[] = ResourceMiddlewareAttachmentType[]> {
464
+ interface IResourceDefinition<TConfig = any, TValue extends Promise<any> = Promise<any>, TDependencies extends DependencyMapType = {}, TContext = any, _THooks = any, _TRegisterableItems = any, TMeta extends IResourceMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends ResourceMiddlewareAttachmentType[] = ResourceMiddlewareAttachmentType[]> {
168
465
  /** Stable identifier. */
169
466
  id: string;
170
467
  /** Static or lazy dependency map. Receives `config` when provided. */
@@ -194,6 +491,16 @@ interface IResourceDefinition<TConfig = any, TValue extends Promise<any> = Promi
194
491
  */
195
492
  dispose?: (this: any, value: TValue extends Promise<infer U> ? U : TValue, config: TConfig, dependencies: ResourceDependencyValuesType<TDependencies>, context: TContext) => Promise<void>;
196
493
  meta?: TMeta;
494
+ /**
495
+ * Declares which typed errors are part of this resource's contract.
496
+ *
497
+ * This is a declarative contract only:
498
+ * - It does not imply dependency injection
499
+ * - It does not enforce that only these errors can be thrown
500
+ *
501
+ * Use string ids or Error helpers.
502
+ */
503
+ throws?: ThrowsList;
197
504
  /**
198
505
  * Optional validation schema for runtime config validation.
199
506
  * When provided, resource config will be validated when .with() is called.
@@ -230,9 +537,19 @@ interface IResource<TConfig = void, TValue extends Promise<any> = Promise<any>,
230
537
  middleware: TMiddleware;
231
538
  [symbolFilePath]: string;
232
539
  [symbolResource]: true;
540
+ /** Present only on forked resources. */
541
+ [symbolResourceForkedFrom]?: ResourceForkInfo;
542
+ /** Normalized list of error ids declared via `throws`. */
543
+ throws?: readonly string[];
233
544
  /** Return an optional dependency wrapper for this resource. */
234
545
  optional: () => IOptionalDependency<IResource<TConfig, TValue, TDependencies, TContext, TMeta, TTags, TMiddleware>>;
235
546
  tags: TTags;
547
+ /**
548
+ * Create a new resource with a different id but the same definition.
549
+ * Useful for creating multiple instances of a "template" resource.
550
+ * The forked resource should be exported and used as a dependency.
551
+ */
552
+ fork(newId: string, options?: ResourceForkOptions): IResource<TConfig, TValue, TDependencies, TContext, TMeta, TTags, TMiddleware>;
236
553
  }
237
554
  interface IResourceWithConfig<TConfig = any, TValue extends Promise<any> = Promise<any>, TDependencies extends DependencyMapType = any, TContext = any, TMeta extends IResourceMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends IResourceMiddleware<any, any, any, any>[] = IResourceMiddleware[]> {
238
555
  [symbolResourceWithConfig]: true;
@@ -244,55 +561,34 @@ interface IResourceWithConfig<TConfig = any, TValue extends Promise<any> = Promi
244
561
  config: TConfig;
245
562
  }
246
563
 
247
- interface ITaskDefinition<TInput = undefined, TOutput extends Promise<any> = any, TDependencies extends DependencyMapType = {}, TMeta extends ITaskMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> {
248
- id: string;
249
- /**
250
- * Access other tasks/resources/events. Can be an object or a function when
251
- * you need late or config‑dependent resolution.
252
- */
253
- dependencies?: TDependencies | (() => TDependencies);
254
- /** Middleware applied around task execution. */
255
- middleware?: TMiddleware;
256
- /** Optional metadata used for docs, filtering and tooling. */
257
- meta?: TMeta;
258
- /**
259
- * Optional validation schema for runtime input validation.
260
- * When provided, task input will be validated before execution.
261
- */
262
- inputSchema?: IValidationSchema<TInput>;
263
- /**
264
- * Optional validation schema for the task result.
265
- * When provided, the result will be validated immediately after the task's
266
- * `run` resolves, without considering middleware.
267
- */
268
- resultSchema?: IValidationSchema<TOutput extends Promise<infer U> ? U : never>;
269
- run: (input: HasInputContracts<[...TTags, ...TMiddleware]> extends true ? [TInput] extends [undefined] ? InferInputOrViolationFromContracts<[...TTags, ...TMiddleware]> : EnsureInputSatisfiesContracts<[...TTags, ...TMiddleware], TInput> : TInput, dependencies: DependencyValuesType<TDependencies>) => HasOutputContracts<[...TTags, ...TMiddleware]> extends true ? EnsureOutputSatisfiesContracts<[...TTags, ...TMiddleware], TOutput> : TOutput;
564
+ /**
565
+ * Typed key used to store/retrieve values from an ExecutionJournal.
566
+ * The `id` is used as the storage slot.
567
+ */
568
+ declare const journalKeyBrand: unique symbol;
569
+ type JournalKey<T> = {
570
+ readonly id: string;
571
+ readonly [journalKeyBrand]?: (value: T) => T;
572
+ };
573
+ /**
574
+ * Options for setting values in the journal.
575
+ */
576
+ interface JournalSetOptions {
270
577
  /**
271
- * Tags applied to the task that might define its behvaiour or impact the systems.
578
+ * If true, allows overwriting an existing value.
579
+ * By default, attempting to set a key that already exists will throw an error.
272
580
  */
273
- tags?: TTags;
581
+ override?: boolean;
274
582
  }
275
- interface ITask<TInput = any, TOutput extends Promise<any> = any, TDependencies extends DependencyMapType = {}, TMeta extends ITaskMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> extends ITaskDefinition<TInput, TOutput, TDependencies, TMeta, TTags, TMiddleware> {
276
- [symbolFilePath]: string;
277
- [symbolTask]: true;
278
- /** Present only for phantom tasks. */
279
- [symbolPhantomTask]?: true;
280
- /** Indicates if the task is tunneled through a tunnel client. */
281
- isTunneled?: boolean;
282
- /** Records which tunnel resource owns the task (exclusivity). */
283
- [symbolTunneledBy]?: string;
284
- id: string;
285
- dependencies: TDependencies | (() => TDependencies);
286
- computedDependencies?: DependencyValuesType<TDependencies>;
287
- middleware: TMiddleware;
288
- /** Return an optional dependency wrapper for this task. */
289
- optional: () => IOptionalDependency<ITask<TInput, TOutput, TDependencies, TMeta, TTags, TMiddleware>>;
290
- tags: TTags;
583
+ /**
584
+ * Per-execution registry that allows middleware and tasks to share state.
585
+ * A new journal is created for each top-level task execution unless explicitly forwarded.
586
+ */
587
+ interface ExecutionJournal {
588
+ set<T>(key: JournalKey<T>, value: T, options?: JournalSetOptions): void;
589
+ get<T>(key: JournalKey<T>): T | undefined;
590
+ has<T>(key: JournalKey<T>): boolean;
291
591
  }
292
- /** Narrowed type for phantom tasks (no-op run by default). */
293
- type IPhantomTask<TInput = any, TResolved = any, TDependencies extends DependencyMapType = {}, TMeta extends ITaskMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> = ITask<TInput, Promise<TResolved>, TDependencies, TMeta, TTags, TMiddleware> & {
294
- [symbolPhantomTask]: true;
295
- };
296
592
 
297
593
  interface ITaskMiddlewareDefinition<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> {
298
594
  id: string;
@@ -315,7 +611,7 @@ interface ITaskMiddleware<TConfig = any, TEnforceInputContract = void, TEnforceO
315
611
  [symbolTaskMiddleware]: true;
316
612
  [symbolFilePath]: string;
317
613
  id: string;
318
- dependencies: TDependencies | (() => TDependencies);
614
+ dependencies: TDependencies | ((config: TConfig) => TDependencies);
319
615
  /** Current configuration object (empty by default). */
320
616
  config: TConfig;
321
617
  /** Configure the middleware and return a marked, configured instance. */
@@ -333,72 +629,76 @@ interface ITaskMiddlewareExecutionInput<TTaskInput = any, TTaskOutput = any> {
333
629
  input: TTaskInput;
334
630
  };
335
631
  next: (taskInput?: TTaskInput) => Promise<TTaskOutput>;
632
+ /** Per-execution registry for sharing state between middleware and task */
633
+ journal: ExecutionJournal;
336
634
  }
337
635
  type TaskMiddlewareAttachmentType = ITaskMiddleware<void, any, any, any> | ITaskMiddleware<{
338
636
  [K in any]?: any;
339
637
  }, any, any, any> | ITaskMiddlewareConfigured<any, any, any, any>;
340
638
 
341
- interface IResourceMiddlewareDefinition<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> {
639
+ interface ITaskDefinition<TInput = undefined, TOutput extends Promise<any> = any, TDependencies extends DependencyMapType = {}, TMeta extends ITaskMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> {
342
640
  id: string;
343
- /** Static or lazy dependency map. */
344
- dependencies?: TDependencies | ((config: TConfig) => TDependencies);
345
641
  /**
346
- * Optional validation schema for runtime config validation.
347
- * When provided, middleware config will be validated when .with() is called.
642
+ * Access other tasks/resources/events. Can be an object or a function when
643
+ * you need late or config‑dependent resolution.
348
644
  */
349
- configSchema?: IValidationSchema<TConfig>;
645
+ dependencies?: TDependencies | (() => TDependencies);
646
+ /** Middleware applied around task execution. */
647
+ middleware?: TMiddleware;
648
+ /** Optional metadata used for docs, filtering and tooling. */
649
+ meta?: TMeta;
350
650
  /**
351
- * The middleware body, called with resource execution input.
651
+ * Optional validation schema for runtime input validation.
652
+ * When provided, task input will be validated before execution.
352
653
  */
353
- run: (input: IResourceMiddlewareExecutionInput<TEnforceInputContract extends void ? any : TEnforceInputContract, TEnforceOutputContract extends void ? any : TEnforceOutputContract>, dependencies: DependencyValuesType<TDependencies>, config: TConfig) => Promise<any>;
354
- meta?: IMiddlewareMeta;
355
- tags?: TagType[];
356
- everywhere?: boolean | ((resource: IResource<any, any, any, any, any>) => boolean);
654
+ inputSchema?: IValidationSchema<TInput>;
655
+ /**
656
+ * Optional validation schema for the task result.
657
+ * When provided, the result will be validated immediately after the task's
658
+ * `run` resolves, without considering middleware.
659
+ */
660
+ resultSchema?: IValidationSchema<TOutput extends Promise<infer U> ? U : never>;
661
+ /**
662
+ * Declares which typed errors are part of this task's contract.
663
+ *
664
+ * This is a declarative contract only:
665
+ * - It does not imply dependency injection
666
+ * - It does not enforce that only these errors can be thrown
667
+ *
668
+ * Use string ids or Error helpers.
669
+ */
670
+ throws?: ThrowsList;
671
+ run: (input: HasInputContracts<[...TTags, ...TMiddleware]> extends true ? [TInput] extends [undefined] ? InferInputOrViolationFromContracts<[...TTags, ...TMiddleware]> : EnsureInputSatisfiesContracts<[...TTags, ...TMiddleware], TInput> : TInput, dependencies: DependencyValuesType<TDependencies>, context?: {
672
+ journal: ExecutionJournal;
673
+ }) => HasOutputContracts<[...TTags, ...TMiddleware]> extends true ? EnsureOutputSatisfiesContracts<[...TTags, ...TMiddleware], TOutput> : TOutput;
674
+ /**
675
+ * Tags applied to the task that might define its behvaiour or impact the systems.
676
+ */
677
+ tags?: TTags;
357
678
  }
358
- interface IResourceMiddleware<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> extends IResourceMiddlewareDefinition<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>, IContractable<TConfig, TEnforceInputContract, TEnforceOutputContract> {
359
- [symbolResourceMiddleware]: true;
679
+ interface ITask<TInput = any, TOutput extends Promise<any> = any, TDependencies extends DependencyMapType = {}, TMeta extends ITaskMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> extends ITaskDefinition<TInput, TOutput, TDependencies, TMeta, TTags, TMiddleware> {
680
+ [symbolFilePath]: string;
681
+ [symbolTask]: true;
682
+ /** Present only for phantom tasks. */
683
+ [symbolPhantomTask]?: true;
684
+ /** Indicates if the task is tunneled through a tunnel client. */
685
+ isTunneled?: boolean;
686
+ /** Records which tunnel resource owns the task (exclusivity). */
687
+ [symbolTunneledBy]?: string;
360
688
  id: string;
361
689
  dependencies: TDependencies | (() => TDependencies);
362
- /** Current configuration object (empty by default). */
363
- config: TConfig;
364
- /** Configure the middleware and return a marked, configured instance. */
365
- with: (config: TConfig) => IResourceMiddlewareConfigured<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
366
- [symbolFilePath]: string;
367
- tags: TagType[];
368
- }
369
- interface IResourceMiddlewareConfigured<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> extends IResourceMiddleware<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies> {
370
- [symbolMiddlewareConfigured]: true;
371
- }
372
- interface IResourceMiddlewareExecutionInput<TResourceConfig = any, TResourceOutput = any> {
373
- /** Resource hook */
374
- resource: {
375
- definition: IResource<TResourceConfig, any, any, any, any>;
376
- config: TResourceConfig;
377
- };
378
- next: (resourceConfig?: TResourceConfig) => Promise<TResourceOutput>;
379
- }
380
- type ResourceMiddlewareAttachmentType = IResourceMiddleware<void, any, any, any> | IResourceMiddleware<{
381
- [K in any]?: any;
382
- }, any, any, any> | IResourceMiddlewareConfigured<any, any, any, any>;
383
-
384
- type OnType = "*" | IEventDefinition<any> | readonly IEventDefinition<any>[];
385
- interface IHookDefinition<TDependencies extends DependencyMapType = {}, TOn extends OnType = any, TMeta extends ITaskMeta = any> {
386
- id: string;
387
- dependencies?: TDependencies | (() => TDependencies);
388
- on: TOn;
389
- /** Listener execution order. Lower numbers run first. */
390
- order?: number;
391
- meta?: TMeta;
392
- run: (event: IEventEmission<TOn extends "*" ? any : TOn extends readonly IEventDefinition<any>[] ? CommonPayload<TOn> : ExtractEventPayload<TOn>>, dependencies: DependencyValuesType<TDependencies>) => Promise<any>;
393
- tags?: TagType[];
394
- }
395
- interface IHook<TDependencies extends DependencyMapType = {}, TOn extends OnType = any, TMeta extends ITaskMeta = any> extends IHookDefinition<TDependencies, TOn, TMeta> {
396
- id: string;
397
- dependencies: TDependencies | (() => TDependencies);
398
- [symbolFilePath]: string;
399
- [symbolHook]: true;
400
- tags: TagType[];
690
+ computedDependencies?: DependencyValuesType<TDependencies>;
691
+ middleware: TMiddleware;
692
+ /** Normalized list of error ids declared via `throws`. */
693
+ throws?: readonly string[];
694
+ /** Return an optional dependency wrapper for this task. */
695
+ optional: () => IOptionalDependency<ITask<TInput, TOutput, TDependencies, TMeta, TTags, TMiddleware>>;
696
+ tags: TTags;
401
697
  }
698
+ /** Narrowed type for phantom tasks (no-op run by default). */
699
+ type IPhantomTask<TInput = any, TResolved = any, TDependencies extends DependencyMapType = {}, TMeta extends ITaskMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> = ITask<TInput, Promise<TResolved>, TDependencies, TMeta, TTags, TMiddleware> & {
700
+ [symbolPhantomTask]: true;
701
+ };
402
702
 
403
703
  type EventHandlerType<T = any> = (event: IEventEmission<T>) => any | Promise<any>;
404
704
  declare function onAnyOf<T extends readonly IEventDefinition<any>[]>(...defs: T): T;
@@ -476,41 +776,25 @@ interface IEventEmission<TPayload = any> {
476
776
  tags: TagType[];
477
777
  }
478
778
 
479
- declare const ERROR_TYPES_LOADED: true;
480
- interface IErrorDefinition<TData extends DefaultErrorType = DefaultErrorType> {
779
+ type OnType = "*" | IEventDefinition<any> | readonly IEventDefinition<any>[];
780
+ interface IHookDefinition<TDependencies extends DependencyMapType = {}, TOn extends OnType = any, TMeta extends ITaskMeta = any> {
481
781
  id: string;
482
- serialize?: (data: TData) => string;
483
- parse?: (data: string) => TData;
484
- format?: (data: TData) => string;
485
- /**
486
- * Validate error data on throw(). If provided, data is parsed first.
487
- */
488
- dataSchema?: IValidationSchema<TData>;
489
- meta?: IErrorMeta;
490
- }
491
- interface IErrorDefinitionFinal<TData extends DefaultErrorType> extends IErrorDefinition<TData> {
492
- format: (data: TData) => string;
782
+ dependencies?: TDependencies | (() => TDependencies);
783
+ on: TOn;
784
+ /** Listener execution order. Lower numbers run first. */
785
+ order?: number;
786
+ meta?: TMeta;
787
+ run: (event: IEventEmission<TOn extends "*" ? any : TOn extends readonly IEventDefinition<any>[] ? CommonPayload<TOn> : ExtractEventPayload<TOn>>, dependencies: DependencyValuesType<TDependencies>) => Promise<any>;
788
+ tags?: TagType[];
493
789
  }
494
- type DefaultErrorType = Record<string, unknown>;
495
- /**
496
- * Runtime helper returned by defineError()/r.error().
497
- * Contains helpers to throw typed errors and perform type-safe checks.
498
- */
499
- interface IErrorHelper<TData extends DefaultErrorType = DefaultErrorType> {
500
- /** Unique id for registration and DI */
790
+ interface IHook<TDependencies extends DependencyMapType = {}, TOn extends OnType = any, TMeta extends ITaskMeta = any> extends IHookDefinition<TDependencies, TOn, TMeta> {
501
791
  id: string;
502
- /** Throw a typed error with the given data */
503
- throw(data: TData): never;
504
- /** Type guard for checking if an unknown error is this error */
505
- is(error: unknown): boolean;
506
- /** Brand symbol for runtime detection */
507
- [symbolError]: true;
508
- /** Return an optional dependency wrapper for this error */
509
- optional(): IOptionalDependency<IErrorHelper<TData>>;
792
+ dependencies: TDependencies | (() => TDependencies);
793
+ [symbolFilePath]: string;
794
+ [symbolHook]: true;
795
+ tags: TagType[];
510
796
  }
511
797
 
512
- declare const ASYNC_CONTEXT_TYPES_LOADED: true;
513
-
514
798
  interface IAsyncContextDefinition<T> {
515
799
  id: string;
516
800
  serialize?(data: T): string;
@@ -598,20 +882,31 @@ interface IOptionalDependency<T> {
598
882
  /** Brand symbol for optional dependency */
599
883
  [symbolOptionalDependency]: true;
600
884
  }
601
- type ExtractTaskInput<T> = T extends ITask<infer I, any, infer D> ? I : never;
602
- type ExtractTaskOutput<T> = T extends ITask<any, infer O, infer D> ? O : never;
885
+ type ExtractTaskInput<T> = T extends ITask<infer I, any, infer _D> ? I : never;
886
+ type ExtractTaskOutput<T> = T extends ITask<any, infer O, infer _D> ? O : never;
603
887
  type ExtractResourceConfig<T> = T extends IResource<infer C, any, any> ? C : never;
604
- type ExtractResourceValue<T> = T extends IResource<any, infer V, infer D> ? V extends Promise<infer U> ? U : V : never;
888
+ type ExtractResourceValue<T> = T extends IResource<any, infer V, infer _D> ? V extends Promise<infer U> ? U : V : never;
605
889
  type ExtractEventPayload<T> = T extends IEventDefinition<infer P> ? P : T extends IEvent<infer P> ? P : never;
606
890
  type UnionToIntersection<U> = (U extends any ? (x: U) => any : never) extends (x: infer I) => any ? I : never;
607
891
  type CommonPayload<T extends readonly IEventDefinition<any>[] | IEventDefinition<any>> = T extends readonly IEventDefinition<any>[] ? {
608
892
  [K in keyof ExtractEventPayload<T[number]>]: UnionToIntersection<ExtractEventPayload<T[number]> extends any ? ExtractEventPayload<T[number]>[K] : never>;
609
893
  } : ExtractEventPayload<T>;
894
+ /**
895
+ * Options that can be passed when calling a task dependency.
896
+ * Allows forwarding the execution journal to nested task calls.
897
+ */
898
+ interface TaskCallOptions {
899
+ /** Optional journal to forward to the nested task */
900
+ journal?: ExecutionJournal;
901
+ }
610
902
  /**
611
903
  * Task dependencies transform into callable functions: call with the task input
612
- * and you receive the task output.
904
+ * and you receive the task output. Optionally accepts TaskCallOptions for journal forwarding.
613
905
  */
614
- type TaskDependency<I, O> = (...args: I extends null | void ? [] : [I]) => O;
906
+ type TaskDependency<I, O> = I extends null | void ? {
907
+ (options?: TaskCallOptions): O;
908
+ (input?: I, options?: TaskCallOptions): O;
909
+ } : (input: I, options?: TaskCallOptions) => O;
615
910
  /**
616
911
  * Resource dependencies resolve to the resource's value directly.
617
912
  */
@@ -668,7 +963,7 @@ interface TaskMiddlewareFluentBuilder<C = any, In = void, Out = void, D extends
668
963
  everywhere(flag: boolean | ((task: ITask<any, any, any, any>) => boolean)): TaskMiddlewareFluentBuilder<C, In, Out, D>;
669
964
  build(): ITaskMiddleware<C, In, Out, D>;
670
965
  }
671
- declare function taskMiddlewareBuilder<C = void, In = void, Out = void, D extends DependencyMapType = {}>(id: string): TaskMiddlewareFluentBuilder<C, In, Out, D>;
966
+
672
967
  interface ResourceMiddlewareFluentBuilder<C = any, In = void, Out = void, D extends DependencyMapType = {}> {
673
968
  id: string;
674
969
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | ((config: C) => TNewDeps), options?: {
@@ -686,35 +981,29 @@ interface ResourceMiddlewareFluentBuilder<C = any, In = void, Out = void, D exte
686
981
  everywhere(flag: boolean | ((resource: IResource<any, any, any, any, any>) => boolean)): ResourceMiddlewareFluentBuilder<C, In, Out, D>;
687
982
  build(): IResourceMiddleware<C, In, Out, D>;
688
983
  }
689
- declare function resourceMiddlewareBuilder<C = void, In = void, Out = void, D extends DependencyMapType = {}>(id: string): ResourceMiddlewareFluentBuilder<C, In, Out, D>;
690
984
 
691
- declare class RunnerError<TData extends DefaultErrorType = DefaultErrorType> extends Error {
692
- readonly id: string;
693
- readonly data: TData;
694
- constructor(id: string, message: string, data: TData);
695
- }
696
- declare class ErrorHelper<TData extends DefaultErrorType = DefaultErrorType> implements IErrorHelper<TData> {
697
- private readonly definition;
698
- [symbolError]: true;
699
- constructor(definition: IErrorDefinitionFinal<TData>);
700
- get id(): string;
701
- throw(data: TData): never;
702
- is(error: unknown): error is RunnerError<TData>;
703
- optional(): {
704
- readonly inner: IErrorHelper<TData>;
705
- readonly [symbolOptionalDependency]: true;
706
- };
707
- }
985
+ /**
986
+ * Entry point for creating a task middleware builder.
987
+ */
988
+ declare function taskMiddlewareBuilder<C = void, In = void, Out = void, D extends DependencyMapType = {}>(id: string): TaskMiddlewareFluentBuilder<C, In, Out, D>;
989
+ /**
990
+ * Entry point for creating a resource middleware builder.
991
+ */
992
+ declare function resourceMiddlewareBuilder<C = void, In = void, Out = void, D extends DependencyMapType = {}>(id: string): ResourceMiddlewareFluentBuilder<C, In, Out, D>;
708
993
 
709
994
  interface ErrorFluentBuilder<TData extends DefaultErrorType = DefaultErrorType> {
710
995
  id: string;
711
996
  serialize(fn: (data: TData) => string): ErrorFluentBuilder<TData>;
712
997
  parse(fn: (raw: string) => TData): ErrorFluentBuilder<TData>;
713
998
  dataSchema(schema: IValidationSchema<TData>): ErrorFluentBuilder<TData>;
714
- build(): ErrorHelper<TData>;
999
+ build(): IErrorHelper<TData>;
715
1000
  format(fn: (data: TData) => string): ErrorFluentBuilder<TData>;
716
1001
  meta<TNewMeta extends IErrorMeta>(m: TNewMeta): ErrorFluentBuilder<TData>;
717
1002
  }
1003
+
1004
+ /**
1005
+ * Entry point for creating an error builder.
1006
+ */
718
1007
  declare function errorBuilder<TData extends DefaultErrorType = DefaultErrorType>(id: string): ErrorFluentBuilder<TData>;
719
1008
 
720
1009
  interface AsyncContextFluentBuilder<T = unknown> {
@@ -725,6 +1014,10 @@ interface AsyncContextFluentBuilder<T = unknown> {
725
1014
  meta<TNewMeta extends IAsyncContextMeta>(m: TNewMeta): AsyncContextFluentBuilder<T>;
726
1015
  build(): IAsyncContext<T>;
727
1016
  }
1017
+
1018
+ /**
1019
+ * Entry point for creating an async context builder.
1020
+ */
728
1021
  declare function asyncContextBuilder<T = unknown>(id: string): AsyncContextFluentBuilder<T>;
729
1022
 
730
1023
  interface TagFluentBuilder<TConfig = void, TEnforceIn = void, TEnforceOut = void> {
@@ -734,11 +1027,19 @@ interface TagFluentBuilder<TConfig = void, TEnforceIn = void, TEnforceOut = void
734
1027
  config<TNewConfig>(config: TNewConfig): TagFluentBuilder<TNewConfig, TEnforceIn, TEnforceOut>;
735
1028
  build(): ITag<TConfig, TEnforceIn, TEnforceOut>;
736
1029
  }
1030
+
1031
+ /**
1032
+ * Entry point for creating a tag builder.
1033
+ */
737
1034
  declare function tagBuilder<TConfig = void, TEnforceIn = void, TEnforceOut = void>(id: string): TagFluentBuilder<TConfig, TEnforceIn, TEnforceOut>;
738
1035
 
739
- interface HookFluentBuilder<TDeps extends DependencyMapType = {}, TOn extends "*" | IEventDefinition<any> | readonly IEventDefinition<any>[] = any, TMeta extends ITaskMeta = ITaskMeta> {
1036
+ /** Valid event targets for hook's .on() method */
1037
+ type ValidOnTarget = "*" | IEventDefinition<any> | readonly IEventDefinition<any>[];
1038
+ /** Resolved TOn when valid, or `any` when undefined (build will throw at runtime) */
1039
+ type ResolvedOn<TOn> = TOn extends ValidOnTarget ? TOn : any;
1040
+ interface HookFluentBuilder<TDeps extends DependencyMapType = {}, TOn extends ValidOnTarget | undefined = undefined, TMeta extends ITaskMeta = ITaskMeta> {
740
1041
  id: string;
741
- on<TNewOn extends "*" | IEventDefinition<any> | readonly IEventDefinition<any>[]>(on: TNewOn): HookFluentBuilder<TDeps, TNewOn, TMeta>;
1042
+ on<TNewOn extends ValidOnTarget>(on: TNewOn): HookFluentBuilder<TDeps, TNewOn, TMeta>;
742
1043
  order(order: number): HookFluentBuilder<TDeps, TOn, TMeta>;
743
1044
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | (() => TNewDeps), options?: {
744
1045
  override?: false;
@@ -750,10 +1051,20 @@ interface HookFluentBuilder<TDeps extends DependencyMapType = {}, TOn extends "*
750
1051
  override?: boolean;
751
1052
  }): HookFluentBuilder<TDeps, TOn, TMeta>;
752
1053
  meta<TNewMeta extends ITaskMeta>(m: TNewMeta): HookFluentBuilder<TDeps, TOn, TNewMeta>;
753
- run(fn: IHookDefinition<TDeps, TOn, TMeta>["run"]): HookFluentBuilder<TDeps, TOn, TMeta>;
754
- build(): IHook<TDeps, TOn, TMeta>;
1054
+ /** Set the hook's run handler. Required before build(). */
1055
+ run(fn: IHookDefinition<TDeps, ResolvedOn<TOn>, TMeta>["run"]): HookFluentBuilder<TDeps, TOn, TMeta>;
1056
+ /**
1057
+ * Build the hook definition. Requires .on() and .run() to be called first.
1058
+ * @throws {Error} if on or run are not set
1059
+ */
1060
+ build(): IHook<TDeps, ResolvedOn<TOn>, TMeta>;
755
1061
  }
756
- declare function hookBuilder(id: string): HookFluentBuilder<{}, any, ITaskMeta>;
1062
+
1063
+ /**
1064
+ * Entry point for creating a hook builder.
1065
+ * Requires calling .on() and .run() before .build().
1066
+ */
1067
+ declare function hookBuilder(id: string): HookFluentBuilder<{}, undefined, ITaskMeta>;
757
1068
 
758
1069
  interface EventFluentBuilder<TPayload = void> {
759
1070
  id: string;
@@ -772,69 +1083,98 @@ interface EventFluentBuilder<TPayload = void> {
772
1083
  parallel(enabled?: boolean): EventFluentBuilder<TPayload>;
773
1084
  build(): IEvent<TPayload>;
774
1085
  }
775
- declare function eventBuilder(id: string): EventFluentBuilder<void>;
776
1086
 
777
- interface PhantomTaskFluentBuilder<TInput = undefined, TResolved = any, TDeps extends DependencyMapType = {}, TMeta extends ITaskMeta = ITaskMeta, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> {
1087
+ /**
1088
+ * Entry point for creating an event builder.
1089
+ */
1090
+ declare function eventBuilder<TPayload = void>(id: string): EventFluentBuilder<TPayload>;
1091
+
1092
+ type ShouldReplaceInput<T> = [T] extends [undefined] ? true : [T] extends [void] ? true : 0 extends 1 & T ? true : false;
1093
+ type ResolveInput<TExisting, TProposed> = ShouldReplaceInput<TExisting> extends true ? TProposed : TExisting;
1094
+
1095
+ /**
1096
+ * Fluent builder interface for constructing tasks.
1097
+ */
1098
+ interface TaskFluentBuilder<TInput = undefined, TOutput extends Promise<any> = Promise<any>, TDeps extends DependencyMapType = {}, TMeta extends ITaskMeta = ITaskMeta, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> {
778
1099
  id: string;
779
1100
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | (() => TNewDeps), options?: {
780
1101
  override?: false;
781
- }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps & TNewDeps, TMeta, TTags, TMiddleware>;
1102
+ }): TaskFluentBuilder<TInput, TOutput, TDeps & TNewDeps, TMeta, TTags, TMiddleware>;
782
1103
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | (() => TNewDeps), options: {
783
1104
  override: true;
784
- }): PhantomTaskFluentBuilder<TInput, TResolved, TNewDeps, TMeta, TTags, TMiddleware>;
1105
+ }): TaskFluentBuilder<TInput, TOutput, TNewDeps, TMeta, TTags, TMiddleware>;
785
1106
  middleware<TNewMw extends TaskMiddlewareAttachmentType[]>(mw: TNewMw, options?: {
786
1107
  override?: boolean;
787
- }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, TTags, TNewMw>;
1108
+ }): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, TTags, TNewMw>;
788
1109
  tags<TNewTags extends TagType[]>(t: TNewTags, options?: {
789
1110
  override?: false;
790
- }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, [
1111
+ }): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, [
791
1112
  ...TTags,
792
1113
  ...TNewTags
793
1114
  ], TMiddleware>;
794
1115
  tags<TNewTags extends TagType[]>(t: TNewTags, options: {
795
1116
  override: true;
796
- }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, TNewTags, TMiddleware>;
797
- inputSchema<TNewInput>(schema: IValidationSchema<TNewInput>): PhantomTaskFluentBuilder<TNewInput, TResolved, TDeps, TMeta, TTags, TMiddleware>;
798
- resultSchema<TNewResolved>(schema: IValidationSchema<TNewResolved>): PhantomTaskFluentBuilder<TInput, TNewResolved, TDeps, TMeta, TTags, TMiddleware>;
799
- meta<TNewMeta extends ITaskMeta>(m: TNewMeta): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TNewMeta, TTags, TMiddleware>;
800
- build(): IPhantomTask<TInput, TResolved, TDeps, TMeta, TTags, TMiddleware>;
1117
+ }): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, TNewTags, TMiddleware>;
1118
+ inputSchema<TNewInput>(schema: IValidationSchema<TNewInput>): TaskFluentBuilder<TNewInput, TOutput, TDeps, TMeta, TTags, TMiddleware>;
1119
+ resultSchema<TResolved>(schema: IValidationSchema<TResolved>): TaskFluentBuilder<TInput, Promise<TResolved>, TDeps, TMeta, TTags, TMiddleware>;
1120
+ run<TNewInput = TInput, TNewOutput extends Promise<any> = TOutput>(fn: NonNullable<ITaskDefinition<ResolveInput<TInput, TNewInput>, TNewOutput, TDeps, TMeta, TTags, TMiddleware>["run"]>): TaskFluentBuilder<ResolveInput<TInput, TNewInput>, TNewOutput, TDeps, TMeta, TTags, TMiddleware>;
1121
+ throws(list: ThrowsList): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, TTags, TMiddleware>;
1122
+ meta<TNewMeta extends ITaskMeta>(m: TNewMeta): TaskFluentBuilder<TInput, TOutput, TDeps, TNewMeta, TTags, TMiddleware>;
1123
+ build(): ITask<TInput, TOutput, TDeps, TMeta, TTags, TMiddleware>;
801
1124
  }
802
1125
 
803
- type ShouldReplaceInput<T> = [T] extends [undefined] ? true : [T] extends [void] ? true : (0 extends 1 & T ? true : false);
804
- type ResolveInput<TExisting, TProposed> = ShouldReplaceInput<TExisting> extends true ? TProposed : TExisting;
805
- interface TaskFluentBuilder<TInput = undefined, TOutput extends Promise<any> = Promise<any>, TDeps extends DependencyMapType = {}, TMeta extends ITaskMeta = ITaskMeta, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> {
1126
+ /**
1127
+ * Fluent builder interface for constructing phantom tasks.
1128
+ */
1129
+ interface PhantomTaskFluentBuilder<TInput = undefined, TResolved = any, TDeps extends DependencyMapType = {}, TMeta extends ITaskMeta = ITaskMeta, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> {
806
1130
  id: string;
807
1131
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | (() => TNewDeps), options?: {
808
1132
  override?: false;
809
- }): TaskFluentBuilder<TInput, TOutput, TDeps & TNewDeps, TMeta, TTags, TMiddleware>;
1133
+ }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps & TNewDeps, TMeta, TTags, TMiddleware>;
810
1134
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | (() => TNewDeps), options: {
811
1135
  override: true;
812
- }): TaskFluentBuilder<TInput, TOutput, TNewDeps, TMeta, TTags, TMiddleware>;
1136
+ }): PhantomTaskFluentBuilder<TInput, TResolved, TNewDeps, TMeta, TTags, TMiddleware>;
813
1137
  middleware<TNewMw extends TaskMiddlewareAttachmentType[]>(mw: TNewMw, options?: {
814
1138
  override?: boolean;
815
- }): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, TTags, TNewMw>;
1139
+ }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, TTags, TNewMw>;
816
1140
  tags<TNewTags extends TagType[]>(t: TNewTags, options?: {
817
1141
  override?: false;
818
- }): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, [
1142
+ }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, [
819
1143
  ...TTags,
820
1144
  ...TNewTags
821
1145
  ], TMiddleware>;
822
1146
  tags<TNewTags extends TagType[]>(t: TNewTags, options: {
823
1147
  override: true;
824
- }): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, TNewTags, TMiddleware>;
825
- inputSchema<TNewInput>(schema: IValidationSchema<TNewInput>): TaskFluentBuilder<TNewInput, TOutput, TDeps, TMeta, TTags, TMiddleware>;
826
- resultSchema<TResolved>(schema: IValidationSchema<TResolved>): TaskFluentBuilder<TInput, Promise<TResolved>, TDeps, TMeta, TTags, TMiddleware>;
827
- run<TNewInput = TInput, TNewOutput extends Promise<any> = TOutput>(fn: NonNullable<ITaskDefinition<ResolveInput<TInput, TNewInput>, TNewOutput, TDeps, TMeta, TTags, TMiddleware>["run"]>): TaskFluentBuilder<ResolveInput<TInput, TNewInput>, TNewOutput, TDeps, TMeta, TTags, TMiddleware>;
828
- meta<TNewMeta extends ITaskMeta>(m: TNewMeta): TaskFluentBuilder<TInput, TOutput, TDeps, TNewMeta, TTags, TMiddleware>;
829
- build(): ITask<TInput, TOutput, TDeps, TMeta, TTags, TMiddleware>;
1148
+ }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, TNewTags, TMiddleware>;
1149
+ inputSchema<TNewInput>(schema: IValidationSchema<TNewInput>): PhantomTaskFluentBuilder<TNewInput, TResolved, TDeps, TMeta, TTags, TMiddleware>;
1150
+ resultSchema<TNewResolved>(schema: IValidationSchema<TNewResolved>): PhantomTaskFluentBuilder<TInput, TNewResolved, TDeps, TMeta, TTags, TMiddleware>;
1151
+ meta<TNewMeta extends ITaskMeta>(m: TNewMeta): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TNewMeta, TTags, TMiddleware>;
1152
+ throws(list: ThrowsList): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, TTags, TMiddleware>;
1153
+ build(): IPhantomTask<TInput, TResolved, TDeps, TMeta, TTags, TMiddleware>;
830
1154
  }
1155
+
1156
+ /**
1157
+ * Entry point for creating a phantom task builder.
1158
+ */
1159
+ declare function phantomTaskBuilder<TInput = undefined, TResolved = any>(id: string): PhantomTaskFluentBuilder<TInput, TResolved, {}, ITaskMeta, TagType[], TaskMiddlewareAttachmentType[]>;
831
1160
  interface TaskBuilderWithPhantom {
832
1161
  (id: string): TaskFluentBuilder<undefined, Promise<any>, {}, ITaskMeta, TagType[], TaskMiddlewareAttachmentType[]>;
833
- phantom: <TInput = undefined, TResolved = any>(id: string) => PhantomTaskFluentBuilder<TInput, TResolved, {}, ITaskMeta, TagType[], TaskMiddlewareAttachmentType[]>;
1162
+ phantom: typeof phantomTaskBuilder;
834
1163
  }
835
1164
 
1165
+ /**
1166
+ * Helper type to determine if config should be replaced.
1167
+ */
836
1168
  type ShouldReplaceConfig<T> = [T] extends [void] ? true : [T] extends [undefined] ? true : false;
1169
+ /**
1170
+ * Resolves the config type - uses proposed if existing is void/undefined.
1171
+ */
837
1172
  type ResolveConfig<TExisting, TProposed> = ShouldReplaceConfig<TExisting> extends true ? TProposed : TExisting;
1173
+
1174
+ /**
1175
+ * Fluent builder interface for constructing resources.
1176
+ * Each method returns a new builder with updated type parameters.
1177
+ */
838
1178
  interface ResourceFluentBuilder<TConfig = void, TValue extends Promise<any> = Promise<any>, TDeps extends DependencyMapType = {}, TContext = any, TMeta extends IResourceMeta = IResourceMeta, TTags extends TagType[] = TagType[], TMiddleware extends ResourceMiddlewareAttachmentType[] = ResourceMiddlewareAttachmentType[]> {
839
1179
  id: string;
840
1180
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | ((config: TConfig) => TNewDeps), options?: {
@@ -864,27 +1204,41 @@ interface ResourceFluentBuilder<TConfig = void, TValue extends Promise<any> = Pr
864
1204
  init<TNewConfig = TConfig, TNewValue extends Promise<any> = TValue>(fn: ResourceInitFn<ResolveConfig<TConfig, TNewConfig>, TNewValue, TDeps, TContext, TMeta, TTags, TMiddleware>): ResourceFluentBuilder<ResolveConfig<TConfig, TNewConfig>, TNewValue, TDeps, TContext, TMeta, TTags, TMiddleware>;
865
1205
  dispose(fn: NonNullable<IResourceDefinition<TConfig, TValue, TDeps, TContext, any, any, TMeta, TTags, TMiddleware>["dispose"]>): ResourceFluentBuilder<TConfig, TValue, TDeps, TContext, TMeta, TTags, TMiddleware>;
866
1206
  meta<TNewMeta extends IResourceMeta>(m: TNewMeta): ResourceFluentBuilder<TConfig, TValue, TDeps, TContext, TNewMeta, TTags, TMiddleware>;
1207
+ throws(list: ThrowsList): ResourceFluentBuilder<TConfig, TValue, TDeps, TContext, TMeta, TTags, TMiddleware>;
867
1208
  overrides(o: Array<OverridableElements>, options?: {
868
1209
  override?: boolean;
869
1210
  }): ResourceFluentBuilder<TConfig, TValue, TDeps, TContext, TMeta, TTags, TMiddleware>;
870
1211
  build(): IResource<TConfig, TValue, TDeps, TContext, TMeta, TTags, TMiddleware>;
871
1212
  }
1213
+
1214
+ /**
1215
+ * Creates a new resource builder with the given id.
1216
+ * Overload allows callers to seed the config type at the entry point for convenience.
1217
+ */
872
1218
  declare function resourceBuilder<TConfig = void>(id: string): ResourceFluentBuilder<TConfig, Promise<any>, {}, any, IResourceMeta, TagType[], ResourceMiddlewareAttachmentType[]>;
873
1219
 
874
1220
  type TunnelMiddlewareId = string | ITaskMiddleware<any, any, any, any>;
1221
+ interface TunnelTaskMiddlewareSidePolicy {
1222
+ /**
1223
+ * Middleware ids/definitions allowed to run on this side when the task is tunneled.
1224
+ * If omitted, defaults to allowing none (caller-side middleware is skipped by default).
1225
+ */
1226
+ middlewareAllowList?: TunnelMiddlewareId[];
1227
+ }
1228
+ type TunnelTaskMiddlewarePolicySideConfig = TunnelTaskMiddlewareSidePolicy | TunnelMiddlewareId[];
875
1229
  interface TunnelTaskMiddlewarePolicyConfig {
876
1230
  /**
877
- * Whitelist of middleware ids/definitions allowed to run on the caller side
878
- * when the task is tunneled (mode: "client"). If omitted, defaults to
879
- * allowing all (the framework default remains "both").
1231
+ * Preferred configuration shape: explicit per-side allowlist.
880
1232
  */
881
- client?: TunnelMiddlewareId[];
1233
+ client?: TunnelTaskMiddlewarePolicySideConfig;
1234
+ server?: TunnelTaskMiddlewarePolicySideConfig;
882
1235
  /**
883
- * Whitelist of middleware ids/definitions intended to run on the executor side.
884
- * Note: The local runner cannot enforce server-side policy; this is a declarative
885
- * contract that a Runner-based executor can consume to apply a symmetric filter.
1236
+ * Backwards-compatible configuration shape (previous): grouped allowlists.
886
1237
  */
887
- server?: TunnelMiddlewareId[];
1238
+ middlewareAllowList?: {
1239
+ client?: TunnelMiddlewareId[];
1240
+ server?: TunnelMiddlewareId[];
1241
+ };
888
1242
  }
889
1243
 
890
1244
  interface TimeoutMiddlewareConfig {
@@ -915,63 +1269,249 @@ interface RetryMiddlewareConfig {
915
1269
  delayStrategy?: (attempt: number, error: Error) => number;
916
1270
  }
917
1271
 
918
- /**
919
- * Options for configuring event listeners.
920
- */
921
- interface IEventHandlerOptions<T = any> {
922
- order?: number;
923
- filter?: (event: IEventEmission<T>) => boolean;
1272
+ interface FallbackMiddlewareConfig {
924
1273
  /**
925
- * Represents the listener ID. Use this to avoid a listener calling itself.
1274
+ * The fallback to use if the task fails.
1275
+ * Can be a value, a function that returns a value (or promise), or another task.
926
1276
  */
927
- id?: string;
1277
+ fallback: any;
928
1278
  }
929
- /**
930
- * Interceptor for event emissions.
931
- */
932
- type EventEmissionInterceptor = (next: (event: IEventEmission<any>) => Promise<void>, event: IEventEmission<any>) => Promise<void>;
933
- /**
934
- * Interceptor for hook execution.
935
- */
936
- type HookExecutionInterceptor = (next: (hook: IHook<any, any>, event: IEventEmission<any>) => Promise<any>, hook: IHook<any, any>, event: IEventEmission<any>) => Promise<any>;
937
1279
 
1280
+ declare const SemaphoreEvents: {
1281
+ readonly queued: IEvent<SemaphoreEvent>;
1282
+ readonly acquired: IEvent<SemaphoreEvent>;
1283
+ readonly released: IEvent<SemaphoreEvent>;
1284
+ readonly timeout: IEvent<SemaphoreEvent>;
1285
+ readonly aborted: IEvent<SemaphoreEvent>;
1286
+ readonly disposed: IEvent<SemaphoreEvent>;
1287
+ };
1288
+ type SemaphoreEventType = keyof typeof SemaphoreEvents;
1289
+ type SemaphoreEvent = {
1290
+ type: SemaphoreEventType;
1291
+ permits: number;
1292
+ waiting: number;
1293
+ maxPermits: number;
1294
+ disposed: boolean;
1295
+ };
938
1296
  /**
939
- * EventManager handles event emission, listener registration, and event processing.
940
- * It supports both specific event listeners and global listeners that handle all events.
941
- * Listeners are processed in order based on their priority.
1297
+ * A semaphore that limits the number of concurrent operations.
1298
+ * Used to prevent connection pool exhaustion by limiting concurrent
1299
+ * database operations to the pool size.
942
1300
  */
943
- declare class EventManager {
944
- #private;
945
- private listeners;
946
- private globalListeners;
947
- private cachedMergedListeners;
948
- private emissionInterceptors;
949
- private hookInterceptors;
950
- private readonly registry;
951
- private readonly cycleContext;
952
- private readonly runtimeCycleDetection;
953
- constructor(options?: {
954
- runtimeCycleDetection?: boolean;
955
- });
1301
+ declare class Semaphore {
1302
+ private permits;
1303
+ private waitingHead;
1304
+ private waitingTail;
1305
+ private waitingCount;
1306
+ private disposed;
1307
+ private readonly maxPermits;
1308
+ private readonly eventManager;
1309
+ private listenerId;
1310
+ private activeListeners;
1311
+ constructor(maxPermits: number);
956
1312
  /**
957
- * Gets the current lock status of the EventManager
1313
+ * Acquire a permit. If no permits are available, waits until one becomes available.
958
1314
  */
959
- get isLocked(): boolean;
1315
+ acquire(options?: {
1316
+ timeout?: number;
1317
+ signal?: AbortSignal;
1318
+ }): Promise<void>;
960
1319
  /**
961
- * Locks the EventManager, preventing any further modifications to listeners
1320
+ * Release a permit, allowing waiting operations to proceed.
962
1321
  */
963
- lock(): void;
1322
+ release(): void;
1323
+ private removeFromQueue;
964
1324
  /**
965
- * Emits an event to all registered listeners for that event type.
966
- * Listeners are processed in order of priority and can stop event propagation.
967
- *
968
- * @param eventDefinition - The event definition to emit
969
- * @param data - The event payload data
970
- * @param source - The source identifier of the event emitter
1325
+ * Execute a function with a permit, automatically releasing it afterwards.
971
1326
  */
972
- emit<TInput>(eventDefinition: IEvent<TInput>, data: TInput, source: string): Promise<void>;
1327
+ withPermit<T>(fn: () => Promise<T>, options?: {
1328
+ timeout?: number;
1329
+ signal?: AbortSignal;
1330
+ }): Promise<T>;
973
1331
  /**
974
- * Registers an event listener for specific event(s).
1332
+ * Dispose the semaphore, rejecting all waiting operations and preventing new ones.
1333
+ */
1334
+ dispose(): void;
1335
+ /**
1336
+ * Get current number of available permits (for debugging)
1337
+ */
1338
+ getAvailablePermits(): number;
1339
+ /**
1340
+ * Get current number of waiting operations (for debugging)
1341
+ */
1342
+ getWaitingCount(): number;
1343
+ /**
1344
+ * Get maximum number of permits
1345
+ */
1346
+ getMaxPermits(): number;
1347
+ /**
1348
+ * Check if the semaphore has been disposed
1349
+ */
1350
+ isDisposed(): boolean;
1351
+ /**
1352
+ * Get metrics about the current state of the semaphore
1353
+ */
1354
+ getMetrics(): {
1355
+ availablePermits: number;
1356
+ waitingCount: number;
1357
+ maxPermits: number;
1358
+ utilization: number;
1359
+ disposed: boolean;
1360
+ };
1361
+ on(type: SemaphoreEventType, handler: (event: SemaphoreEvent) => any): () => void;
1362
+ once(type: SemaphoreEventType, handler: (event: SemaphoreEvent) => any): () => void;
1363
+ private enqueue;
1364
+ private dequeue;
1365
+ private emit;
1366
+ private buildEvent;
1367
+ }
1368
+
1369
+ interface ConcurrencyMiddlewareConfig {
1370
+ /**
1371
+ * Maximum number of concurrent executions.
1372
+ * If provided, a Semaphore will be created and shared for this config object.
1373
+ */
1374
+ limit?: number;
1375
+ /**
1376
+ * Optional key to identify a shared semaphore.
1377
+ * If provided, the semaphore will be shared across all tasks using the same key.
1378
+ */
1379
+ key?: string;
1380
+ /**
1381
+ * An existing Semaphore instance to use.
1382
+ */
1383
+ semaphore?: Semaphore;
1384
+ }
1385
+
1386
+ interface TemporalMiddlewareConfig {
1387
+ ms: number;
1388
+ }
1389
+ interface DebounceState {
1390
+ timeoutId?: NodeJS.Timeout;
1391
+ latestInput?: any;
1392
+ resolveList: ((value: any) => void)[];
1393
+ rejectList: ((error: any) => void)[];
1394
+ }
1395
+ interface ThrottleState {
1396
+ lastExecution: number;
1397
+ timeoutId?: NodeJS.Timeout;
1398
+ latestInput?: any;
1399
+ resolveList: ((value: any) => void)[];
1400
+ rejectList: ((error: any) => void)[];
1401
+ currentPromise?: Promise<any>;
1402
+ }
1403
+
1404
+ /**
1405
+ * States of the Circuit Breaker
1406
+ */
1407
+ declare enum CircuitBreakerState {
1408
+ CLOSED = "CLOSED",
1409
+ OPEN = "OPEN",
1410
+ HALF_OPEN = "HALF_OPEN"
1411
+ }
1412
+ /**
1413
+ * Configuration for the Circuit Breaker middleware
1414
+ */
1415
+ interface CircuitBreakerMiddlewareConfig {
1416
+ /**
1417
+ * Number of failures before tripping the circuit
1418
+ * @default 5
1419
+ */
1420
+ failureThreshold?: number;
1421
+ /**
1422
+ * Time in milliseconds before transitioning from OPEN to HALF_OPEN
1423
+ * @default 30000 (30 seconds)
1424
+ */
1425
+ resetTimeout?: number;
1426
+ }
1427
+ interface CircuitBreakerStatus {
1428
+ state: CircuitBreakerState;
1429
+ failures: number;
1430
+ lastFailureTime: number;
1431
+ }
1432
+
1433
+ interface RateLimitMiddlewareConfig {
1434
+ /**
1435
+ * Time window in milliseconds
1436
+ */
1437
+ windowMs: number;
1438
+ /**
1439
+ * Maximum number of requests within the window
1440
+ */
1441
+ max: number;
1442
+ }
1443
+ interface RateLimitState {
1444
+ count: number;
1445
+ resetTime: number;
1446
+ }
1447
+
1448
+ /**
1449
+ * Options for configuring event listeners.
1450
+ */
1451
+ interface IEventHandlerOptions<T = any> {
1452
+ order?: number;
1453
+ filter?: (event: IEventEmission<T>) => boolean;
1454
+ /**
1455
+ * Represents the listener ID. Use this to avoid a listener calling itself.
1456
+ */
1457
+ id?: string;
1458
+ }
1459
+ /**
1460
+ * Interceptor for event emissions.
1461
+ */
1462
+ type EventEmissionInterceptor = (next: (event: IEventEmission<any>) => Promise<void>, event: IEventEmission<any>) => Promise<void>;
1463
+ /**
1464
+ * Interceptor for hook execution.
1465
+ */
1466
+ type HookExecutionInterceptor = (next: (hook: IHook<any, any>, event: IEventEmission<any>) => Promise<any>, hook: IHook<any, any>, event: IEventEmission<any>) => Promise<any>;
1467
+
1468
+ /**
1469
+ * EventManager handles event emission, listener registration, and event processing.
1470
+ * It supports both specific event listeners and global listeners that handle all events.
1471
+ * Listeners are processed in order based on their priority.
1472
+ */
1473
+ declare class EventManager {
1474
+ #private;
1475
+ private listeners;
1476
+ private globalListeners;
1477
+ private cachedMergedListeners;
1478
+ private emissionInterceptors;
1479
+ private hookInterceptors;
1480
+ private readonly registry;
1481
+ private readonly cycleContext;
1482
+ private readonly runtimeEventCycleDetection;
1483
+ constructor(options?: {
1484
+ runtimeEventCycleDetection?: boolean;
1485
+ });
1486
+ /**
1487
+ * Gets the current lock status of the EventManager
1488
+ */
1489
+ get isLocked(): boolean;
1490
+ /**
1491
+ * Locks the EventManager, preventing any further modifications to listeners
1492
+ */
1493
+ lock(): void;
1494
+ /**
1495
+ * Emits an event to all registered listeners for that event type.
1496
+ * Listeners are processed in order of priority and can stop event propagation.
1497
+ *
1498
+ * @param eventDefinition - The event definition to emit
1499
+ * @param data - The event payload data
1500
+ * @param source - The source identifier of the event emitter
1501
+ */
1502
+ emit<TInput>(eventDefinition: IEvent<TInput>, data: TInput, source: string): Promise<void>;
1503
+ /**
1504
+ * Emits an event and returns the final payload.
1505
+ * The payload is taken from the deepest emission object that reached either:
1506
+ * - the base listener executor, or
1507
+ * - an interceptor that short-circuited the emission.
1508
+ *
1509
+ * This enables tunnel transports to return the final payload after local and/or remote delivery.
1510
+ */
1511
+ emitWithResult<TInput>(eventDefinition: IEvent<TInput>, data: TInput, source: string): Promise<TInput>;
1512
+ private emitAndReturnEmission;
1513
+ /**
1514
+ * Registers an event listener for specific event(s).
975
1515
  * Listeners are ordered by priority and executed in ascending order.
976
1516
  *
977
1517
  * @param event - The event definition(s) to listen for
@@ -1024,6 +1564,16 @@ declare class EventManager {
1024
1564
  * Throws an error if the EventManager is locked
1025
1565
  */
1026
1566
  private checkLock;
1567
+ /**
1568
+ * Clears all listeners and interceptors.
1569
+ * Call this to release references and free memory.
1570
+ */
1571
+ clear(): void;
1572
+ /**
1573
+ * Disposes the EventManager, releasing all listeners and interceptors.
1574
+ * Alias for clear() following the IResource disposal pattern.
1575
+ */
1576
+ dispose(): void;
1027
1577
  /**
1028
1578
  * Retrieves cached merged listeners for an event, or creates them if not cached.
1029
1579
  * Kept for backward compatibility (tests spy on this).
@@ -1079,6 +1629,7 @@ declare class LogPrinter {
1079
1629
  private formatContext;
1080
1630
  private normalizeForJson;
1081
1631
  private static NO_COLORS;
1632
+ private static readonly DEFAULT_WRITERS;
1082
1633
  private static writers;
1083
1634
  static setWriters(writers: Partial<{
1084
1635
  log: (msg: any) => void;
@@ -1208,7 +1759,7 @@ declare class TaskRunner {
1208
1759
  protected readonly store: Store;
1209
1760
  protected readonly eventManager: EventManager;
1210
1761
  protected readonly logger: Logger;
1211
- protected readonly runnerStore: Map<string | symbol, (input: any) => Promise<any>>;
1762
+ protected readonly runnerStore: Map<string | symbol, (input: any, journal?: ExecutionJournal) => Promise<any>>;
1212
1763
  constructor(store: Store, eventManager: EventManager, logger: Logger);
1213
1764
  private readonly middlewareManager;
1214
1765
  /**
@@ -1216,8 +1767,9 @@ declare class TaskRunner {
1216
1767
  * This function can throw only if any of the event listeners or run function throws
1217
1768
  * @param task the task to be run
1218
1769
  * @param input the input to be passed to the task
1770
+ * @param options optional call options including journal for forwarding
1219
1771
  */
1220
- run<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>, input?: TInput): Promise<TOutput | undefined>;
1772
+ run<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>, input?: TInput, options?: TaskCallOptions): Promise<TOutput | undefined>;
1221
1773
  /**
1222
1774
  * Creates the function with the chain of middleware.
1223
1775
  * @param task
@@ -1225,7 +1777,7 @@ declare class TaskRunner {
1225
1777
  * @param taskDependencies
1226
1778
  * @returns
1227
1779
  */
1228
- protected createRunnerWithMiddleware<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>): (input: TInput) => Promise<Awaited<TOutput>>;
1780
+ protected createRunnerWithMiddleware<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>): (input: TInput, parentJournal?: ExecutionJournal) => Promise<Awaited<TOutput>>;
1229
1781
  }
1230
1782
 
1231
1783
  type UnhandledErrorKind = "process" | "task" | "middleware" | "resourceInit" | "hook" | "run";
@@ -1300,7 +1852,7 @@ declare class MiddlewareManager {
1300
1852
  * Compose a runner for a task with its local interceptors and applicable middlewares.
1301
1853
  * Returns a function that accepts the task input and resolves to the task output.
1302
1854
  */
1303
- composeTaskRunner<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>): (input: TInput) => Promise<Awaited<TOutput>>;
1855
+ composeTaskRunner<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>): (input: TInput, parentJournal?: ExecutionJournal) => Promise<Awaited<TOutput>>;
1304
1856
  /**
1305
1857
  * Run a resource init wrapped with its applicable middlewares.
1306
1858
  */
@@ -1331,6 +1883,7 @@ declare class Store {
1331
1883
  private validator;
1332
1884
  private taskRunner?;
1333
1885
  private middlewareManager;
1886
+ private readonly initializedResourceIds;
1334
1887
  mode: RunnerMode;
1335
1888
  constructor(eventManager: EventManager, logger: Logger, onUnhandledError: OnUnhandledError, mode?: RunnerMode);
1336
1889
  get tasks(): Map<string, TaskStoreElementType>;
@@ -1358,6 +1911,8 @@ declare class Store {
1358
1911
  validateEventEmissionGraph(): void;
1359
1912
  initializeStore(root: IResource<any, any, any, any, any>, config: any): void;
1360
1913
  dispose(): Promise<void>;
1914
+ recordResourceInitialized(resourceId: string): void;
1915
+ private getResourcesInDisposeOrder;
1361
1916
  /**
1362
1917
  * Internal, avoid using this method directly.
1363
1918
  */
@@ -1393,16 +1948,14 @@ declare class ResourceInitializer {
1393
1948
  * This function can throw only if any of the event listeners or run function throws
1394
1949
  */
1395
1950
  initializeResource<TConfig = null, TValue extends Promise<any> = Promise<any>, TDeps extends DependencyMapType = {}, TContext = any>(resource: IResource<TConfig, TValue, TDeps>, config: TConfig, dependencies: ResourceDependencyValuesType<TDeps>): Promise<{
1396
- value: TValue;
1951
+ value: TValue | undefined;
1397
1952
  context: TContext;
1398
1953
  }>;
1399
1954
  initWithMiddleware<C, V extends Promise<any>, D extends DependencyMapType, TContext>(resource: IResource<C, V, D, TContext>, config: C, dependencies: ResourceDependencyValuesType<D>, context: TContext): Promise<V | undefined>;
1400
1955
  }
1401
1956
 
1402
1957
  /**
1403
- * This class is responsible of setting up dependencies with their respective computedValues.
1404
- * Note that all elements must have been previously registered otherwise errors will be thrown
1405
- * when trying to depend on something not in the store.
1958
+ * Resolves and caches computed dependencies for store items (resources, tasks, middleware, hooks).
1406
1959
  */
1407
1960
  declare class DependencyProcessor {
1408
1961
  protected readonly store: Store;
@@ -1412,21 +1965,21 @@ declare class DependencyProcessor {
1412
1965
  protected readonly logger: Logger;
1413
1966
  constructor(store: Store, eventManager: EventManager, taskRunner: TaskRunner, logger: Logger);
1414
1967
  /**
1415
- * This function is going to go through all the resources, tasks and middleware to compute their required dependencies.
1968
+ * Computes and caches dependencies for all registered store items.
1416
1969
  */
1417
1970
  computeAllDependencies(): Promise<void>;
1418
1971
  private computeTaskDependencies;
1419
1972
  initializeUninitializedResources(): Promise<void>;
1973
+ private rethrowResourceInitError;
1420
1974
  /**
1421
- * Processes dependencies and hooks
1422
- * @param resource
1975
+ * Computes and caches dependencies for a resource (if not already computed).
1423
1976
  */
1424
1977
  protected processResourceDependencies<TD extends DependencyMapType>(resource: ResourceStoreElementType<any, any, TD>): Promise<void>;
1425
1978
  private wrapResourceDependencies;
1426
1979
  private makeTaskWithIntercept;
1427
1980
  initializeRoot(): Promise<void>;
1428
1981
  /**
1429
- * Processes all hooks, should run before emission of any event.
1982
+ * Attaches listeners for all hooks. Must run before emitting events.
1430
1983
  */
1431
1984
  attachListeners(): void;
1432
1985
  extractDependencies<T extends DependencyMapType>(map: T, source: string): Promise<DependencyValuesType<T>>;
@@ -1437,72 +1990,25 @@ declare class DependencyProcessor {
1437
1990
  * @returns
1438
1991
  */
1439
1992
  extractEventDependency(object: IEvent<any>, source: string): (input: any) => Promise<void>;
1440
- extractTaskDependency(object: ITask<any, any, {}>): Promise<(input: unknown) => Promise<any>>;
1993
+ extractTaskDependency(object: ITask<any, any, {}>): Promise<(input: unknown, options?: TaskCallOptions) => Promise<any>>;
1441
1994
  extractResourceDependency(object: IResource<any, any, any>): Promise<any>;
1442
1995
  }
1443
1996
 
1444
- /**
1445
- * A semaphore that limits the number of concurrent operations.
1446
- * Used to prevent connection pool exhaustion by limiting concurrent
1447
- * database operations to the pool size.
1448
- */
1449
- declare class Semaphore {
1450
- private permits;
1451
- private readonly waitingQueue;
1452
- private disposed;
1453
- private readonly maxPermits;
1454
- constructor(maxPermits: number);
1455
- /**
1456
- * Acquire a permit. If no permits are available, waits until one becomes available.
1457
- */
1458
- acquire(options?: {
1459
- timeout?: number;
1460
- signal?: AbortSignal;
1461
- }): Promise<void>;
1462
- /**
1463
- * Release a permit, allowing waiting operations to proceed.
1464
- */
1465
- release(): void;
1466
- private removeFromQueue;
1467
- /**
1468
- * Execute a function with a permit, automatically releasing it afterwards.
1469
- */
1470
- withPermit<T>(fn: () => Promise<T>, options?: {
1471
- timeout?: number;
1472
- signal?: AbortSignal;
1473
- }): Promise<T>;
1474
- /**
1475
- * Dispose the semaphore, rejecting all waiting operations and preventing new ones.
1476
- */
1477
- dispose(): void;
1478
- /**
1479
- * Get current number of available permits (for debugging)
1480
- */
1481
- getAvailablePermits(): number;
1482
- /**
1483
- * Get current number of waiting operations (for debugging)
1484
- */
1485
- getWaitingCount(): number;
1486
- /**
1487
- * Get maximum number of permits
1488
- */
1489
- getMaxPermits(): number;
1490
- /**
1491
- * Check if the semaphore has been disposed
1492
- */
1493
- isDisposed(): boolean;
1494
- /**
1495
- * Get metrics about the current state of the semaphore
1496
- */
1497
- getMetrics(): {
1498
- availablePermits: number;
1499
- waitingCount: number;
1500
- maxPermits: number;
1501
- utilization: number;
1502
- disposed: boolean;
1503
- };
1504
- }
1505
-
1997
+ declare const QueueEvents: {
1998
+ readonly enqueue: IEvent<QueueEvent>;
1999
+ readonly start: IEvent<QueueEvent>;
2000
+ readonly finish: IEvent<QueueEvent>;
2001
+ readonly error: IEvent<QueueEvent>;
2002
+ readonly cancel: IEvent<QueueEvent>;
2003
+ readonly disposed: IEvent<QueueEvent>;
2004
+ };
2005
+ type QueueEventType = keyof typeof QueueEvents;
2006
+ type QueueEvent = {
2007
+ type: QueueEventType;
2008
+ taskId: number;
2009
+ disposed: boolean;
2010
+ error?: Error;
2011
+ };
1506
2012
  /**
1507
2013
  * Cooperative task queue.
1508
2014
  * • Tasks run one‑after‑another (FIFO ordering).
@@ -1513,6 +2019,10 @@ declare class Queue {
1513
2019
  private tail;
1514
2020
  private disposed;
1515
2021
  private abortController;
2022
+ private readonly eventManager;
2023
+ private nextTaskId;
2024
+ private listenerId;
2025
+ private activeListeners;
1516
2026
  private readonly executionContext;
1517
2027
  private readonly hasAsyncLocalStorage;
1518
2028
  /**
@@ -1528,6 +2038,9 @@ declare class Queue {
1528
2038
  dispose(options?: {
1529
2039
  cancel?: boolean;
1530
2040
  }): Promise<void>;
2041
+ on(type: QueueEventType, handler: (event: QueueEvent) => any): () => void;
2042
+ once(type: QueueEventType, handler: (event: QueueEvent) => any): () => void;
2043
+ private emit;
1531
2044
  }
1532
2045
 
1533
2046
  declare class RunResult<V> {
@@ -1605,8 +2118,9 @@ type AnyResource = IResource<any, any, any, any, any, any, any>;
1605
2118
  type AnyTaskMiddleware = ITaskMiddleware<any, any, any, any>;
1606
2119
  type AnyResourceMiddleware = IResourceMiddleware<any, any, any, any>;
1607
2120
  type AnyHook = IHook<any, any, any>;
1608
- type OverridePatch<T> = T extends AnyTask ? Omit<Partial<T>, "id"> & Pick<T, "run"> : T extends AnyResource ? Omit<Partial<T>, "id"> & Pick<T, "init"> : T extends AnyTaskMiddleware ? Omit<Partial<T>, "id"> : T extends AnyResourceMiddleware ? Omit<Partial<T>, "id"> & Pick<T, "run"> : T extends AnyHook ? Omit<Partial<T>, "id" | "on"> & Pick<T, "run"> : never;
1609
- declare function defineOverride<T extends AnyTask | AnyResource | AnyTaskMiddleware | AnyResourceMiddleware | AnyHook>(base: T, patch: OverridePatch<T>): T;
2121
+ type AnyOverrideable = AnyTask | AnyResource | AnyTaskMiddleware | AnyResourceMiddleware | AnyHook;
2122
+ type OverridePatch<TBase extends AnyOverrideable> = Readonly<TBase extends AnyHook ? Omit<Partial<TBase>, "id" | "on"> : Omit<Partial<TBase>, "id">>;
2123
+ declare function defineOverride<TBase extends AnyOverrideable>(base: TBase, patch: OverridePatch<TBase>): TBase;
1610
2124
 
1611
2125
  /**
1612
2126
  * Create a tag definition.
@@ -1661,68 +2175,83 @@ declare class PlatformAdapter implements IPlatformAdapter {
1661
2175
  clearTimeout: typeof clearTimeout;
1662
2176
  }
1663
2177
 
1664
- declare const duplicateRegistrationError: ErrorHelper<{
2178
+ declare const duplicateRegistrationError: IErrorHelper<{
1665
2179
  type: string;
1666
2180
  id: string;
1667
2181
  } & DefaultErrorType>;
1668
- declare const dependencyNotFoundError: ErrorHelper<{
2182
+ declare const dependencyNotFoundError: IErrorHelper<{
1669
2183
  key: string;
1670
2184
  } & DefaultErrorType>;
1671
- declare const unknownItemTypeError: ErrorHelper<{
2185
+ declare const unknownItemTypeError: IErrorHelper<{
1672
2186
  item: unknown;
1673
2187
  } & DefaultErrorType>;
1674
- declare const contextError: ErrorHelper<{
2188
+ declare const contextError: IErrorHelper<{
1675
2189
  details?: string;
1676
2190
  } & DefaultErrorType>;
1677
- declare const circularDependenciesError: ErrorHelper<{
2191
+ declare const circularDependenciesError: IErrorHelper<{
1678
2192
  cycles: string[];
1679
2193
  } & DefaultErrorType>;
1680
- declare const eventNotFoundError: ErrorHelper<{
2194
+ declare const eventNotFoundError: IErrorHelper<{
1681
2195
  id: string;
1682
2196
  } & DefaultErrorType>;
1683
- declare const resourceNotFoundError: ErrorHelper<{
2197
+ declare const resourceNotFoundError: IErrorHelper<{
1684
2198
  id: string;
1685
2199
  } & DefaultErrorType>;
1686
- declare const middlewareNotRegisteredError: ErrorHelper<{
2200
+ declare const middlewareNotRegisteredError: IErrorHelper<{
1687
2201
  type: "task" | "resource";
1688
2202
  source: string;
1689
2203
  middlewareId: string;
1690
2204
  } & DefaultErrorType>;
1691
- declare const tagNotFoundError: ErrorHelper<{
2205
+ declare const tagNotFoundError: IErrorHelper<{
1692
2206
  id: string;
1693
2207
  } & DefaultErrorType>;
1694
- declare const lockedError: ErrorHelper<{
2208
+ declare const lockedError: IErrorHelper<{
1695
2209
  what: string;
1696
2210
  } & DefaultErrorType>;
1697
- declare const storeAlreadyInitializedError: ErrorHelper<DefaultErrorType>;
1698
- declare const validationError: ErrorHelper<{
2211
+ declare const storeAlreadyInitializedError: IErrorHelper<DefaultErrorType>;
2212
+ declare const validationError: IErrorHelper<{
1699
2213
  subject: string;
1700
2214
  id: string;
1701
2215
  originalError: string | Error;
1702
2216
  } & DefaultErrorType>;
1703
- declare const eventCycleError: ErrorHelper<{
2217
+ declare const eventCycleError: IErrorHelper<{
1704
2218
  path: Array<{
1705
2219
  id: string;
1706
2220
  source: string;
1707
2221
  }>;
1708
2222
  } & DefaultErrorType>;
1709
- declare const eventEmissionCycleError: ErrorHelper<{
2223
+ declare const eventEmissionCycleError: IErrorHelper<{
1710
2224
  cycles: string[];
1711
2225
  } & DefaultErrorType>;
1712
- declare const platformUnsupportedFunctionError: ErrorHelper<{
2226
+ declare const platformUnsupportedFunctionError: IErrorHelper<{
1713
2227
  functionName: string;
1714
2228
  } & DefaultErrorType>;
1715
- declare const cancellationError: ErrorHelper<{
2229
+ declare const cancellationError: IErrorHelper<{
1716
2230
  reason?: string;
1717
2231
  } & DefaultErrorType>;
1718
- declare const tunnelOwnershipConflictError: ErrorHelper<{
2232
+ declare const tunnelOwnershipConflictError: IErrorHelper<{
1719
2233
  taskId: string;
1720
2234
  currentOwnerId: string;
1721
2235
  attemptedOwnerId: string;
1722
2236
  } & DefaultErrorType>;
2237
+ declare const phantomTaskNotRoutedError: IErrorHelper<{
2238
+ taskId: string;
2239
+ } & DefaultErrorType>;
2240
+ declare const taskNotRegisteredError: IErrorHelper<{
2241
+ taskId: string;
2242
+ } & DefaultErrorType>;
2243
+ /** Builder types that require validation before build() */
2244
+ type BuilderType = "hook" | "task-middleware" | "resource-middleware";
2245
+ declare const builderIncompleteError: IErrorHelper<{
2246
+ type: BuilderType;
2247
+ builderId: string;
2248
+ missingFields: string[];
2249
+ } & DefaultErrorType>;
1723
2250
  declare function isCancellationError(err: unknown): boolean;
1724
2251
 
2252
+ type errors_BuilderType = BuilderType;
1725
2253
  type errors_IErrorHelper<TData extends DefaultErrorType = DefaultErrorType> = IErrorHelper<TData>;
2254
+ declare const errors_builderIncompleteError: typeof builderIncompleteError;
1726
2255
  declare const errors_cancellationError: typeof cancellationError;
1727
2256
  declare const errors_circularDependenciesError: typeof circularDependenciesError;
1728
2257
  declare const errors_contextError: typeof contextError;
@@ -1734,15 +2263,17 @@ declare const errors_eventNotFoundError: typeof eventNotFoundError;
1734
2263
  declare const errors_isCancellationError: typeof isCancellationError;
1735
2264
  declare const errors_lockedError: typeof lockedError;
1736
2265
  declare const errors_middlewareNotRegisteredError: typeof middlewareNotRegisteredError;
2266
+ declare const errors_phantomTaskNotRoutedError: typeof phantomTaskNotRoutedError;
1737
2267
  declare const errors_platformUnsupportedFunctionError: typeof platformUnsupportedFunctionError;
1738
2268
  declare const errors_resourceNotFoundError: typeof resourceNotFoundError;
1739
2269
  declare const errors_storeAlreadyInitializedError: typeof storeAlreadyInitializedError;
1740
2270
  declare const errors_tagNotFoundError: typeof tagNotFoundError;
2271
+ declare const errors_taskNotRegisteredError: typeof taskNotRegisteredError;
1741
2272
  declare const errors_tunnelOwnershipConflictError: typeof tunnelOwnershipConflictError;
1742
2273
  declare const errors_unknownItemTypeError: typeof unknownItemTypeError;
1743
2274
  declare const errors_validationError: typeof validationError;
1744
2275
  declare namespace errors {
1745
- export { type errors_IErrorHelper as IErrorHelper, errors_cancellationError as cancellationError, errors_circularDependenciesError as circularDependenciesError, errors_contextError as contextError, errors_dependencyNotFoundError as dependencyNotFoundError, errors_duplicateRegistrationError as duplicateRegistrationError, errors_eventCycleError as eventCycleError, errors_eventEmissionCycleError as eventEmissionCycleError, errors_eventNotFoundError as eventNotFoundError, errors_isCancellationError as isCancellationError, errors_lockedError as lockedError, errors_middlewareNotRegisteredError as middlewareNotRegisteredError, errors_platformUnsupportedFunctionError as platformUnsupportedFunctionError, errors_resourceNotFoundError as resourceNotFoundError, errors_storeAlreadyInitializedError as storeAlreadyInitializedError, errors_tagNotFoundError as tagNotFoundError, errors_tunnelOwnershipConflictError as tunnelOwnershipConflictError, errors_unknownItemTypeError as unknownItemTypeError, errors_validationError as validationError };
2276
+ export { type errors_BuilderType as BuilderType, type errors_IErrorHelper as IErrorHelper, errors_builderIncompleteError as builderIncompleteError, errors_cancellationError as cancellationError, errors_circularDependenciesError as circularDependenciesError, errors_contextError as contextError, errors_dependencyNotFoundError as dependencyNotFoundError, errors_duplicateRegistrationError as duplicateRegistrationError, errors_eventCycleError as eventCycleError, errors_eventEmissionCycleError as eventEmissionCycleError, errors_eventNotFoundError as eventNotFoundError, errors_isCancellationError as isCancellationError, errors_lockedError as lockedError, errors_middlewareNotRegisteredError as middlewareNotRegisteredError, errors_phantomTaskNotRoutedError as phantomTaskNotRoutedError, errors_platformUnsupportedFunctionError as platformUnsupportedFunctionError, errors_resourceNotFoundError as resourceNotFoundError, errors_storeAlreadyInitializedError as storeAlreadyInitializedError, errors_tagNotFoundError as tagNotFoundError, errors_taskNotRegisteredError as taskNotRegisteredError, errors_tunnelOwnershipConflictError as tunnelOwnershipConflictError, errors_unknownItemTypeError as unknownItemTypeError, errors_validationError as validationError };
1746
2277
  }
1747
2278
 
1748
2279
  /**
@@ -1778,6 +2309,27 @@ declare function buildTestFacade(deps: {
1778
2309
  eventManager: EventManager;
1779
2310
  };
1780
2311
 
2312
+ type HookOn = "*" | IEventDefinition<any> | readonly IEventDefinition<any>[];
2313
+ interface HookOverrideBuilder<TDeps extends DependencyMapType, TOn extends HookOn, TMeta extends ITaskMeta> {
2314
+ id: string;
2315
+ order(order: number): HookOverrideBuilder<TDeps, TOn, TMeta>;
2316
+ dependencies<TNewDeps extends DependencyMapType, TIsOverride extends boolean = false>(deps: TNewDeps | (() => TNewDeps), options?: {
2317
+ override?: TIsOverride;
2318
+ }): HookOverrideBuilder<TIsOverride extends true ? TNewDeps : TDeps & TNewDeps, TOn, TMeta>;
2319
+ tags<TNewTags extends TagType[]>(t: TNewTags, options?: {
2320
+ override?: boolean;
2321
+ }): HookOverrideBuilder<TDeps, TOn, TMeta>;
2322
+ meta<TNewMeta extends ITaskMeta>(m: TNewMeta): HookOverrideBuilder<TDeps, TOn, TNewMeta>;
2323
+ run(fn: IHookDefinition<TDeps, TOn, TMeta>["run"]): HookOverrideBuilder<TDeps, TOn, TMeta>;
2324
+ build(): IHook<TDeps, TOn, TMeta>;
2325
+ }
2326
+
2327
+ declare function override<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType, TMeta extends ITaskMeta, TTags extends TagType[], TMiddleware extends TaskMiddlewareAttachmentType[]>(base: ITask<TInput, TOutput, TDeps, TMeta, TTags, TMiddleware>): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, TTags, TMiddleware>;
2328
+ declare function override<TConfig, TValue extends Promise<any>, TDeps extends DependencyMapType, TContext, TMeta extends IResourceMeta, TTags extends TagType[], TMiddleware extends ResourceMiddlewareAttachmentType[]>(base: IResource<TConfig, TValue, TDeps, TContext, TMeta, TTags, TMiddleware>): ResourceFluentBuilder<TConfig, TValue, TDeps, TContext, TMeta, TTags, TMiddleware>;
2329
+ declare function override<TDeps extends DependencyMapType, TOn extends HookOn, TMeta extends ITaskMeta>(base: IHook<TDeps, TOn, TMeta>): HookOverrideBuilder<TDeps, TOn, TMeta>;
2330
+ declare function override<C, In, Out, D extends DependencyMapType>(base: ITaskMiddleware<C, In, Out, D>): TaskMiddlewareFluentBuilder<C, In, Out, D>;
2331
+ declare function override<C, In, Out, D extends DependencyMapType>(base: IResourceMiddleware<C, In, Out, D>): ResourceMiddlewareFluentBuilder<C, In, Out, D>;
2332
+
1781
2333
  type DebugConfig = {
1782
2334
  logResourceConfig: boolean;
1783
2335
  logResourceValue: boolean;
@@ -1823,23 +2375,24 @@ interface HttpClientConfig {
1823
2375
  auth?: HttpClientAuth;
1824
2376
  timeoutMs?: number;
1825
2377
  fetchImpl?: typeof fetch;
1826
- serializer: Serializer;
2378
+ serializer: SerializerLike;
1827
2379
  onRequest?: (ctx: {
1828
2380
  url: string;
1829
2381
  headers: Record<string, string>;
1830
2382
  }) => void | Promise<void>;
1831
- contexts?: Array<IAsyncContext<any>>;
2383
+ contexts?: Array<IAsyncContext<unknown>>;
1832
2384
  errorRegistry?: Map<string, IErrorHelper<any>>;
1833
2385
  }
1834
2386
  interface HttpClient {
1835
2387
  task<I = unknown, O = unknown>(id: string, input?: I): Promise<O>;
1836
2388
  event<P = unknown>(id: string, payload?: P): Promise<void>;
2389
+ eventWithResult?<P = unknown>(id: string, payload?: P): Promise<P>;
1837
2390
  }
1838
2391
  declare function createHttpClient(cfg: HttpClientConfig): HttpClient;
1839
2392
 
1840
2393
  /**
1841
2394
  * Factory for creating HTTP clients with automatic injection of:
1842
- * - serializer (EJSON-compatible)
2395
+ * - serializer
1843
2396
  * - error registry (from Store)
1844
2397
  * - async contexts (from Store)
1845
2398
  *
@@ -1856,6 +2409,40 @@ interface HttpClientFactoryConfig {
1856
2409
  }
1857
2410
  type HttpClientFactory = (config: HttpClientFactoryConfig) => HttpClient;
1858
2411
 
2412
+ /**
2413
+ * Implementation of ExecutionJournal.
2414
+ * Created per task execution and passed through the middleware chain.
2415
+ */
2416
+ declare class ExecutionJournalImpl implements ExecutionJournal {
2417
+ private readonly store;
2418
+ /**
2419
+ * Store a value in the journal.
2420
+ * Throws an error if the key already exists unless { override: true } is passed.
2421
+ */
2422
+ set<T>(key: JournalKey<T>, value: T, options?: JournalSetOptions): void;
2423
+ get<T>(key: JournalKey<T>): T | undefined;
2424
+ has<T>(key: JournalKey<T>): boolean;
2425
+ }
2426
+ /**
2427
+ * Creates a typed journal key for use with ExecutionJournal.
2428
+ *
2429
+ * @example
2430
+ * ```typescript
2431
+ * const abortController = journal.createKey<AbortController>("timeout.abortController");
2432
+ * journal.set(abortController, new AbortController());
2433
+ * const ctrl = journal.get(abortController); // AbortController | undefined
2434
+ * ```
2435
+ */
2436
+ declare function createKey<T>(id: string): JournalKey<T>;
2437
+ declare const journal: {
2438
+ createKey: typeof createKey;
2439
+ /**
2440
+ * Creates a new empty ExecutionJournal.
2441
+ * Useful when you need to pass a specific journal instance to `runTask` or nested calls.
2442
+ */
2443
+ create: () => ExecutionJournalImpl;
2444
+ };
2445
+
1859
2446
  declare const createContext: typeof createContext$1;
1860
2447
 
1861
2448
  declare const r: Readonly<{
@@ -1864,6 +2451,7 @@ declare const r: Readonly<{
1864
2451
  event: typeof eventBuilder;
1865
2452
  hook: typeof hookBuilder;
1866
2453
  tag: typeof tagBuilder;
2454
+ override: typeof override;
1867
2455
  asyncContext: typeof asyncContextBuilder;
1868
2456
  error: typeof errorBuilder;
1869
2457
  middleware: Readonly<{
@@ -1922,7 +2510,7 @@ type RunOptions = {
1922
2510
  * When set, forces runtime cycle detection for event emissions. Disable if you're sure
1923
2511
  * you don't have event deadlocks to improve event emission performance.
1924
2512
  */
1925
- runtimeCycleDetection?: boolean;
2513
+ runtimeEventCycleDetection?: boolean;
1926
2514
  /**
1927
2515
  * Specify in which mode to run "dev", "prod" or "test".
1928
2516
  * If inside Node this is automatically detected from the NODE_ENV environment variable if not provided.
@@ -1942,6 +2530,8 @@ interface ICacheInstance {
1942
2530
  set(key: string, value: any): void;
1943
2531
  get(key: string): any;
1944
2532
  clear(): void;
2533
+ /** Optional presence check to disambiguate cached undefined values */
2534
+ has?(key: string): boolean;
1945
2535
  }
1946
2536
 
1947
2537
  /**
@@ -1961,13 +2551,12 @@ interface ICacheInstance {
1961
2551
  * - Safe overrides and strong typing around config and register mechanics
1962
2552
  */
1963
2553
 
1964
- declare const defs_ASYNC_CONTEXT_TYPES_LOADED: typeof ASYNC_CONTEXT_TYPES_LOADED;
1965
2554
  type defs_CommonPayload<T extends readonly IEventDefinition<any>[] | IEventDefinition<any>> = CommonPayload<T>;
1966
2555
  type defs_DefaultErrorType = DefaultErrorType;
1967
2556
  type defs_DependencyMapType = DependencyMapType;
1968
2557
  type defs_DependencyValueType<T> = DependencyValueType<T>;
1969
2558
  type defs_DependencyValuesType<T extends DependencyMapType> = DependencyValuesType<T>;
1970
- declare const defs_ERROR_TYPES_LOADED: typeof ERROR_TYPES_LOADED;
2559
+ type defs_ErrorReference = ErrorReference;
1971
2560
  type defs_EventHandlerType<T = any> = EventHandlerType<T>;
1972
2561
  type defs_EventStoreElementType = EventStoreElementType;
1973
2562
  type defs_ExtractEventPayload<T> = ExtractEventPayload<T>;
@@ -1995,7 +2584,7 @@ type defs_IMiddlewareMeta = IMiddlewareMeta;
1995
2584
  type defs_IOptionalDependency<T> = IOptionalDependency<T>;
1996
2585
  type defs_IPhantomTask<TInput = any, TResolved = any, TDependencies extends DependencyMapType = {}, TMeta extends ITaskMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> = IPhantomTask<TInput, TResolved, TDependencies, TMeta, TTags, TMiddleware>;
1997
2586
  type defs_IResource<TConfig = void, TValue extends Promise<any> = Promise<any>, TDependencies extends DependencyMapType = any, TContext = any, TMeta extends IResourceMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends ResourceMiddlewareAttachmentType[] = ResourceMiddlewareAttachmentType[]> = IResource<TConfig, TValue, TDependencies, TContext, TMeta, TTags, TMiddleware>;
1998
- type defs_IResourceDefinition<TConfig = any, TValue extends Promise<any> = Promise<any>, TDependencies extends DependencyMapType = {}, TContext = any, THooks = any, TRegisterableItems = any, TMeta extends IResourceMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends ResourceMiddlewareAttachmentType[] = ResourceMiddlewareAttachmentType[]> = IResourceDefinition<TConfig, TValue, TDependencies, TContext, THooks, TRegisterableItems, TMeta, TTags, TMiddleware>;
2587
+ type defs_IResourceDefinition<TConfig = any, TValue extends Promise<any> = Promise<any>, TDependencies extends DependencyMapType = {}, TContext = any, _THooks = any, _TRegisterableItems = any, TMeta extends IResourceMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends ResourceMiddlewareAttachmentType[] = ResourceMiddlewareAttachmentType[]> = IResourceDefinition<TConfig, TValue, TDependencies, TContext, _THooks, _TRegisterableItems, TMeta, TTags, TMiddleware>;
1999
2588
  type defs_IResourceMeta = IResourceMeta;
2000
2589
  type defs_IResourceMiddleware<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> = IResourceMiddleware<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
2001
2590
  type defs_IResourceMiddlewareConfigured<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> = IResourceMiddlewareConfigured<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
@@ -2004,7 +2593,7 @@ type defs_IResourceMiddlewareExecutionInput<TResourceConfig = any, TResourceOutp
2004
2593
  type defs_IResourceWithConfig<TConfig = any, TValue extends Promise<any> = Promise<any>, TDependencies extends DependencyMapType = any, TContext = any, TMeta extends IResourceMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends IResourceMiddleware<any, any, any, any>[] = IResourceMiddleware[]> = IResourceWithConfig<TConfig, TValue, TDependencies, TContext, TMeta, TTags, TMiddleware>;
2005
2594
  type defs_ITag<TConfig = void, TEnforceInputContract = void, TEnforceOutputContract = void> = ITag<TConfig, TEnforceInputContract, TEnforceOutputContract>;
2006
2595
  type defs_ITagConfigured<TConfig = void, TEnforceInputContract = void, TEnforceOutputContract = void> = ITagConfigured<TConfig, TEnforceInputContract, TEnforceOutputContract>;
2007
- type defs_ITagDefinition<TConfig = void, TEnforceInputContract = void, TEnforceOutputContract = void> = ITagDefinition<TConfig, TEnforceInputContract, TEnforceOutputContract>;
2596
+ type defs_ITagDefinition<TConfig = void, _TEnforceInputContract = void, _TEnforceOutputContract = void> = ITagDefinition<TConfig, _TEnforceInputContract, _TEnforceOutputContract>;
2008
2597
  type defs_ITagMeta = ITagMeta;
2009
2598
  type defs_ITaggable = ITaggable;
2010
2599
  type defs_ITask<TInput = any, TOutput extends Promise<any> = any, TDependencies extends DependencyMapType = {}, TMeta extends ITaskMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> = ITask<TInput, TOutput, TDependencies, TMeta, TTags, TMiddleware>;
@@ -2020,6 +2609,9 @@ type defs_RegisterableItems = RegisterableItems;
2020
2609
  type defs_RequiredKeys<T> = RequiredKeys<T>;
2021
2610
  type defs_ResourceDependencyValueType<T> = ResourceDependencyValueType<T>;
2022
2611
  type defs_ResourceDependencyValuesType<T extends DependencyMapType> = ResourceDependencyValuesType<T>;
2612
+ type defs_ResourceForkInfo = ResourceForkInfo;
2613
+ type defs_ResourceForkOptions = ResourceForkOptions;
2614
+ type defs_ResourceForkRegisterMode = ResourceForkRegisterMode;
2023
2615
  type defs_ResourceInitFn<TConfig, TValue extends Promise<any>, TDependencies extends DependencyMapType, TContext, TMeta extends IResourceMeta, TTags extends TagType[], TMiddleware extends ResourceMiddlewareAttachmentType[]> = ResourceInitFn<TConfig, TValue, TDependencies, TContext, TMeta, TTags, TMiddleware>;
2024
2616
  type defs_ResourceMiddlewareAttachmentType = ResourceMiddlewareAttachmentType;
2025
2617
  type defs_ResourceMiddlewareStoreElementType<TDeps extends DependencyMapType = any> = ResourceMiddlewareStoreElementType<TDeps>;
@@ -2028,11 +2620,13 @@ type defs_RunOptions = RunOptions;
2028
2620
  type defs_RunnerMode = RunnerMode;
2029
2621
  declare const defs_RunnerMode: typeof RunnerMode;
2030
2622
  type defs_TagType = TagType;
2623
+ type defs_TaskCallOptions = TaskCallOptions;
2031
2624
  type defs_TaskDependencyWithIntercept<TInput, TOutput> = TaskDependencyWithIntercept<TInput, TOutput>;
2032
2625
  type defs_TaskLocalInterceptor<TInput, TOutput> = TaskLocalInterceptor<TInput, TOutput>;
2033
2626
  type defs_TaskMiddlewareAttachmentType = TaskMiddlewareAttachmentType;
2034
2627
  type defs_TaskMiddlewareStoreElementType<TDeps extends DependencyMapType = any> = TaskMiddlewareStoreElementType<TDeps>;
2035
2628
  type defs_TaskStoreElementType<Input = any, Output extends Promise<any> = any, D extends DependencyMapType = any> = TaskStoreElementType<Input, Output, D>;
2629
+ type defs_ThrowsList = ThrowsList;
2036
2630
  type defs_UnionToIntersection<U> = UnionToIntersection<U>;
2037
2631
  declare const defs_isOneOf: typeof isOneOf;
2038
2632
  declare const defs_onAnyOf: typeof onAnyOf;
@@ -2046,6 +2640,7 @@ declare const defs_symbolMiddlewareConfigured: typeof symbolMiddlewareConfigured
2046
2640
  declare const defs_symbolOptionalDependency: typeof symbolOptionalDependency;
2047
2641
  declare const defs_symbolPhantomTask: typeof symbolPhantomTask;
2048
2642
  declare const defs_symbolResource: typeof symbolResource;
2643
+ declare const defs_symbolResourceForkedFrom: typeof symbolResourceForkedFrom;
2049
2644
  declare const defs_symbolResourceMiddleware: typeof symbolResourceMiddleware;
2050
2645
  declare const defs_symbolResourceWithConfig: typeof symbolResourceWithConfig;
2051
2646
  declare const defs_symbolTag: typeof symbolTag;
@@ -2054,7 +2649,7 @@ declare const defs_symbolTask: typeof symbolTask;
2054
2649
  declare const defs_symbolTaskMiddleware: typeof symbolTaskMiddleware;
2055
2650
  declare const defs_symbolTunneledBy: typeof symbolTunneledBy;
2056
2651
  declare namespace defs {
2057
- export { defs_ASYNC_CONTEXT_TYPES_LOADED as ASYNC_CONTEXT_TYPES_LOADED, type defs_CommonPayload as CommonPayload, type defs_DefaultErrorType as DefaultErrorType, type defs_DependencyMapType as DependencyMapType, type defs_DependencyValueType as DependencyValueType, type defs_DependencyValuesType as DependencyValuesType, defs_ERROR_TYPES_LOADED as ERROR_TYPES_LOADED, type defs_EventHandlerType as EventHandlerType, type defs_EventStoreElementType as EventStoreElementType, type defs_ExtractEventPayload as ExtractEventPayload, type defs_ExtractResourceConfig as ExtractResourceConfig, type defs_ExtractResourceValue as ExtractResourceValue, type defs_ExtractTaskInput as ExtractTaskInput, type defs_ExtractTaskOutput as ExtractTaskOutput, type defs_HookStoreElementType as HookStoreElementType, type defs_IAsyncContext as IAsyncContext, type defs_IAsyncContextDefinition as IAsyncContextDefinition, type defs_IAsyncContextMeta as IAsyncContextMeta, type defs_ICacheInstance as ICacheInstance, type defs_IErrorDefinition as IErrorDefinition, type defs_IErrorDefinitionFinal as IErrorDefinitionFinal, type defs_IErrorHelper as IErrorHelper, type defs_IErrorMeta as IErrorMeta, type defs_IEvent as IEvent, type defs_IEventDefinition as IEventDefinition, type defs_IEventEmission as IEventEmission, type defs_IEventMeta as IEventMeta, type defs_IHook as IHook, type defs_IHookDefinition as IHookDefinition, type defs_IMeta as IMeta, type defs_IMiddlewareMeta as IMiddlewareMeta, type defs_IOptionalDependency as IOptionalDependency, type defs_IPhantomTask as IPhantomTask, type defs_IResource as IResource, type defs_IResourceDefinition as IResourceDefinition, type defs_IResourceMeta as IResourceMeta, type defs_IResourceMiddleware as IResourceMiddleware, type defs_IResourceMiddlewareConfigured as IResourceMiddlewareConfigured, type defs_IResourceMiddlewareDefinition as IResourceMiddlewareDefinition, type defs_IResourceMiddlewareExecutionInput as IResourceMiddlewareExecutionInput, type defs_IResourceWithConfig as IResourceWithConfig, type defs_ITag as ITag, type defs_ITagConfigured as ITagConfigured, type defs_ITagDefinition as ITagDefinition, type defs_ITagMeta as ITagMeta, type defs_ITaggable as ITaggable, type defs_ITask as ITask, type defs_ITaskDefinition as ITaskDefinition, type defs_ITaskMeta as ITaskMeta, type defs_ITaskMiddleware as ITaskMiddleware, type defs_ITaskMiddlewareConfigured as ITaskMiddlewareConfigured, type defs_ITaskMiddlewareDefinition as ITaskMiddlewareDefinition, type defs_ITaskMiddlewareExecutionInput as ITaskMiddlewareExecutionInput, type defs_IValidationSchema as IValidationSchema, type defs_OverridableElements as OverridableElements, type defs_RegisterableItems as RegisterableItems, type defs_RequiredKeys as RequiredKeys, type defs_ResourceDependencyValueType as ResourceDependencyValueType, type defs_ResourceDependencyValuesType as ResourceDependencyValuesType, type defs_ResourceInitFn as ResourceInitFn, type defs_ResourceMiddlewareAttachmentType as ResourceMiddlewareAttachmentType, type defs_ResourceMiddlewareStoreElementType as ResourceMiddlewareStoreElementType, type defs_ResourceStoreElementType as ResourceStoreElementType, type defs_RunOptions as RunOptions, defs_RunnerMode as RunnerMode, type defs_TagType as TagType, type defs_TaskDependencyWithIntercept as TaskDependencyWithIntercept, type defs_TaskLocalInterceptor as TaskLocalInterceptor, type defs_TaskMiddlewareAttachmentType as TaskMiddlewareAttachmentType, type defs_TaskMiddlewareStoreElementType as TaskMiddlewareStoreElementType, type defs_TaskStoreElementType as TaskStoreElementType, type defs_UnionToIntersection as UnionToIntersection, defs_isOneOf as isOneOf, defs_onAnyOf as onAnyOf, defs_symbolAsyncContext as symbolAsyncContext, defs_symbolError as symbolError, defs_symbolEvent as symbolEvent, defs_symbolFilePath as symbolFilePath, defs_symbolHook as symbolHook, defs_symbolMiddleware as symbolMiddleware, defs_symbolMiddlewareConfigured as symbolMiddlewareConfigured, defs_symbolOptionalDependency as symbolOptionalDependency, defs_symbolPhantomTask as symbolPhantomTask, defs_symbolResource as symbolResource, defs_symbolResourceMiddleware as symbolResourceMiddleware, defs_symbolResourceWithConfig as symbolResourceWithConfig, defs_symbolTag as symbolTag, defs_symbolTagConfigured as symbolTagConfigured, defs_symbolTask as symbolTask, defs_symbolTaskMiddleware as symbolTaskMiddleware, defs_symbolTunneledBy as symbolTunneledBy };
2652
+ export { type defs_CommonPayload as CommonPayload, type defs_DefaultErrorType as DefaultErrorType, type defs_DependencyMapType as DependencyMapType, type defs_DependencyValueType as DependencyValueType, type defs_DependencyValuesType as DependencyValuesType, type defs_ErrorReference as ErrorReference, type defs_EventHandlerType as EventHandlerType, type defs_EventStoreElementType as EventStoreElementType, type defs_ExtractEventPayload as ExtractEventPayload, type defs_ExtractResourceConfig as ExtractResourceConfig, type defs_ExtractResourceValue as ExtractResourceValue, type defs_ExtractTaskInput as ExtractTaskInput, type defs_ExtractTaskOutput as ExtractTaskOutput, type defs_HookStoreElementType as HookStoreElementType, type defs_IAsyncContext as IAsyncContext, type defs_IAsyncContextDefinition as IAsyncContextDefinition, type defs_IAsyncContextMeta as IAsyncContextMeta, type defs_ICacheInstance as ICacheInstance, type defs_IErrorDefinition as IErrorDefinition, type defs_IErrorDefinitionFinal as IErrorDefinitionFinal, type defs_IErrorHelper as IErrorHelper, type defs_IErrorMeta as IErrorMeta, type defs_IEvent as IEvent, type defs_IEventDefinition as IEventDefinition, type defs_IEventEmission as IEventEmission, type defs_IEventMeta as IEventMeta, type defs_IHook as IHook, type defs_IHookDefinition as IHookDefinition, type defs_IMeta as IMeta, type defs_IMiddlewareMeta as IMiddlewareMeta, type defs_IOptionalDependency as IOptionalDependency, type defs_IPhantomTask as IPhantomTask, type defs_IResource as IResource, type defs_IResourceDefinition as IResourceDefinition, type defs_IResourceMeta as IResourceMeta, type defs_IResourceMiddleware as IResourceMiddleware, type defs_IResourceMiddlewareConfigured as IResourceMiddlewareConfigured, type defs_IResourceMiddlewareDefinition as IResourceMiddlewareDefinition, type defs_IResourceMiddlewareExecutionInput as IResourceMiddlewareExecutionInput, type defs_IResourceWithConfig as IResourceWithConfig, type defs_ITag as ITag, type defs_ITagConfigured as ITagConfigured, type defs_ITagDefinition as ITagDefinition, type defs_ITagMeta as ITagMeta, type defs_ITaggable as ITaggable, type defs_ITask as ITask, type defs_ITaskDefinition as ITaskDefinition, type defs_ITaskMeta as ITaskMeta, type defs_ITaskMiddleware as ITaskMiddleware, type defs_ITaskMiddlewareConfigured as ITaskMiddlewareConfigured, type defs_ITaskMiddlewareDefinition as ITaskMiddlewareDefinition, type defs_ITaskMiddlewareExecutionInput as ITaskMiddlewareExecutionInput, type defs_IValidationSchema as IValidationSchema, type defs_OverridableElements as OverridableElements, type defs_RegisterableItems as RegisterableItems, type defs_RequiredKeys as RequiredKeys, type defs_ResourceDependencyValueType as ResourceDependencyValueType, type defs_ResourceDependencyValuesType as ResourceDependencyValuesType, type defs_ResourceForkInfo as ResourceForkInfo, type defs_ResourceForkOptions as ResourceForkOptions, type defs_ResourceForkRegisterMode as ResourceForkRegisterMode, type defs_ResourceInitFn as ResourceInitFn, type defs_ResourceMiddlewareAttachmentType as ResourceMiddlewareAttachmentType, type defs_ResourceMiddlewareStoreElementType as ResourceMiddlewareStoreElementType, type defs_ResourceStoreElementType as ResourceStoreElementType, type defs_RunOptions as RunOptions, defs_RunnerMode as RunnerMode, type defs_TagType as TagType, type defs_TaskCallOptions as TaskCallOptions, type defs_TaskDependencyWithIntercept as TaskDependencyWithIntercept, type defs_TaskLocalInterceptor as TaskLocalInterceptor, type defs_TaskMiddlewareAttachmentType as TaskMiddlewareAttachmentType, type defs_TaskMiddlewareStoreElementType as TaskMiddlewareStoreElementType, type defs_TaskStoreElementType as TaskStoreElementType, type defs_ThrowsList as ThrowsList, type defs_UnionToIntersection as UnionToIntersection, defs_isOneOf as isOneOf, defs_onAnyOf as onAnyOf, defs_symbolAsyncContext as symbolAsyncContext, defs_symbolError as symbolError, defs_symbolEvent as symbolEvent, defs_symbolFilePath as symbolFilePath, defs_symbolHook as symbolHook, defs_symbolMiddleware as symbolMiddleware, defs_symbolMiddlewareConfigured as symbolMiddlewareConfigured, defs_symbolOptionalDependency as symbolOptionalDependency, defs_symbolPhantomTask as symbolPhantomTask, defs_symbolResource as symbolResource, defs_symbolResourceForkedFrom as symbolResourceForkedFrom, defs_symbolResourceMiddleware as symbolResourceMiddleware, defs_symbolResourceWithConfig as symbolResourceWithConfig, defs_symbolTag as symbolTag, defs_symbolTagConfigured as symbolTagConfigured, defs_symbolTask as symbolTask, defs_symbolTaskMiddleware as symbolTaskMiddleware, defs_symbolTunneledBy as symbolTunneledBy };
2058
2653
  }
2059
2654
 
2060
2655
  type TunnelMode = "client" | "server" | "both" | "none";
@@ -2082,17 +2677,23 @@ interface ExposureFetchConfig {
2082
2677
  auth?: ExposureFetchAuthConfig;
2083
2678
  timeoutMs?: number;
2084
2679
  fetchImpl?: typeof fetch;
2085
- serializer: Serializer;
2680
+ serializer: SerializerLike;
2086
2681
  onRequest?: (ctx: {
2087
2682
  url: string;
2088
2683
  headers: Record<string, string>;
2089
2684
  }) => void | Promise<void>;
2090
- contexts?: Array<IAsyncContext<any>>;
2685
+ contexts?: Array<IAsyncContext<unknown>>;
2091
2686
  errorRegistry?: Map<string, IErrorHelper<any>>;
2092
2687
  }
2093
2688
  interface ExposureFetchClient {
2094
2689
  task<I = unknown, O = unknown>(id: string, input?: I): Promise<O>;
2095
2690
  event<P = unknown>(id: string, payload?: P): Promise<void>;
2691
+ /**
2692
+ * Emits an event and returns the final payload as seen by the remote Runner.
2693
+ * Requires server support; older servers will respond with `{ ok: true }`
2694
+ * without `result`, in which case clients should throw.
2695
+ */
2696
+ eventWithResult?<P = unknown>(id: string, payload?: P): Promise<P>;
2096
2697
  }
2097
2698
 
2098
2699
  declare function normalizeError(input: unknown): Error;
@@ -2115,12 +2716,35 @@ interface HttpCreateClientConfig {
2115
2716
  auth?: HttpClientAuthConfig;
2116
2717
  timeoutMs?: number;
2117
2718
  fetchImpl?: typeof fetch;
2118
- serializer: Serializer;
2719
+ serializer: SerializerLike;
2720
+ onRequest?: (ctx: {
2721
+ url: string;
2722
+ headers: Record<string, string>;
2723
+ }) => void | Promise<void>;
2724
+ }
2725
+
2726
+ interface HttpSmartClientAuthConfig {
2727
+ header?: string;
2728
+ token: string;
2729
+ }
2730
+ interface HttpSmartClientConfig {
2731
+ baseUrl: string;
2732
+ auth?: HttpSmartClientAuthConfig;
2733
+ timeoutMs?: number;
2734
+ serializer: SerializerLike;
2119
2735
  onRequest?: (ctx: {
2120
2736
  url: string;
2121
2737
  headers: Record<string, string>;
2122
2738
  }) => void | Promise<void>;
2739
+ contexts?: Array<IAsyncContext<unknown>>;
2740
+ errorRegistry?: Map<string, IErrorHelper<any>>;
2741
+ }
2742
+ interface HttpSmartClient {
2743
+ task<I = unknown, O = unknown>(id: string, input?: I): Promise<O | Readable>;
2744
+ event<P = unknown>(id: string, payload?: P): Promise<void>;
2745
+ eventWithResult?<P = unknown>(id: string, payload?: P): Promise<P>;
2123
2746
  }
2747
+ declare function createHttpSmartClient(cfg: HttpSmartClientConfig): HttpSmartClient;
2124
2748
 
2125
2749
  interface MixedHttpClientAuthConfig {
2126
2750
  header?: string;
@@ -2131,24 +2755,52 @@ interface MixedHttpClientConfig {
2131
2755
  auth?: MixedHttpClientAuthConfig;
2132
2756
  timeoutMs?: number;
2133
2757
  fetchImpl?: typeof fetch;
2134
- serializer: Serializer;
2758
+ /**
2759
+ * Forces the Smart client path even for plain JSON inputs.
2760
+ *
2761
+ * Use this when a task may return a stream even when its input is not a stream
2762
+ * and does not include Node File sentinels (ex: download endpoints).
2763
+ *
2764
+ * - `true`: always use Smart for tasks
2765
+ * - predicate: use Smart for selected task ids/inputs
2766
+ */
2767
+ forceSmart?: boolean | ((ctx: {
2768
+ id: string;
2769
+ input: unknown;
2770
+ }) => boolean | Promise<boolean>);
2771
+ serializer: SerializerLike;
2135
2772
  onRequest?: (ctx: {
2136
2773
  url: string;
2137
2774
  headers: Record<string, string>;
2138
2775
  }) => void | Promise<void>;
2139
- contexts?: Array<IAsyncContext<any>>;
2776
+ contexts?: Array<IAsyncContext<unknown>>;
2140
2777
  errorRegistry?: Map<string, IErrorHelper<any>>;
2141
2778
  }
2142
2779
  interface MixedHttpClient {
2143
2780
  task<I = unknown, O = unknown>(id: string, input?: I): Promise<O | Readable | ReadableStream<Uint8Array>>;
2144
2781
  event<P = unknown>(id: string, payload?: P): Promise<void>;
2782
+ eventWithResult?<P = unknown>(id: string, payload?: P): Promise<P>;
2145
2783
  }
2146
2784
  /**
2147
- * Unified Node client that mixes JSON/EJSON fetch for standard calls and
2785
+ * Unified Node client that mixes JSON fetch for standard calls and
2148
2786
  * Smart client for streaming/multipart. Keeps transport details out of app code.
2149
2787
  */
2150
2788
  declare function createHttpMixedClient(cfg: MixedHttpClientConfig): MixedHttpClient;
2151
2789
 
2790
+ interface HttpSmartClientFactoryConfig {
2791
+ baseUrl: string;
2792
+ auth?: {
2793
+ header?: string;
2794
+ token: string;
2795
+ };
2796
+ timeoutMs?: number;
2797
+ onRequest?: (ctx: {
2798
+ url: string;
2799
+ headers: Record<string, string>;
2800
+ }) => void | Promise<void>;
2801
+ }
2802
+ type HttpSmartClientFactory = (config: HttpSmartClientFactoryConfig) => HttpSmartClient;
2803
+
2152
2804
  interface HttpMixedClientFactoryConfig {
2153
2805
  baseUrl: string;
2154
2806
  auth?: {
@@ -2164,57 +2816,21 @@ interface HttpMixedClientFactoryConfig {
2164
2816
  }
2165
2817
  type HttpMixedClientFactory = (config: HttpMixedClientFactoryConfig) => MixedHttpClient;
2166
2818
 
2167
- interface HttpSmartClientAuthConfig {
2168
- header?: string;
2169
- token: string;
2170
- }
2171
- interface HttpSmartClientConfig {
2172
- baseUrl: string;
2173
- auth?: HttpSmartClientAuthConfig;
2174
- timeoutMs?: number;
2175
- serializer: Serializer;
2176
- onRequest?: (ctx: {
2177
- url: string;
2178
- headers: Record<string, string>;
2179
- }) => void | Promise<void>;
2180
- contexts?: Array<IAsyncContext<any>>;
2181
- errorRegistry?: Map<string, IErrorHelper<any>>;
2182
- }
2183
- interface HttpSmartClient {
2184
- task<I = unknown, O = unknown>(id: string, input?: I): Promise<O | Readable>;
2185
- event<P = unknown>(id: string, payload?: P): Promise<void>;
2186
- }
2187
- declare function createHttpSmartClient(cfg: HttpSmartClientConfig): HttpSmartClient;
2188
-
2189
- interface HttpSmartClientFactoryConfig {
2190
- baseUrl: string;
2191
- auth?: {
2192
- header?: string;
2193
- token: string;
2194
- };
2195
- timeoutMs?: number;
2196
- onRequest?: (ctx: {
2197
- url: string;
2198
- headers: Record<string, string>;
2199
- }) => void | Promise<void>;
2200
- }
2201
- type HttpSmartClientFactory = (config: HttpSmartClientFactoryConfig) => HttpSmartClient;
2202
-
2203
2819
  declare const globalResources: {
2204
2820
  readonly store: IResource<void, Promise<Store>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2205
2821
  readonly middlewareManager: IResource<void, Promise<MiddlewareManager>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2206
2822
  readonly eventManager: IResource<void, Promise<EventManager>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2207
2823
  readonly taskRunner: IResource<void, Promise<TaskRunner>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2208
2824
  readonly logger: IResource<void, Promise<Logger>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2209
- readonly serializer: IResource<void, Promise<Serializer>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2825
+ readonly serializer: IResource<void, Promise<SerializerLike>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2210
2826
  readonly cache: IResource<{
2211
2827
  defaultOptions?: any;
2212
2828
  }, Promise<{
2213
2829
  map: Map<string, ICacheInstance>;
2214
- cacheFactoryTask: TaskDependencyWithIntercept<any, Promise<ICacheInstance>>;
2830
+ cacheFactoryTask: TaskDependencyWithIntercept<lru_cache.LRUCache.Options<any, any, any>, Promise<ICacheInstance>>;
2215
2831
  defaultOptions: any;
2216
2832
  }>, {
2217
- cacheFactoryTask: ITask<any, Promise<ICacheInstance>, any, any, TagType[], TaskMiddlewareAttachmentType[]>;
2833
+ cacheFactoryTask: ITask<lru_cache.LRUCache.Options<any, any, any>, Promise<ICacheInstance>, any, any, TagType[], TaskMiddlewareAttachmentType[]>;
2218
2834
  }, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2219
2835
  readonly queue: IResource<void, Promise<{
2220
2836
  map: Map<string, Queue>;
@@ -2226,19 +2842,65 @@ declare const globalResources: {
2226
2842
  description: string;
2227
2843
  }, TagType[], ResourceMiddlewareAttachmentType[]>;
2228
2844
  readonly httpClientFactory: IResource<void, Promise<HttpClientFactory>, {
2229
- serializer: IResource<void, Promise<Serializer>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2845
+ serializer: IResource<void, Promise<SerializerLike>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2230
2846
  store: IResource<void, Promise<Store>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2231
2847
  }, any, {
2232
2848
  title: string;
2233
2849
  description: string;
2234
2850
  }, TagType[], ResourceMiddlewareAttachmentType[]>;
2851
+ readonly rateLimit: IResource<void, Promise<{
2852
+ states: WeakMap<RateLimitMiddlewareConfig, RateLimitState>;
2853
+ }>, {}, any, any, ITag<{
2854
+ metadata?: Record<string, any>;
2855
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2856
+ readonly circuitBreaker: IResource<void, Promise<{
2857
+ statusMap: Map<string, CircuitBreakerStatus>;
2858
+ }>, {}, any, any, ITag<{
2859
+ metadata?: Record<string, any>;
2860
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2861
+ readonly temporal: IResource<void, Promise<{
2862
+ debounceStates: WeakMap<TemporalMiddlewareConfig, DebounceState>;
2863
+ throttleStates: WeakMap<TemporalMiddlewareConfig, ThrottleState>;
2864
+ }>, {}, any, any, ITag<{
2865
+ metadata?: Record<string, any>;
2866
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2867
+ readonly concurrency: IResource<void, Promise<{
2868
+ semaphoresByConfig: WeakMap<ConcurrencyMiddlewareConfig, Semaphore>;
2869
+ semaphoresByKey: Map<string, {
2870
+ semaphore: Semaphore;
2871
+ limit: number;
2872
+ }>;
2873
+ }>, {}, any, any, ITag<{
2874
+ metadata?: Record<string, any>;
2875
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2235
2876
  };
2236
2877
 
2237
2878
  interface NodeExposureHttpAuthConfig {
2238
2879
  header?: string;
2239
- token: string;
2880
+ token?: string | string[];
2881
+ /**
2882
+ * When true, allows unauthenticated access if no token or validators are configured.
2883
+ * Defaults to false (secure by default - requires explicit auth configuration).
2884
+ *
2885
+ * WARNING: Setting this to true without proper network isolation exposes
2886
+ * all tasks and events to unauthenticated access.
2887
+ */
2888
+ allowAnonymous?: boolean;
2889
+ }
2890
+
2891
+ interface MultipartLimits {
2892
+ fieldNameSize?: number;
2893
+ fieldSize?: number;
2894
+ fields?: number;
2895
+ fileSize?: number;
2896
+ files?: number;
2897
+ parts?: number;
2898
+ headerPairs?: number;
2240
2899
  }
2241
2900
 
2901
+ interface JsonLimits {
2902
+ maxSize?: number;
2903
+ }
2242
2904
  type NodeExposureDependencyMap = {
2243
2905
  store: typeof globalResources.store;
2244
2906
  taskRunner: typeof globalResources.taskRunner;
@@ -2256,6 +2918,15 @@ interface NodeExposureHttpConfig {
2256
2918
  };
2257
2919
  auth?: NodeExposureHttpAuthConfig;
2258
2920
  cors?: NodeExposureHttpCorsConfig;
2921
+ limits?: {
2922
+ json?: JsonLimits;
2923
+ multipart?: MultipartLimits;
2924
+ };
2925
+ /**
2926
+ * Opt out of fail-closed exposure (not recommended).
2927
+ * When true and no server-mode tunnel is registered, exposure is open.
2928
+ */
2929
+ dangerouslyAllowOpenExposure?: boolean;
2259
2930
  }
2260
2931
  interface NodeExposureConfig {
2261
2932
  http?: NodeExposureHttpConfig;
@@ -2300,7 +2971,7 @@ declare const nodeExposure: IResource<NodeExposureConfig, Promise<NodeExposureHa
2300
2971
  taskRunner: IResource<void, Promise<TaskRunner>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2301
2972
  eventManager: IResource<void, Promise<EventManager>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2302
2973
  logger: IResource<void, Promise<Logger>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2303
- serializer: IResource<void, Promise<Serializer>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2974
+ serializer: IResource<void, Promise<SerializerLike>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2304
2975
  }, any, {
2305
2976
  title: string;
2306
2977
  description: string;
@@ -2351,8 +3022,8 @@ interface InputFile<TStream = unknown> extends InputFileMeta {
2351
3022
  }>;
2352
3023
  }
2353
3024
  /** Client-side sentinel to declare file presence in an input structure. */
2354
- interface EjsonFileSentinel {
2355
- $ejson: "File";
3025
+ interface RunnerFileSentinel {
3026
+ $runnerFile: "File";
2356
3027
  id: string;
2357
3028
  meta: InputFileMeta;
2358
3029
  }
@@ -2361,7 +3032,7 @@ interface NodeFileSource {
2361
3032
  stream?: Readable;
2362
3033
  buffer?: Buffer;
2363
3034
  }
2364
- declare function createNodeFile(meta: InputFileMeta, source: NodeFileSource, id?: string): EjsonFileSentinel & {
3035
+ declare function createNodeFile(meta: InputFileMeta, source: NodeFileSource, id?: string): RunnerFileSentinel & {
2365
3036
  _node: NodeFileSource;
2366
3037
  };
2367
3038
 
@@ -2378,6 +3049,1386 @@ declare function writeInputFileToPath(file: InputFile<Readable>, targetPath: str
2378
3049
  bytesWritten: number;
2379
3050
  }>;
2380
3051
 
3052
+ declare const ExecutionStatus: {
3053
+ readonly Pending: "pending";
3054
+ readonly Running: "running";
3055
+ readonly Retrying: "retrying";
3056
+ readonly Sleeping: "sleeping";
3057
+ readonly Completed: "completed";
3058
+ readonly CompensationFailed: "compensation_failed";
3059
+ readonly Failed: "failed";
3060
+ readonly Cancelled: "cancelled";
3061
+ };
3062
+ type ExecutionStatus = (typeof ExecutionStatus)[keyof typeof ExecutionStatus];
3063
+ interface Execution<TInput = unknown, TResult = unknown> {
3064
+ id: string;
3065
+ taskId: string;
3066
+ input: TInput | undefined;
3067
+ status: ExecutionStatus;
3068
+ result?: TResult;
3069
+ error?: {
3070
+ message: string;
3071
+ stack?: string;
3072
+ };
3073
+ /** Optional cancellation metadata (cooperative cancellation). */
3074
+ cancelledAt?: Date;
3075
+ cancelRequestedAt?: Date;
3076
+ attempt: number;
3077
+ maxAttempts: number;
3078
+ timeout?: number;
3079
+ createdAt: Date;
3080
+ updatedAt: Date;
3081
+ completedAt?: Date;
3082
+ }
3083
+ interface StepResult<T = unknown> {
3084
+ executionId: string;
3085
+ stepId: string;
3086
+ result: T;
3087
+ completedAt: Date;
3088
+ }
3089
+ declare const TimerType: {
3090
+ readonly Sleep: "sleep";
3091
+ readonly Timeout: "timeout";
3092
+ readonly Scheduled: "scheduled";
3093
+ readonly Cron: "cron";
3094
+ readonly Retry: "retry";
3095
+ readonly SignalTimeout: "signal_timeout";
3096
+ };
3097
+ type TimerType = (typeof TimerType)[keyof typeof TimerType];
3098
+ declare const TimerStatus: {
3099
+ readonly Pending: "pending";
3100
+ readonly Fired: "fired";
3101
+ };
3102
+ type TimerStatus = (typeof TimerStatus)[keyof typeof TimerStatus];
3103
+ interface Timer {
3104
+ id: string;
3105
+ executionId?: string;
3106
+ stepId?: string;
3107
+ scheduleId?: string;
3108
+ taskId?: string;
3109
+ input?: unknown;
3110
+ type: TimerType;
3111
+ fireAt: Date;
3112
+ status: TimerStatus;
3113
+ }
3114
+ declare const ScheduleType: {
3115
+ readonly Cron: "cron";
3116
+ readonly Interval: "interval";
3117
+ };
3118
+ type ScheduleType = (typeof ScheduleType)[keyof typeof ScheduleType];
3119
+ declare const ScheduleStatus: {
3120
+ readonly Active: "active";
3121
+ readonly Paused: "paused";
3122
+ };
3123
+ type ScheduleStatus = (typeof ScheduleStatus)[keyof typeof ScheduleStatus];
3124
+ interface Schedule<TInput = unknown> {
3125
+ id: string;
3126
+ taskId: string;
3127
+ type: ScheduleType;
3128
+ pattern: string;
3129
+ input: TInput | undefined;
3130
+ status: ScheduleStatus;
3131
+ lastRun?: Date;
3132
+ nextRun?: Date;
3133
+ createdAt: Date;
3134
+ updatedAt: Date;
3135
+ }
3136
+
3137
+ type DurableSignalId<TPayload = unknown> = IEventDefinition<TPayload>;
3138
+ interface DurableStepId<TResult = unknown> {
3139
+ id: string;
3140
+ /**
3141
+ * Phantom field used only for type inference. Not present at runtime.
3142
+ * The result type is carried through the object type.
3143
+ */
3144
+ readonly __result?: TResult;
3145
+ }
3146
+ declare function createDurableStepId<TResult>(id: string): DurableStepId<TResult>;
3147
+
3148
+ declare const DurableAuditEntryKind: {
3149
+ readonly ExecutionStatusChanged: "execution_status_changed";
3150
+ readonly StepCompleted: "step_completed";
3151
+ readonly SleepScheduled: "sleep_scheduled";
3152
+ readonly SleepCompleted: "sleep_completed";
3153
+ readonly SignalWaiting: "signal_waiting";
3154
+ readonly SignalDelivered: "signal_delivered";
3155
+ readonly SignalTimedOut: "signal_timed_out";
3156
+ readonly EmitPublished: "emit_published";
3157
+ readonly Note: "note";
3158
+ };
3159
+ type DurableAuditEntryKind = (typeof DurableAuditEntryKind)[keyof typeof DurableAuditEntryKind];
3160
+ interface DurableAuditEntryBase {
3161
+ id: string;
3162
+ executionId: string;
3163
+ at: Date;
3164
+ kind: DurableAuditEntryKind;
3165
+ attempt: number;
3166
+ taskId?: string;
3167
+ }
3168
+ type DurableAuditEntry = (DurableAuditEntryBase & {
3169
+ kind: typeof DurableAuditEntryKind.ExecutionStatusChanged;
3170
+ from: ExecutionStatus | null;
3171
+ to: ExecutionStatus;
3172
+ reason?: string;
3173
+ }) | (DurableAuditEntryBase & {
3174
+ kind: typeof DurableAuditEntryKind.StepCompleted;
3175
+ stepId: string;
3176
+ durationMs: number;
3177
+ isInternal: boolean;
3178
+ }) | (DurableAuditEntryBase & {
3179
+ kind: typeof DurableAuditEntryKind.SleepScheduled;
3180
+ stepId: string;
3181
+ timerId: string;
3182
+ durationMs: number;
3183
+ fireAt: Date;
3184
+ }) | (DurableAuditEntryBase & {
3185
+ kind: typeof DurableAuditEntryKind.SleepCompleted;
3186
+ stepId: string;
3187
+ timerId: string;
3188
+ }) | (DurableAuditEntryBase & {
3189
+ kind: typeof DurableAuditEntryKind.SignalWaiting;
3190
+ stepId: string;
3191
+ signalId: string;
3192
+ timeoutMs?: number;
3193
+ timeoutAtMs?: number;
3194
+ timerId?: string;
3195
+ reason?: "initial" | "timeout_armed";
3196
+ }) | (DurableAuditEntryBase & {
3197
+ kind: typeof DurableAuditEntryKind.SignalDelivered;
3198
+ stepId: string;
3199
+ signalId: string;
3200
+ }) | (DurableAuditEntryBase & {
3201
+ kind: typeof DurableAuditEntryKind.SignalTimedOut;
3202
+ stepId: string;
3203
+ signalId: string;
3204
+ timerId: string;
3205
+ }) | (DurableAuditEntryBase & {
3206
+ kind: typeof DurableAuditEntryKind.EmitPublished;
3207
+ stepId: string;
3208
+ eventId: string;
3209
+ }) | (DurableAuditEntryBase & {
3210
+ kind: typeof DurableAuditEntryKind.Note;
3211
+ message: string;
3212
+ meta?: Record<string, unknown>;
3213
+ });
3214
+ /**
3215
+ * Input type for appendAuditEntry - omits auto-generated fields (id, at).
3216
+ * Preserves the discriminated union for proper type checking at call sites.
3217
+ * executionId and attempt are required for service-level entries but filled by context.
3218
+ */
3219
+ type DurableAuditEntryInput = {
3220
+ kind: typeof DurableAuditEntryKind.ExecutionStatusChanged;
3221
+ executionId: string;
3222
+ attempt: number;
3223
+ from: ExecutionStatus | null;
3224
+ to: ExecutionStatus;
3225
+ reason?: string;
3226
+ taskId?: string;
3227
+ } | {
3228
+ kind: typeof DurableAuditEntryKind.StepCompleted;
3229
+ stepId: string;
3230
+ durationMs: number;
3231
+ isInternal: boolean;
3232
+ taskId?: string;
3233
+ } | {
3234
+ kind: typeof DurableAuditEntryKind.SleepScheduled;
3235
+ stepId: string;
3236
+ timerId: string;
3237
+ durationMs: number;
3238
+ fireAt: Date;
3239
+ taskId?: string;
3240
+ } | {
3241
+ kind: typeof DurableAuditEntryKind.SleepCompleted;
3242
+ executionId: string;
3243
+ attempt: number;
3244
+ stepId: string;
3245
+ timerId: string;
3246
+ taskId?: string;
3247
+ } | {
3248
+ kind: typeof DurableAuditEntryKind.SignalWaiting;
3249
+ stepId: string;
3250
+ signalId: string;
3251
+ timeoutMs?: number;
3252
+ timeoutAtMs?: number;
3253
+ timerId?: string;
3254
+ reason?: "initial" | "timeout_armed";
3255
+ taskId?: string;
3256
+ } | {
3257
+ kind: typeof DurableAuditEntryKind.SignalDelivered;
3258
+ executionId: string;
3259
+ attempt: number;
3260
+ stepId: string;
3261
+ signalId: string;
3262
+ taskId?: string;
3263
+ } | {
3264
+ kind: typeof DurableAuditEntryKind.SignalTimedOut;
3265
+ executionId: string;
3266
+ attempt: number;
3267
+ stepId: string;
3268
+ signalId: string;
3269
+ timerId: string;
3270
+ taskId?: string;
3271
+ } | {
3272
+ kind: typeof DurableAuditEntryKind.EmitPublished;
3273
+ stepId: string;
3274
+ eventId: string;
3275
+ taskId?: string;
3276
+ } | {
3277
+ kind: typeof DurableAuditEntryKind.Note;
3278
+ message: string;
3279
+ meta?: Record<string, unknown>;
3280
+ taskId?: string;
3281
+ };
3282
+ interface DurableAuditEmitter {
3283
+ emit(entry: DurableAuditEntry): Promise<void>;
3284
+ }
3285
+ declare function isDurableInternalStepId(stepId: string): boolean;
3286
+ declare function createDurableAuditEntryId(atMs?: number): string;
3287
+
3288
+ interface ListExecutionsOptions {
3289
+ status?: ExecutionStatus[];
3290
+ taskId?: string;
3291
+ limit?: number;
3292
+ offset?: number;
3293
+ }
3294
+ interface IDurableStore {
3295
+ saveExecution(execution: Execution): Promise<void>;
3296
+ getExecution(id: string): Promise<Execution | null>;
3297
+ updateExecution(id: string, updates: Partial<Execution>): Promise<void>;
3298
+ listIncompleteExecutions(): Promise<Execution[]>;
3299
+ /**
3300
+ * Optional execution-level idempotency mapping.
3301
+ * If supported, allows `startExecution(..., { idempotencyKey })` to dedupe workflow starts.
3302
+ */
3303
+ getExecutionIdByIdempotencyKey?(params: {
3304
+ taskId: string;
3305
+ idempotencyKey: string;
3306
+ }): Promise<string | null>;
3307
+ setExecutionIdByIdempotencyKey?(params: {
3308
+ taskId: string;
3309
+ idempotencyKey: string;
3310
+ executionId: string;
3311
+ }): Promise<boolean>;
3312
+ listExecutions?(options?: ListExecutionsOptions): Promise<Execution[]>;
3313
+ listStepResults?(executionId: string): Promise<StepResult[]>;
3314
+ appendAuditEntry?(entry: DurableAuditEntry): Promise<void>;
3315
+ listAuditEntries?(executionId: string, options?: {
3316
+ limit?: number;
3317
+ offset?: number;
3318
+ }): Promise<DurableAuditEntry[]>;
3319
+ retryRollback?(executionId: string): Promise<void>;
3320
+ skipStep?(executionId: string, stepId: string): Promise<void>;
3321
+ forceFail?(executionId: string, error: {
3322
+ message: string;
3323
+ stack?: string;
3324
+ }): Promise<void>;
3325
+ editStepResult?(executionId: string, stepId: string, newResult: unknown): Promise<void>;
3326
+ getStepResult(executionId: string, stepId: string): Promise<StepResult | null>;
3327
+ saveStepResult(result: StepResult): Promise<void>;
3328
+ createTimer(timer: Timer): Promise<void>;
3329
+ getReadyTimers(now?: Date): Promise<Timer[]>;
3330
+ markTimerFired(timerId: string): Promise<void>;
3331
+ /**
3332
+ * Atomically claim a timer for processing. Returns true if claimed, false if already claimed.
3333
+ * Used for distributed timer coordination to ensure only one worker processes each timer.
3334
+ * @param timerId The ID of the timer to claim
3335
+ * @param workerId A unique identifier for the worker claiming the timer
3336
+ * @param ttlMs Time-to-live in milliseconds for the claim (in case worker dies)
3337
+ */
3338
+ claimTimer?(timerId: string, workerId: string, ttlMs: number): Promise<boolean>;
3339
+ deleteTimer(timerId: string): Promise<void>;
3340
+ createSchedule(schedule: Schedule): Promise<void>;
3341
+ getSchedule(id: string): Promise<Schedule | null>;
3342
+ updateSchedule(id: string, updates: Partial<Schedule>): Promise<void>;
3343
+ deleteSchedule(id: string): Promise<void>;
3344
+ listSchedules(): Promise<Schedule[]>;
3345
+ listActiveSchedules(): Promise<Schedule[]>;
3346
+ listStuckExecutions?(): Promise<Execution[]>;
3347
+ init?(): Promise<void>;
3348
+ dispose?(): Promise<void>;
3349
+ acquireLock?(resource: string, ttlMs: number): Promise<string | null>;
3350
+ releaseLock?(resource: string, lockId: string): Promise<void>;
3351
+ }
3352
+
3353
+ interface QueueMessage<T = unknown> {
3354
+ id: string;
3355
+ type: "execute" | "resume" | "schedule";
3356
+ payload: T;
3357
+ attempts: number;
3358
+ maxAttempts: number;
3359
+ createdAt: Date;
3360
+ }
3361
+ type MessageHandler<T = unknown> = (message: QueueMessage<T>) => Promise<void>;
3362
+ interface IDurableQueue {
3363
+ enqueue<T>(message: Omit<QueueMessage<T>, "id" | "createdAt" | "attempts">): Promise<string>;
3364
+ consume<T>(handler: MessageHandler<T>): Promise<void>;
3365
+ ack(messageId: string): Promise<void>;
3366
+ nack(messageId: string, requeue?: boolean): Promise<void>;
3367
+ init?(): Promise<void>;
3368
+ dispose?(): Promise<void>;
3369
+ }
3370
+
3371
+ interface BusEvent {
3372
+ type: string;
3373
+ payload: unknown;
3374
+ timestamp: Date;
3375
+ }
3376
+ type BusEventHandler = (event: BusEvent) => Promise<void>;
3377
+ interface IEventBus {
3378
+ publish(channel: string, event: BusEvent): Promise<void>;
3379
+ subscribe(channel: string, handler: BusEventHandler): Promise<void>;
3380
+ unsubscribe(channel: string): Promise<void>;
3381
+ init?(): Promise<void>;
3382
+ dispose?(): Promise<void>;
3383
+ }
3384
+
3385
+ interface StepOptions {
3386
+ retries?: number;
3387
+ timeout?: number;
3388
+ }
3389
+ /**
3390
+ * Options for sleep operations.
3391
+ * Use `stepId` to provide a stable identifier that survives code refactoring.
3392
+ */
3393
+ interface SleepOptions {
3394
+ /** Explicit step ID for replay stability. If not provided, an auto-indexed ID is used. */
3395
+ stepId?: string;
3396
+ }
3397
+ /**
3398
+ * Options for waitForSignal operations.
3399
+ */
3400
+ interface SignalOptions {
3401
+ /** Timeout in milliseconds. If provided, returns a discriminated union with kind. */
3402
+ timeoutMs?: number;
3403
+ /** Explicit step ID for replay stability. If not provided, an auto-indexed ID is used. */
3404
+ stepId?: string;
3405
+ }
3406
+ /**
3407
+ * Options for emit operations.
3408
+ */
3409
+ interface EmitOptions {
3410
+ /** Explicit step ID for replay stability. If not provided, an auto-indexed ID is used. */
3411
+ stepId?: string;
3412
+ }
3413
+ interface IStepBuilder<T> extends PromiseLike<T> {
3414
+ up(fn: () => Promise<T>): this;
3415
+ down(fn: (result: T) => Promise<void>): this;
3416
+ }
3417
+ interface IDurableContext {
3418
+ readonly executionId: string;
3419
+ readonly attempt: number;
3420
+ step<T>(stepId: string): IStepBuilder<T>;
3421
+ step<T>(stepId: DurableStepId<T>): IStepBuilder<T>;
3422
+ step<T>(stepId: string, fn: () => Promise<T>): Promise<T>;
3423
+ step<T>(stepId: DurableStepId<T>, fn: () => Promise<T>): Promise<T>;
3424
+ step<T>(stepId: string, options: StepOptions, fn: () => Promise<T>): Promise<T>;
3425
+ step<T>(stepId: DurableStepId<T>, options: StepOptions, fn: () => Promise<T>): Promise<T>;
3426
+ sleep(durationMs: number, options?: SleepOptions): Promise<void>;
3427
+ /**
3428
+ * Suspend until an external signal is delivered via DurableService.signal().
3429
+ * The signal is memoized as a durable step under `__signal:<signalId>[:index]`.
3430
+ * Use options.stepId to provide a stable identifier for replay safety.
3431
+ */
3432
+ waitForSignal<TPayload>(signal: IEventDefinition<TPayload>): Promise<TPayload>;
3433
+ waitForSignal<TPayload>(signal: IEventDefinition<TPayload>, options: SignalOptions & {
3434
+ timeoutMs: number;
3435
+ }): Promise<{
3436
+ kind: "signal";
3437
+ payload: TPayload;
3438
+ } | {
3439
+ kind: "timeout";
3440
+ }>;
3441
+ waitForSignal<TPayload>(signal: IEventDefinition<TPayload>, options: SignalOptions): Promise<TPayload>;
3442
+ emit<TPayload>(event: IEventDefinition<TPayload>, payload: TPayload, options?: EmitOptions): Promise<void>;
3443
+ /**
3444
+ * Append a custom audit entry for observability and debugging.
3445
+ * This is a no-op if audit is disabled or the store does not support it.
3446
+ */
3447
+ note(message: string, meta?: Record<string, unknown>): Promise<void>;
3448
+ rollback(): Promise<void>;
3449
+ }
3450
+ /**
3451
+ * Internal control-flow signal used to suspend a durable execution without failing it.
3452
+ *
3453
+ * `DurableContext` throws this error to indicate "pause here and resume later":
3454
+ * - `"sleep"`: durable sleep timer was scheduled
3455
+ * - `"yield"`: waiting for a signal (or signal-timeout timer) to complete
3456
+ *
3457
+ * `ExecutionManager` treats this as a normal suspension and will not mark the execution
3458
+ * as failed; instead it schedules a resume via timers/queue depending on configuration.
3459
+ */
3460
+ declare class SuspensionSignal extends Error {
3461
+ readonly reason: "sleep" | "yield" | "timeout";
3462
+ constructor(reason: "sleep" | "yield" | "timeout");
3463
+ }
3464
+
3465
+ type DurableTask<TInput = unknown, TResult = unknown> = ITask<TInput, Promise<TResult>, any>;
3466
+ interface ITaskExecutor {
3467
+ run<TInput, TResult>(task: DurableTask<TInput, TResult>, input?: TInput): Promise<TResult>;
3468
+ }
3469
+ interface ScheduleConfig<TInput = unknown> {
3470
+ id: string;
3471
+ task: DurableTask<TInput, unknown>;
3472
+ cron?: string;
3473
+ interval?: number;
3474
+ input: TInput;
3475
+ }
3476
+ interface DurableServiceConfig {
3477
+ store: IDurableStore;
3478
+ queue?: IDurableQueue;
3479
+ eventBus?: IEventBus;
3480
+ taskExecutor?: ITaskExecutor;
3481
+ determinism?: {
3482
+ /**
3483
+ * Internal step IDs for `sleep()`/`emit()`/`waitForSignal()` default to call-order based IDs.
3484
+ * In production this can be a replay/versioning footgun when refactors change call order.
3485
+ *
3486
+ * - "allow" (default): do nothing
3487
+ * - "warn": emit a warning on first implicit internal step per kind
3488
+ * - "error": throw when an implicit internal step id would be used
3489
+ */
3490
+ implicitInternalStepIds?: "allow" | "warn" | "error";
3491
+ };
3492
+ /**
3493
+ * Unique identifier for this worker instance.
3494
+ * Used for distributed timer coordination to ensure only one worker processes each timer.
3495
+ * If not provided, a random UUID is generated.
3496
+ */
3497
+ workerId?: string;
3498
+ /**
3499
+ * Runs a callback with the given durable context available.
3500
+ * In Runner environments this is typically implemented via AsyncLocalStorage
3501
+ * so tasks can call `durable.use()`.
3502
+ */
3503
+ contextProvider?: <R>(context: IDurableContext, fn: () => Promise<R> | R) => Promise<R> | R;
3504
+ /**
3505
+ * Resolves tasks by id for resuming/recovering executions.
3506
+ * Useful in Runner environments where tasks are registered in the Store registry.
3507
+ */
3508
+ taskResolver?: (taskId: string) => DurableTask<any, any> | undefined;
3509
+ audit?: {
3510
+ enabled?: boolean;
3511
+ emitter?: DurableAuditEmitter;
3512
+ };
3513
+ polling?: {
3514
+ enabled?: boolean;
3515
+ interval?: number;
3516
+ /** Time-to-live for timer claims in milliseconds. Default: 30000. */
3517
+ claimTtlMs?: number;
3518
+ };
3519
+ execution?: {
3520
+ maxAttempts?: number;
3521
+ timeout?: number;
3522
+ /**
3523
+ * When a queue is configured, `startExecution()` persists the execution and then enqueues it.
3524
+ * If enqueue fails (eg. broker outage), the execution would otherwise remain "pending" forever.
3525
+ *
3526
+ * This delay arms a small store-backed timer as a failsafe so workers can retry resuming it
3527
+ * via the poller. Default: 10000 (10s). Set to 0 to disable.
3528
+ */
3529
+ kickoffFailsafeDelayMs?: number;
3530
+ };
3531
+ schedules?: ScheduleConfig[];
3532
+ tasks?: Array<DurableTask<any, any>>;
3533
+ }
3534
+ interface ExecuteOptions {
3535
+ timeout?: number;
3536
+ priority?: number;
3537
+ waitPollIntervalMs?: number;
3538
+ /**
3539
+ * Optional workflow-level idempotency key.
3540
+ * When supported by the store, multiple concurrent callers using the same key will receive the same executionId.
3541
+ */
3542
+ idempotencyKey?: string;
3543
+ }
3544
+ interface ScheduleOptions {
3545
+ id?: string;
3546
+ at?: Date;
3547
+ delay?: number;
3548
+ cron?: string;
3549
+ interval?: number;
3550
+ }
3551
+ interface IDurableService {
3552
+ startExecution<TInput>(task: DurableTask<TInput, unknown>, input?: TInput, options?: ExecuteOptions): Promise<string>;
3553
+ /**
3554
+ * Request cancellation for an execution.
3555
+ * Cancellation is cooperative: it marks the execution as cancelled and unblocks waiters,
3556
+ * but cannot preempt arbitrary in-process async work.
3557
+ */
3558
+ cancelExecution(executionId: string, reason?: string): Promise<void>;
3559
+ wait<TResult>(executionId: string, options?: {
3560
+ timeout?: number;
3561
+ waitPollIntervalMs?: number;
3562
+ }): Promise<TResult>;
3563
+ execute<TInput, TResult>(task: DurableTask<TInput, TResult>, input?: TInput, options?: ExecuteOptions): Promise<TResult>;
3564
+ /**
3565
+ * A stricter alternative to `execute()` that rejects tasks whose result type
3566
+ * includes `undefined` (including `void`, `unknown`, and `any`).
3567
+ *
3568
+ * This mirrors the runtime contract where `wait()`/`execute()` treat
3569
+ * "completed without result" as an error.
3570
+ */
3571
+ executeStrict<TInput, TResult>(task: undefined extends TResult ? never : DurableTask<TInput, TResult>, input?: TInput, options?: ExecuteOptions): Promise<TResult>;
3572
+ schedule<TInput>(task: DurableTask<TInput, unknown>, input: TInput | undefined, options: ScheduleOptions): Promise<string>;
3573
+ /**
3574
+ * Idempotently create (or update) a recurring schedule (cron/interval) with a stable id.
3575
+ * Safe to call concurrently from multiple processes.
3576
+ */
3577
+ ensureSchedule<TInput>(task: DurableTask<TInput, unknown>, input: TInput | undefined, options: ScheduleOptions & {
3578
+ id: string;
3579
+ }): Promise<string>;
3580
+ recover(): Promise<void>;
3581
+ start(): void;
3582
+ stop(): Promise<void>;
3583
+ pauseSchedule(scheduleId: string): Promise<void>;
3584
+ resumeSchedule(scheduleId: string): Promise<void>;
3585
+ getSchedule(scheduleId: string): Promise<Schedule | null>;
3586
+ listSchedules(): Promise<Schedule[]>;
3587
+ updateSchedule(scheduleId: string, updates: {
3588
+ cron?: string;
3589
+ interval?: number;
3590
+ input?: unknown;
3591
+ }): Promise<void>;
3592
+ removeSchedule(scheduleId: string): Promise<void>;
3593
+ /**
3594
+ * Deliver a signal payload to a waiting workflow execution and resume it.
3595
+ */
3596
+ signal<TPayload>(executionId: string, signal: IEventDefinition<TPayload>, payload: TPayload): Promise<void>;
3597
+ }
3598
+ interface IDurableExecutionProcessor {
3599
+ processExecution(executionId: string): Promise<void>;
3600
+ }
3601
+
3602
+ interface DurableResourceConfig {
3603
+ worker?: boolean;
3604
+ }
3605
+ interface IDurableResource extends Pick<IDurableService, "startExecution" | "cancelExecution" | "wait" | "execute" | "executeStrict" | "schedule" | "ensureSchedule" | "pauseSchedule" | "resumeSchedule" | "getSchedule" | "listSchedules" | "updateSchedule" | "removeSchedule" | "recover" | "signal"> {
3606
+ /**
3607
+ * Reads the durable context for the currently running workflow execution.
3608
+ * Throws if called outside of a durable execution.
3609
+ */
3610
+ use(): IDurableContext;
3611
+ }
3612
+ /**
3613
+ * A Runner-facing wrapper around `DurableService` that exposes a per-instance
3614
+ * context store and the public durable API (`execute`, `signal`, `wait`, etc.).
3615
+ *
3616
+ * This enables tasks to depend on a specific durable instance and call
3617
+ * `durable.use()` to access the per-execution durable context.
3618
+ */
3619
+ declare class DurableResource$1 implements IDurableResource {
3620
+ readonly service: IDurableService;
3621
+ private readonly contextStorage;
3622
+ constructor(service: IDurableService, contextStorage: AsyncLocalStorage<IDurableContext>);
3623
+ use(): IDurableContext;
3624
+ startExecution<TInput>(task: DurableTask<TInput, unknown>, input?: TInput, options?: ExecuteOptions): Promise<string>;
3625
+ cancelExecution(executionId: string, reason?: string): Promise<void>;
3626
+ wait<TResult>(executionId: string, options?: {
3627
+ timeout?: number;
3628
+ waitPollIntervalMs?: number;
3629
+ }): Promise<TResult>;
3630
+ execute<TInput, TResult>(task: DurableTask<TInput, TResult>, input?: TInput, options?: ExecuteOptions): Promise<TResult>;
3631
+ executeStrict<TInput, TResult>(task: undefined extends TResult ? never : DurableTask<TInput, TResult>, input?: TInput, options?: ExecuteOptions): Promise<TResult>;
3632
+ schedule<TInput>(task: DurableTask<TInput, unknown>, input: TInput | undefined, options: ScheduleOptions): Promise<string>;
3633
+ ensureSchedule<TInput>(task: DurableTask<TInput, unknown>, input: TInput | undefined, options: ScheduleOptions & {
3634
+ id: string;
3635
+ }): Promise<string>;
3636
+ pauseSchedule(scheduleId: string): Promise<void>;
3637
+ resumeSchedule(scheduleId: string): Promise<void>;
3638
+ getSchedule(scheduleId: string): Promise<Schedule | null>;
3639
+ listSchedules(): Promise<Schedule[]>;
3640
+ updateSchedule(scheduleId: string, updates: {
3641
+ cron?: string;
3642
+ interval?: number;
3643
+ input?: unknown;
3644
+ }): Promise<void>;
3645
+ removeSchedule(scheduleId: string): Promise<void>;
3646
+ recover(): Promise<void>;
3647
+ signal<TPayload>(executionId: string, signal: IEventDefinition<TPayload>, payload: TPayload): Promise<void>;
3648
+ }
3649
+
3650
+ declare const durableEvents: {
3651
+ readonly audit: {
3652
+ readonly appended: IEvent<{
3653
+ entry: DurableAuditEntry;
3654
+ }>;
3655
+ };
3656
+ readonly execution: {
3657
+ readonly statusChanged: IEvent<DurableAuditEntryBase & {
3658
+ kind: typeof DurableAuditEntryKind.ExecutionStatusChanged;
3659
+ from: ExecutionStatus | null;
3660
+ to: ExecutionStatus;
3661
+ reason?: string;
3662
+ }>;
3663
+ };
3664
+ readonly step: {
3665
+ readonly completed: IEvent<DurableAuditEntryBase & {
3666
+ kind: typeof DurableAuditEntryKind.StepCompleted;
3667
+ stepId: string;
3668
+ durationMs: number;
3669
+ isInternal: boolean;
3670
+ }>;
3671
+ };
3672
+ readonly sleep: {
3673
+ readonly scheduled: IEvent<DurableAuditEntryBase & {
3674
+ kind: typeof DurableAuditEntryKind.SleepScheduled;
3675
+ stepId: string;
3676
+ timerId: string;
3677
+ durationMs: number;
3678
+ fireAt: Date;
3679
+ }>;
3680
+ readonly completed: IEvent<DurableAuditEntryBase & {
3681
+ kind: typeof DurableAuditEntryKind.SleepCompleted;
3682
+ stepId: string;
3683
+ timerId: string;
3684
+ }>;
3685
+ };
3686
+ readonly signal: {
3687
+ readonly waiting: IEvent<DurableAuditEntryBase & {
3688
+ kind: typeof DurableAuditEntryKind.SignalWaiting;
3689
+ stepId: string;
3690
+ signalId: string;
3691
+ timeoutMs?: number;
3692
+ timeoutAtMs?: number;
3693
+ timerId?: string;
3694
+ reason?: "initial" | "timeout_armed";
3695
+ }>;
3696
+ readonly delivered: IEvent<DurableAuditEntryBase & {
3697
+ kind: typeof DurableAuditEntryKind.SignalDelivered;
3698
+ stepId: string;
3699
+ signalId: string;
3700
+ }>;
3701
+ readonly timedOut: IEvent<DurableAuditEntryBase & {
3702
+ kind: typeof DurableAuditEntryKind.SignalTimedOut;
3703
+ stepId: string;
3704
+ signalId: string;
3705
+ timerId: string;
3706
+ }>;
3707
+ };
3708
+ readonly emit: {
3709
+ readonly published: IEvent<DurableAuditEntryBase & {
3710
+ kind: typeof DurableAuditEntryKind.EmitPublished;
3711
+ stepId: string;
3712
+ eventId: string;
3713
+ }>;
3714
+ };
3715
+ readonly note: {
3716
+ readonly created: IEvent<DurableAuditEntryBase & {
3717
+ kind: typeof DurableAuditEntryKind.Note;
3718
+ message: string;
3719
+ meta?: Record<string, unknown>;
3720
+ }>;
3721
+ };
3722
+ };
3723
+ declare const durableEventsArray: IEvent<any>[];
3724
+
3725
+ declare function createDurableRunnerAuditEmitter(params: {
3726
+ eventManager: EventManager;
3727
+ source?: string;
3728
+ }): DurableAuditEmitter;
3729
+
3730
+ declare class NoopEventBus implements IEventBus {
3731
+ publish(_channel: string, _event: BusEvent): Promise<void>;
3732
+ subscribe(_channel: string, _handler: BusEventHandler): Promise<void>;
3733
+ unsubscribe(_channel: string): Promise<void>;
3734
+ }
3735
+
3736
+ /**
3737
+ * In-memory durable task registry.
3738
+ *
3739
+ * Durable executions persist only a `taskId` in the store, so the runtime needs a way
3740
+ * to resolve `taskId -> DurableTask` when resuming. This registry holds tasks that
3741
+ * were registered on the current process and optionally delegates to an external
3742
+ * resolver for tasks defined elsewhere (useful for modular apps).
3743
+ */
3744
+ declare class TaskRegistry {
3745
+ private readonly externalResolver?;
3746
+ private readonly tasks;
3747
+ constructor(externalResolver?: ((taskId: string) => DurableTask<any, any> | undefined) | undefined);
3748
+ register<TInput, TResult>(task: DurableTask<TInput, TResult>): void;
3749
+ find(taskId: string): DurableTask<any, any> | undefined;
3750
+ }
3751
+
3752
+ interface AuditConfig {
3753
+ /**
3754
+ * When enabled, attempts to persist audit entries to the store (if supported).
3755
+ * This is separate from event emission via `emitter`.
3756
+ */
3757
+ enabled?: boolean;
3758
+ /**
3759
+ * Optional emitter for streaming audit entries (e.g. Runner events, logging, mirroring).
3760
+ * Emissions must be best-effort and never affect workflow correctness.
3761
+ */
3762
+ emitter?: DurableAuditEmitter;
3763
+ }
3764
+ /**
3765
+ * Durable audit trail sink.
3766
+ *
3767
+ * Used across the durable subsystem (service/managers/context) to record lifecycle
3768
+ * events in a best-effort way. Persistence and emission are explicitly non-critical:
3769
+ * failures must never affect workflow correctness (the store remains the source of truth).
3770
+ */
3771
+ declare class AuditLogger {
3772
+ private readonly config;
3773
+ private readonly store;
3774
+ constructor(config: AuditConfig, store: IDurableStore);
3775
+ log(params: DurableAuditEntryInput & {
3776
+ at?: Date;
3777
+ }): Promise<void>;
3778
+ }
3779
+
3780
+ interface WaitConfig {
3781
+ defaultTimeout?: number;
3782
+ defaultPollIntervalMs?: number;
3783
+ }
3784
+ /**
3785
+ * Waits for an execution to reach a terminal state and returns/throws accordingly.
3786
+ *
3787
+ * Strategy:
3788
+ * - if an event bus is configured, subscribe to `execution:<executionId>` for low-latency completion
3789
+ * - otherwise (or on bus issues) fall back to polling the store
3790
+ *
3791
+ * The durable store remains the source of truth; this manager is purely a convenience layer
3792
+ * for callers that want `await durable.wait(...)` / `await durable.execute(...)`.
3793
+ */
3794
+ declare class WaitManager {
3795
+ private readonly store;
3796
+ private readonly eventBus?;
3797
+ private readonly config?;
3798
+ constructor(store: IDurableStore, eventBus?: IEventBus | undefined, config?: WaitConfig | undefined);
3799
+ waitForResult<TResult>(executionId: string, options?: {
3800
+ timeout?: number;
3801
+ waitPollIntervalMs?: number;
3802
+ }): Promise<TResult>;
3803
+ }
3804
+
3805
+ /**
3806
+ * Creates and maintains durable schedules.
3807
+ *
3808
+ * A schedule is persisted in the store and translated into durable timers that
3809
+ * `PollingManager` will later process to kick off executions. This keeps scheduling
3810
+ * crash-safe and horizontally scalable: schedules aren't owned by in-memory timers.
3811
+ */
3812
+ declare class ScheduleManager {
3813
+ private readonly store;
3814
+ private readonly taskRegistry;
3815
+ constructor(store: IDurableStore, taskRegistry: TaskRegistry);
3816
+ ensureSchedule<TInput>(task: DurableTask<TInput, unknown>, input: TInput | undefined, options: ScheduleOptions & {
3817
+ id: string;
3818
+ }): Promise<string>;
3819
+ schedule<TInput>(task: DurableTask<TInput, unknown>, input: TInput | undefined, options: ScheduleOptions): Promise<string>;
3820
+ reschedule(schedule: Schedule, options?: {
3821
+ lastRunAt?: Date;
3822
+ }): Promise<void>;
3823
+ pause(id: string): Promise<void>;
3824
+ resume(id: string): Promise<void>;
3825
+ get(id: string): Promise<Schedule | null>;
3826
+ list(): Promise<Schedule[]>;
3827
+ update(id: string, updates: {
3828
+ cron?: string;
3829
+ interval?: number;
3830
+ input?: unknown;
3831
+ }): Promise<void>;
3832
+ remove(id: string): Promise<void>;
3833
+ }
3834
+
3835
+ interface ExecutionManagerConfig {
3836
+ store: IDurableStore;
3837
+ queue?: IDurableQueue;
3838
+ eventBus?: IEventBus;
3839
+ taskExecutor?: ITaskExecutor;
3840
+ contextProvider?: DurableServiceConfig["contextProvider"];
3841
+ audit?: DurableServiceConfig["audit"];
3842
+ determinism?: DurableServiceConfig["determinism"];
3843
+ execution?: {
3844
+ maxAttempts?: number;
3845
+ timeout?: number;
3846
+ kickoffFailsafeDelayMs?: number;
3847
+ };
3848
+ }
3849
+ /**
3850
+ * Runs durable executions (the "workflow engine" for attempts).
3851
+ *
3852
+ * Responsibilities:
3853
+ * - persist new executions (including optional idempotency keys)
3854
+ * - enqueue work (queue mode) or run directly (embedded mode)
3855
+ * - execute a workflow attempt via `taskExecutor.run(...)`
3856
+ * - inject a per-attempt `DurableContext` (via `contextProvider` / ALS wrapper)
3857
+ * - interpret `SuspensionSignal` as "pause + reschedule" rather than failure
3858
+ * - update execution status/result/error and notify waiters (`WaitManager`)
3859
+ */
3860
+ declare class ExecutionManager {
3861
+ private readonly config;
3862
+ private readonly taskRegistry;
3863
+ private readonly auditLogger;
3864
+ private readonly waitManager;
3865
+ constructor(config: ExecutionManagerConfig, taskRegistry: TaskRegistry, auditLogger: AuditLogger, waitManager: WaitManager);
3866
+ startExecution<TInput>(task: DurableTask<TInput, unknown>, input?: TInput, options?: ExecuteOptions): Promise<string>;
3867
+ cancelExecution(executionId: string, reason?: string): Promise<void>;
3868
+ execute<TInput, TResult>(task: DurableTask<TInput, TResult>, input?: TInput, options?: ExecuteOptions): Promise<TResult>;
3869
+ executeStrict<TInput, TResult>(task: undefined extends TResult ? never : DurableTask<TInput, TResult>, input?: TInput, options?: ExecuteOptions): Promise<TResult>;
3870
+ processExecution(executionId: string): Promise<void>;
3871
+ kickoffExecution(executionId: string): Promise<void>;
3872
+ notifyExecutionFinished(execution: Execution): Promise<void>;
3873
+ private runExecutionAttempt;
3874
+ }
3875
+
3876
+ interface PollingConfig {
3877
+ enabled?: boolean;
3878
+ interval?: number;
3879
+ claimTtlMs?: number;
3880
+ }
3881
+ interface PollingManagerCallbacks {
3882
+ processExecution: (executionId: string) => Promise<void>;
3883
+ kickoffExecution: (executionId: string) => Promise<void>;
3884
+ }
3885
+ /**
3886
+ * Timer/tick driver for durable workflows.
3887
+ *
3888
+ * The durable store is the source of truth, but time needs an active driver:
3889
+ * `PollingManager` periodically scans ready timers and performs the appropriate action:
3890
+ *
3891
+ * - complete `sleep()` steps by marking their step result as completed
3892
+ * - resume executions after signal timeouts / scheduled kickoffs / retries
3893
+ * - coordinate multi-worker polling via optional `store.claimTimer(...)`
3894
+ *
3895
+ * In production topologies you typically enable polling on worker nodes only.
3896
+ */
3897
+ declare class PollingManager {
3898
+ private readonly workerId;
3899
+ private readonly config;
3900
+ private readonly store;
3901
+ private readonly queue;
3902
+ private readonly maxAttempts;
3903
+ private readonly defaultTimeout;
3904
+ private readonly taskRegistry;
3905
+ private readonly auditLogger;
3906
+ private readonly scheduleManager;
3907
+ private readonly callbacks;
3908
+ private isRunning;
3909
+ private pollingTimer;
3910
+ private pollingWake;
3911
+ constructor(workerId: string, config: PollingConfig, store: IDurableStore, queue: IDurableQueue | undefined, maxAttempts: number, defaultTimeout: number | undefined, taskRegistry: TaskRegistry, auditLogger: AuditLogger, scheduleManager: ScheduleManager, callbacks: PollingManagerCallbacks);
3912
+ start(): void;
3913
+ stop(): Promise<void>;
3914
+ private poll;
3915
+ /** @internal - public for testing */
3916
+ handleTimer(timer: Timer): Promise<void>;
3917
+ }
3918
+
3919
+ /**
3920
+ * Error thrown to consumers waiting on an execution (`DurableService.wait/execute*`).
3921
+ *
3922
+ * Distinguishes durable execution failures/timeouts/cancellations from ordinary
3923
+ * task errors by carrying execution metadata and a (serialized) cause payload.
3924
+ * `WaitManager` is the primary producer of this error.
3925
+ */
3926
+ declare class DurableExecutionError extends Error {
3927
+ readonly executionId: string;
3928
+ readonly taskId: string;
3929
+ readonly attempt: number;
3930
+ readonly causeInfo?: {
3931
+ message: string;
3932
+ stack?: string;
3933
+ } | undefined;
3934
+ constructor(message: string, executionId: string, taskId: string, attempt: number, causeInfo?: {
3935
+ message: string;
3936
+ stack?: string;
3937
+ } | undefined);
3938
+ }
3939
+
3940
+ /**
3941
+ * High-level facade for the Durable Workflows subsystem.
3942
+ *
3943
+ * `DurableService` glues together the durable backends (store/queue/event bus) and
3944
+ * the specialized managers that implement durable semantics:
3945
+ *
3946
+ * - `ExecutionManager` runs workflow attempts and injects `DurableContext`
3947
+ * - `SignalHandler` delivers external signals to waiting steps
3948
+ * - `WaitManager` waits for results (event-bus first, polling fallback)
3949
+ * - `ScheduleManager` creates/updates schedules and their timers
3950
+ * - `PollingManager` drives timers (sleep, retries, signal timeouts, schedules)
3951
+ * - `AuditLogger` emits/persists an audit trail (best-effort)
3952
+ *
3953
+ * `DurableResource` wraps this service for Runner integration and provides
3954
+ * `durable.use()` to read the per-execution `DurableContext`.
3955
+ */
3956
+ declare class DurableService implements IDurableService {
3957
+ private readonly config;
3958
+ private readonly taskRegistry;
3959
+ private readonly auditLogger;
3960
+ private readonly waitManager;
3961
+ private readonly scheduleManager;
3962
+ private readonly signalHandler;
3963
+ private readonly executionManager;
3964
+ private readonly pollingManager;
3965
+ /** Unique worker ID for distributed timer coordination */
3966
+ private readonly workerId;
3967
+ constructor(config: DurableServiceConfig);
3968
+ registerTask<TInput, TResult>(task: DurableTask<TInput, TResult>): void;
3969
+ findTask(taskId: string): DurableTask<any, any> | undefined;
3970
+ startExecution<TInput>(task: DurableTask<TInput, unknown>, input?: TInput, options?: ExecuteOptions): Promise<string>;
3971
+ cancelExecution(executionId: string, reason?: string): Promise<void>;
3972
+ execute<TInput, TResult>(task: DurableTask<TInput, TResult>, input?: TInput, options?: ExecuteOptions): Promise<TResult>;
3973
+ executeStrict<TInput, TResult>(task: undefined extends TResult ? never : DurableTask<TInput, TResult>, input?: TInput, options?: ExecuteOptions): Promise<TResult>;
3974
+ wait<TResult>(executionId: string, options?: {
3975
+ timeout?: number;
3976
+ waitPollIntervalMs?: number;
3977
+ }): Promise<TResult>;
3978
+ schedule<TInput>(task: DurableTask<TInput, unknown>, input: TInput | undefined, options: ScheduleOptions): Promise<string>;
3979
+ ensureSchedule<TInput>(task: DurableTask<TInput, unknown>, input: TInput | undefined, options: ScheduleOptions & {
3980
+ id: string;
3981
+ }): Promise<string>;
3982
+ recover(): Promise<void>;
3983
+ start(): void;
3984
+ stop(): Promise<void>;
3985
+ pauseSchedule(id: string): Promise<void>;
3986
+ resumeSchedule(id: string): Promise<void>;
3987
+ getSchedule(id: string): Promise<Schedule | null>;
3988
+ listSchedules(): Promise<Schedule[]>;
3989
+ updateSchedule(id: string, updates: {
3990
+ cron?: string;
3991
+ interval?: number;
3992
+ input?: unknown;
3993
+ }): Promise<void>;
3994
+ removeSchedule(id: string): Promise<void>;
3995
+ signal<TPayload>(executionId: string, signal: IEventDefinition<TPayload>, payload: TPayload): Promise<void>;
3996
+ processExecution(executionId: string): Promise<void>;
3997
+ getEventBus(): NoopEventBus;
3998
+ /** @internal - exposed for unit testing */
3999
+ get _pollingManager(): PollingManager;
4000
+ /** @internal - exposed for unit testing */
4001
+ get _executionManager(): ExecutionManager;
4002
+ /** @internal - exposed for unit testing (delegates to pollingManager) */
4003
+ handleTimer(timer: Timer): Promise<void>;
4004
+ }
4005
+ declare function initDurableService(config: DurableServiceConfig): Promise<DurableService>;
4006
+ declare function disposeDurableService(service: IDurableService, config: DurableServiceConfig): Promise<void>;
4007
+
4008
+ type DurableResourceRuntimeConfig = Omit<DurableServiceConfig, "taskExecutor" | "tasks" | "taskResolver" | "contextProvider"> & {
4009
+ /**
4010
+ * Starts an embedded worker (queue consumer) in this process.
4011
+ * Has effect only when `queue` is configured.
4012
+ */
4013
+ worker?: boolean;
4014
+ };
4015
+ /**
4016
+ * A reusable durable resource template.
4017
+ *
4018
+ * Usage:
4019
+ * - `const durable = durableResource.fork("app.durable");`
4020
+ * - Register it via `durable.with({ store, queue, eventBus, ... })`
4021
+ */
4022
+ declare const durableResource: IResource<DurableResourceRuntimeConfig, Promise<DurableResource$1>, {
4023
+ taskRunner: IResource<void, Promise<TaskRunner>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
4024
+ eventManager: IResource<void, Promise<EventManager>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
4025
+ runnerStore: IResource<void, Promise<Store>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
4026
+ }, any, IResourceMeta, TagType[], ResourceMiddlewareAttachmentType[]>;
4027
+
4028
+ type ImplicitInternalStepIdsPolicy = "allow" | "warn" | "error";
4029
+
4030
+ /**
4031
+ * Per-execution workflow toolkit used by durable tasks.
4032
+ *
4033
+ * `DurableContext` is created by `ExecutionManager` for each execution attempt and
4034
+ * made available to user code via `DurableResource.use()` (AsyncLocalStorage).
4035
+ *
4036
+ * It provides deterministic "save points" (`step()`), durable suspension primitives
4037
+ * (`sleep()`, `waitForSignal()`), and best-effort side-channel notifications (`emit()`).
4038
+ * The durable store is the source of truth; this class is intentionally thin state
4039
+ * around indexes/guards to keep a single in-memory attempt deterministic.
4040
+ */
4041
+ declare class DurableContext implements IDurableContext {
4042
+ private readonly store;
4043
+ private readonly bus;
4044
+ readonly executionId: string;
4045
+ readonly attempt: number;
4046
+ private readonly sleepIndexRef;
4047
+ private readonly signalIndexes;
4048
+ private readonly emitIndexes;
4049
+ private noteIndex;
4050
+ private readonly implicitInternalStepIdsWarned;
4051
+ private readonly seenStepIds;
4052
+ private readonly compensations;
4053
+ private readonly audit;
4054
+ private readonly determinism;
4055
+ private readonly auditEnabled;
4056
+ private readonly auditEmitter;
4057
+ private readonly implicitInternalStepIdsPolicy;
4058
+ constructor(store: IDurableStore, bus: IEventBus, executionId: string, attempt: number, options?: {
4059
+ auditEnabled?: boolean;
4060
+ auditEmitter?: DurableAuditEmitter;
4061
+ implicitInternalStepIds?: ImplicitInternalStepIdsPolicy;
4062
+ });
4063
+ private assertNotCancelled;
4064
+ private getStepId;
4065
+ private internalStep;
4066
+ step<T>(stepId: string): IStepBuilder<T>;
4067
+ step<T>(stepId: DurableStepId<T>): IStepBuilder<T>;
4068
+ step<T>(stepId: string | DurableStepId<T>, fn: () => Promise<T>): Promise<T>;
4069
+ step<T>(stepId: string | DurableStepId<T>, options: StepOptions, fn: () => Promise<T>): Promise<T>;
4070
+ _executeStep<T>(stepId: string, options: StepOptions, upFn: () => Promise<T>, downFn?: (result: T) => Promise<void>): Promise<T>;
4071
+ rollback(): Promise<void>;
4072
+ sleep(durationMs: number, options?: SleepOptions): Promise<void>;
4073
+ waitForSignal<TPayload>(signal: IEventDefinition<TPayload>): Promise<TPayload>;
4074
+ waitForSignal<TPayload>(signal: IEventDefinition<TPayload>, options: SignalOptions & {
4075
+ timeoutMs: number;
4076
+ }): Promise<{
4077
+ kind: "signal";
4078
+ payload: TPayload;
4079
+ } | {
4080
+ kind: "timeout";
4081
+ }>;
4082
+ waitForSignal<TPayload>(signal: IEventDefinition<TPayload>, options: SignalOptions): Promise<TPayload>;
4083
+ emit<TPayload>(event: IEventDefinition<TPayload>, payload: TPayload, options?: EmitOptions): Promise<void>;
4084
+ note(message: string, meta?: Record<string, unknown>): Promise<void>;
4085
+ }
4086
+
4087
+ /**
4088
+ * Fluent helper for building a durable step.
4089
+ *
4090
+ * This is the ergonomic layer behind `ctx.step("id")`:
4091
+ * - `up()` defines the memoized computation
4092
+ * - `down()` registers a compensation to be invoked by `ctx.rollback()`
4093
+ *
4094
+ * It is `PromiseLike`, so users can `await ctx.step("x").up(...).down(...)`.
4095
+ */
4096
+ declare class StepBuilder<T> implements IStepBuilder<T> {
4097
+ private readonly context;
4098
+ private readonly stepId;
4099
+ private readonly options;
4100
+ private upFn?;
4101
+ private downFn?;
4102
+ constructor(context: DurableContext, stepId: string, options?: StepOptions);
4103
+ up(fn: () => Promise<T>): this;
4104
+ down(fn: (result: T) => Promise<void>): this;
4105
+ private execute;
4106
+ then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
4107
+ }
4108
+
4109
+ /**
4110
+ * Administrative / operator API for durable workflows.
4111
+ *
4112
+ * This class is intentionally store-backed and side-effect free with respect to
4113
+ * "running" workflows: it reads execution details and, when supported by the store,
4114
+ * can perform operator actions (retry rollback, skip a step, force fail, patch state).
4115
+ *
4116
+ * Used by dashboards / CLIs / tooling to inspect and recover executions.
4117
+ */
4118
+ declare class DurableOperator {
4119
+ private readonly store;
4120
+ constructor(store: IDurableStore);
4121
+ listExecutions(options?: ListExecutionsOptions): Promise<Execution[]>;
4122
+ getExecutionDetail(executionId: string): Promise<{
4123
+ execution: Execution | null;
4124
+ steps: StepResult[];
4125
+ audit: DurableAuditEntry[];
4126
+ }>;
4127
+ /**
4128
+ * Resets an execution from `compensation_failed` (or other states) to `pending`.
4129
+ * This effectively retries the workflow from the last memoized step.
4130
+ */
4131
+ retryRollback(executionId: string): Promise<void>;
4132
+ /**
4133
+ * Manually marks a step as completed with a specific result.
4134
+ * Useful for skipping broken steps or providing a manual fix.
4135
+ */
4136
+ skipStep(executionId: string, stepId: string): Promise<void>;
4137
+ /**
4138
+ * Forces an execution to the `failed` state.
4139
+ */
4140
+ forceFail(executionId: string, reason: string): Promise<void>;
4141
+ /**
4142
+ * Manually patches the result of a step.
4143
+ * Useful when a step failed to save its result but the side effect occurred.
4144
+ */
4145
+ editState(executionId: string, stepId: string, newState: unknown): Promise<void>;
4146
+ /**
4147
+ * Lists all executions that require manual intervention.
4148
+ */
4149
+ listStuckExecutions(): Promise<Execution[]>;
4150
+ }
4151
+
4152
+ /**
4153
+ * Durable queue consumer (worker process role).
4154
+ *
4155
+ * The worker listens to the durable queue and turns queue messages into
4156
+ * `processExecution(executionId)` calls on the service layer (`ExecutionManager`
4157
+ * behind `IDurableExecutionProcessor`). This is how "resume" work is distributed
4158
+ * horizontally: the store is the source of truth, the queue provides delivery.
4159
+ */
4160
+ declare class DurableWorker {
4161
+ private readonly service;
4162
+ private readonly queue;
4163
+ constructor(service: IDurableExecutionProcessor, queue: IDurableQueue);
4164
+ start(): Promise<void>;
4165
+ private handleMessage;
4166
+ private extractExecutionId;
4167
+ }
4168
+ declare function initDurableWorker(service: IDurableExecutionProcessor, queue: IDurableQueue): Promise<DurableWorker>;
4169
+
4170
+ type DashboardMiddlewareOptions = {
4171
+ /**
4172
+ * Override where the dashboard UI is served from.
4173
+ * Useful for tests or custom deployments.
4174
+ */
4175
+ uiDistPath?: string;
4176
+ /**
4177
+ * Authorization hook for operator actions (retry/skip/force/edit).
4178
+ * Return true to allow, false to deny.
4179
+ */
4180
+ operatorAuth?: (req: Request) => boolean | Promise<boolean>;
4181
+ /**
4182
+ * Opt out of operator auth checks (not recommended).
4183
+ */
4184
+ dangerouslyAllowUnauthenticatedOperator?: boolean;
4185
+ };
4186
+ declare function createDashboardMiddleware(_service: IDurableService, operator: DurableOperator, options?: DashboardMiddlewareOptions): Router;
4187
+
4188
+ declare class MemoryStore implements IDurableStore {
4189
+ private executions;
4190
+ private executionIdByIdempotencyKey;
4191
+ private stepResults;
4192
+ private auditEntries;
4193
+ private timers;
4194
+ private schedules;
4195
+ private locks;
4196
+ private getIdempotencyMapKey;
4197
+ getExecutionIdByIdempotencyKey(params: {
4198
+ taskId: string;
4199
+ idempotencyKey: string;
4200
+ }): Promise<string | null>;
4201
+ setExecutionIdByIdempotencyKey(params: {
4202
+ taskId: string;
4203
+ idempotencyKey: string;
4204
+ executionId: string;
4205
+ }): Promise<boolean>;
4206
+ saveExecution(execution: Execution): Promise<void>;
4207
+ getExecution(id: string): Promise<Execution | null>;
4208
+ updateExecution(id: string, updates: Partial<Execution>): Promise<void>;
4209
+ listIncompleteExecutions(): Promise<Execution[]>;
4210
+ listStuckExecutions(): Promise<Execution[]>;
4211
+ listExecutions(options?: ListExecutionsOptions): Promise<Execution[]>;
4212
+ listStepResults(executionId: string): Promise<StepResult[]>;
4213
+ appendAuditEntry(entry: DurableAuditEntry): Promise<void>;
4214
+ listAuditEntries(executionId: string, options?: {
4215
+ limit?: number;
4216
+ offset?: number;
4217
+ }): Promise<DurableAuditEntry[]>;
4218
+ retryRollback(executionId: string): Promise<void>;
4219
+ skipStep(executionId: string, stepId: string): Promise<void>;
4220
+ forceFail(executionId: string, error: {
4221
+ message: string;
4222
+ stack?: string;
4223
+ }): Promise<void>;
4224
+ editStepResult(executionId: string, stepId: string, newResult: unknown): Promise<void>;
4225
+ getStepResult(executionId: string, stepId: string): Promise<StepResult | null>;
4226
+ saveStepResult(result: StepResult): Promise<void>;
4227
+ createTimer(timer: Timer): Promise<void>;
4228
+ getReadyTimers(now?: Date): Promise<Timer[]>;
4229
+ markTimerFired(timerId: string): Promise<void>;
4230
+ deleteTimer(timerId: string): Promise<void>;
4231
+ claimTimer(timerId: string, workerId: string, ttlMs: number): Promise<boolean>;
4232
+ createSchedule(schedule: Schedule): Promise<void>;
4233
+ getSchedule(id: string): Promise<Schedule | null>;
4234
+ updateSchedule(id: string, updates: Partial<Schedule>): Promise<void>;
4235
+ deleteSchedule(id: string): Promise<void>;
4236
+ listSchedules(): Promise<Schedule[]>;
4237
+ listActiveSchedules(): Promise<Schedule[]>;
4238
+ acquireLock(resource: string, ttlMs: number): Promise<string | null>;
4239
+ releaseLock(resource: string, lockId: string): Promise<void>;
4240
+ }
4241
+
4242
+ interface RedisPipeline {
4243
+ get(key: string): RedisPipeline;
4244
+ hget(hash: string, key: string): RedisPipeline;
4245
+ exec(): Promise<Array<[unknown, unknown]> | null>;
4246
+ }
4247
+ interface RedisClient {
4248
+ set(...args: unknown[]): Promise<unknown>;
4249
+ get(...args: unknown[]): Promise<unknown>;
4250
+ scan(...args: unknown[]): Promise<unknown>;
4251
+ sscan(...args: unknown[]): Promise<unknown>;
4252
+ sadd(...args: unknown[]): Promise<unknown>;
4253
+ srem(...args: unknown[]): Promise<unknown>;
4254
+ keys?(...args: unknown[]): Promise<unknown>;
4255
+ pipeline(): RedisPipeline;
4256
+ hset(...args: unknown[]): Promise<unknown>;
4257
+ hget(...args: unknown[]): Promise<unknown>;
4258
+ hdel(...args: unknown[]): Promise<unknown>;
4259
+ hgetall(...args: unknown[]): Promise<unknown>;
4260
+ zadd(...args: unknown[]): Promise<unknown>;
4261
+ zrangebyscore(...args: unknown[]): Promise<unknown>;
4262
+ zrem(...args: unknown[]): Promise<unknown>;
4263
+ eval(...args: unknown[]): Promise<unknown>;
4264
+ quit(...args: unknown[]): Promise<unknown>;
4265
+ }
4266
+ interface RedisStoreConfig {
4267
+ prefix?: string;
4268
+ redis?: RedisClient | string;
4269
+ }
4270
+ declare class RedisStore implements IDurableStore {
4271
+ private redis;
4272
+ private prefix;
4273
+ constructor(config: RedisStoreConfig);
4274
+ private k;
4275
+ private encodeKeyPart;
4276
+ getExecutionIdByIdempotencyKey(params: {
4277
+ taskId: string;
4278
+ idempotencyKey: string;
4279
+ }): Promise<string | null>;
4280
+ setExecutionIdByIdempotencyKey(params: {
4281
+ taskId: string;
4282
+ idempotencyKey: string;
4283
+ executionId: string;
4284
+ }): Promise<boolean>;
4285
+ private parseRedisString;
4286
+ private parseScanResponse;
4287
+ private scanKeys;
4288
+ private scanSetMembers;
4289
+ private activeExecutionsKey;
4290
+ private isActiveExecutionStatus;
4291
+ private updateActiveExecutionMembership;
4292
+ saveExecution(execution: Execution): Promise<void>;
4293
+ getExecution(id: string): Promise<Execution | null>;
4294
+ updateExecution(id: string, updates: Partial<Execution>): Promise<void>;
4295
+ listIncompleteExecutions(): Promise<Execution[]>;
4296
+ listStuckExecutions(): Promise<Execution[]>;
4297
+ retryRollback(executionId: string): Promise<void>;
4298
+ skipStep(executionId: string, stepId: string): Promise<void>;
4299
+ forceFail(executionId: string, error: {
4300
+ message: string;
4301
+ stack?: string;
4302
+ }): Promise<void>;
4303
+ editStepResult(executionId: string, stepId: string, newResult: unknown): Promise<void>;
4304
+ listExecutions(options?: ListExecutionsOptions): Promise<Execution[]>;
4305
+ listStepResults(executionId: string): Promise<StepResult[]>;
4306
+ appendAuditEntry(entry: DurableAuditEntry): Promise<void>;
4307
+ listAuditEntries(executionId: string, options?: {
4308
+ limit?: number;
4309
+ offset?: number;
4310
+ }): Promise<DurableAuditEntry[]>;
4311
+ getStepResult(executionId: string, stepId: string): Promise<StepResult | null>;
4312
+ saveStepResult(result: StepResult): Promise<void>;
4313
+ createTimer(timer: Timer): Promise<void>;
4314
+ getReadyTimers(now?: Date): Promise<Timer[]>;
4315
+ markTimerFired(timerId: string): Promise<void>;
4316
+ deleteTimer(timerId: string): Promise<void>;
4317
+ claimTimer(timerId: string, workerId: string, ttlMs: number): Promise<boolean>;
4318
+ createSchedule(schedule: Schedule): Promise<void>;
4319
+ getSchedule(id: string): Promise<Schedule | null>;
4320
+ updateSchedule(id: string, updates: Partial<Schedule>): Promise<void>;
4321
+ deleteSchedule(id: string): Promise<void>;
4322
+ listSchedules(): Promise<Schedule[]>;
4323
+ listActiveSchedules(): Promise<Schedule[]>;
4324
+ acquireLock(resource: string, ttlMs: number): Promise<string | null>;
4325
+ releaseLock(resource: string, lockId: string): Promise<void>;
4326
+ dispose(): Promise<void>;
4327
+ }
4328
+
4329
+ declare class MemoryQueue implements IDurableQueue {
4330
+ private queue;
4331
+ private handler;
4332
+ private isProcessing;
4333
+ private readonly inFlight;
4334
+ enqueue<T>(message: Omit<QueueMessage<T>, "id" | "createdAt" | "attempts">): Promise<string>;
4335
+ consume<T>(handler: MessageHandler<T>): Promise<void>;
4336
+ ack(_messageId: string): Promise<void>;
4337
+ nack(_messageId: string, _requeue?: boolean): Promise<void>;
4338
+ private processNext;
4339
+ }
4340
+
4341
+ interface RabbitMQQueueConfig {
4342
+ url?: string;
4343
+ queueName?: string;
4344
+ queue?: {
4345
+ name?: string;
4346
+ quorum?: boolean;
4347
+ deadLetter?: string;
4348
+ messageTtl?: number;
4349
+ };
4350
+ prefetch?: number;
4351
+ }
4352
+ declare class RabbitMQQueue implements IDurableQueue {
4353
+ private connection;
4354
+ private channel;
4355
+ private url;
4356
+ private queueName;
4357
+ private prefetch;
4358
+ private readonly isQuorum;
4359
+ private readonly deadLetterQueue?;
4360
+ private readonly messageTtl?;
4361
+ private messageMap;
4362
+ constructor(config: RabbitMQQueueConfig);
4363
+ init(): Promise<void>;
4364
+ enqueue<T>(message: Omit<QueueMessage<T>, "id" | "createdAt" | "attempts">): Promise<string>;
4365
+ consume<T>(handler: MessageHandler<T>): Promise<void>;
4366
+ ack(messageId: string): Promise<void>;
4367
+ nack(messageId: string, requeue?: boolean): Promise<void>;
4368
+ dispose(): Promise<void>;
4369
+ }
4370
+
4371
+ declare class MemoryEventBus implements IEventBus {
4372
+ private handlers;
4373
+ publish(channel: string, event: BusEvent): Promise<void>;
4374
+ subscribe(channel: string, handler: BusEventHandler): Promise<void>;
4375
+ unsubscribe(channel: string): Promise<void>;
4376
+ }
4377
+
4378
+ interface RedisEventBusConfig {
4379
+ prefix?: string;
4380
+ redis?: RedisEventBusClient | string;
4381
+ }
4382
+ interface RedisEventBusClient {
4383
+ publish(channel: string, payload: string): Promise<unknown>;
4384
+ subscribe(channel: string): Promise<unknown>;
4385
+ unsubscribe(channel: string): Promise<unknown>;
4386
+ on(event: "message", fn: (channel: string, message: string) => void): unknown;
4387
+ quit(): Promise<unknown>;
4388
+ duplicate(): RedisEventBusClient;
4389
+ }
4390
+ declare class RedisEventBus implements IEventBus {
4391
+ private pub;
4392
+ private sub;
4393
+ private prefix;
4394
+ private readonly channels;
4395
+ private readonly serializer;
4396
+ constructor(config: RedisEventBusConfig);
4397
+ private k;
4398
+ private tryParse;
4399
+ private coerceTimestamp;
4400
+ private toBusEvent;
4401
+ private deserializeEvent;
4402
+ publish(channel: string, event: BusEvent): Promise<void>;
4403
+ subscribe(channel: string, handler: BusEventHandler): Promise<void>;
4404
+ unsubscribe(channel: string): Promise<void>;
4405
+ dispose(): Promise<void>;
4406
+ }
4407
+
4408
+ type DurableResource = ReturnType<typeof durableResource.fork>;
4409
+ type DurableResourceRegistration = ReturnType<DurableResource["with"]>;
4410
+ interface DurableTestSetup {
4411
+ durable: DurableResource;
4412
+ durableRegistration: DurableResourceRegistration;
4413
+ store: MemoryStore;
4414
+ eventBus: MemoryEventBus;
4415
+ queue?: MemoryQueue;
4416
+ }
4417
+ interface DurableTestSetupOptions {
4418
+ durableId?: string;
4419
+ store?: MemoryStore;
4420
+ eventBus?: MemoryEventBus;
4421
+ queue?: MemoryQueue;
4422
+ worker?: boolean;
4423
+ pollingIntervalMs?: number;
4424
+ durableConfig?: Partial<DurableResourceRuntimeConfig>;
4425
+ }
4426
+ declare function createDurableTestSetup(options?: DurableTestSetupOptions): DurableTestSetup;
4427
+ declare function waitUntil(predicate: () => boolean | Promise<boolean>, options: {
4428
+ timeoutMs: number;
4429
+ intervalMs: number;
4430
+ }): Promise<void>;
4431
+
2381
4432
  declare const globals: {
2382
4433
  resources: {
2383
4434
  httpSmartClientFactory: IResource<void, Promise<HttpSmartClientFactory>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
@@ -2387,15 +4438,15 @@ declare const globals: {
2387
4438
  eventManager: IResource<void, Promise<EventManager>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2388
4439
  taskRunner: IResource<void, Promise<TaskRunner>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2389
4440
  logger: IResource<void, Promise<Logger>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2390
- serializer: IResource<void, Promise<Serializer>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
4441
+ serializer: IResource<void, Promise<SerializerLike>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2391
4442
  cache: IResource<{
2392
4443
  defaultOptions?: any;
2393
4444
  }, Promise<{
2394
4445
  map: Map<string, ICacheInstance>;
2395
- cacheFactoryTask: TaskDependencyWithIntercept<any, Promise<ICacheInstance>>;
4446
+ cacheFactoryTask: TaskDependencyWithIntercept<lru_cache.LRUCache.Options<any, any, any>, Promise<ICacheInstance>>;
2396
4447
  defaultOptions: any;
2397
4448
  }>, {
2398
- cacheFactoryTask: ITask<any, Promise<ICacheInstance>, any, any, TagType[], TaskMiddlewareAttachmentType[]>;
4449
+ cacheFactoryTask: ITask<lru_cache.LRUCache.Options<any, any, any>, Promise<ICacheInstance>, any, any, TagType[], TaskMiddlewareAttachmentType[]>;
2399
4450
  }, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2400
4451
  queue: IResource<void, Promise<{
2401
4452
  map: Map<string, Queue>;
@@ -2407,12 +4458,37 @@ declare const globals: {
2407
4458
  description: string;
2408
4459
  }, TagType[], ResourceMiddlewareAttachmentType[]>;
2409
4460
  httpClientFactory: IResource<void, Promise<HttpClientFactory>, {
2410
- serializer: IResource<void, Promise<Serializer>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
4461
+ serializer: IResource<void, Promise<SerializerLike>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2411
4462
  store: IResource<void, Promise<Store>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2412
4463
  }, any, {
2413
4464
  title: string;
2414
4465
  description: string;
2415
4466
  }, TagType[], ResourceMiddlewareAttachmentType[]>;
4467
+ rateLimit: IResource<void, Promise<{
4468
+ states: WeakMap<RateLimitMiddlewareConfig, RateLimitState>;
4469
+ }>, {}, any, any, ITag<{
4470
+ metadata?: Record<string, any>;
4471
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
4472
+ circuitBreaker: IResource<void, Promise<{
4473
+ statusMap: Map<string, CircuitBreakerStatus>;
4474
+ }>, {}, any, any, ITag<{
4475
+ metadata?: Record<string, any>;
4476
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
4477
+ temporal: IResource<void, Promise<{
4478
+ debounceStates: WeakMap<TemporalMiddlewareConfig, DebounceState>;
4479
+ throttleStates: WeakMap<TemporalMiddlewareConfig, ThrottleState>;
4480
+ }>, {}, any, any, ITag<{
4481
+ metadata?: Record<string, any>;
4482
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
4483
+ concurrency: IResource<void, Promise<{
4484
+ semaphoresByConfig: WeakMap<ConcurrencyMiddlewareConfig, Semaphore>;
4485
+ semaphoresByKey: Map<string, {
4486
+ semaphore: Semaphore;
4487
+ limit: number;
4488
+ }>;
4489
+ }>, {}, any, any, ITag<{
4490
+ metadata?: Record<string, any>;
4491
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2416
4492
  };
2417
4493
  events: {
2418
4494
  readonly ready: IEvent<void>;
@@ -2430,14 +4506,87 @@ declare const globals: {
2430
4506
  defaultOptions?: any;
2431
4507
  }, Promise<{
2432
4508
  map: Map<string, ICacheInstance>;
2433
- cacheFactoryTask: TaskDependencyWithIntercept<any, Promise<ICacheInstance>>;
4509
+ cacheFactoryTask: TaskDependencyWithIntercept<lru_cache.LRUCache.Options<any, any, any>, Promise<ICacheInstance>>;
2434
4510
  defaultOptions: any;
2435
4511
  }>, {
2436
- cacheFactoryTask: ITask<any, Promise<ICacheInstance>, any, any, TagType[], TaskMiddlewareAttachmentType[]>;
4512
+ cacheFactoryTask: ITask<lru_cache.LRUCache.Options<any, any, any>, Promise<ICacheInstance>, any, any, TagType[], TaskMiddlewareAttachmentType[]>;
2437
4513
  }, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
4514
+ }> & {
4515
+ journalKeys: {
4516
+ readonly hit: JournalKey<boolean>;
4517
+ };
4518
+ };
4519
+ concurrency: ITaskMiddleware<ConcurrencyMiddlewareConfig, void, void, {
4520
+ state: IResource<void, Promise<{
4521
+ semaphoresByConfig: WeakMap<ConcurrencyMiddlewareConfig, Semaphore>;
4522
+ semaphoresByKey: Map<string, {
4523
+ semaphore: Semaphore;
4524
+ limit: number;
4525
+ }>;
4526
+ }>, {}, any, any, ITag<{
4527
+ metadata?: Record<string, any>;
4528
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
4529
+ }>;
4530
+ debounce: ITaskMiddleware<TemporalMiddlewareConfig, void, void, {
4531
+ state: IResource<void, Promise<{
4532
+ debounceStates: WeakMap<TemporalMiddlewareConfig, DebounceState>;
4533
+ throttleStates: WeakMap<TemporalMiddlewareConfig, ThrottleState>;
4534
+ }>, {}, any, any, ITag<{
4535
+ metadata?: Record<string, any>;
4536
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
4537
+ }>;
4538
+ throttle: ITaskMiddleware<TemporalMiddlewareConfig, void, void, {
4539
+ state: IResource<void, Promise<{
4540
+ debounceStates: WeakMap<TemporalMiddlewareConfig, DebounceState>;
4541
+ throttleStates: WeakMap<TemporalMiddlewareConfig, ThrottleState>;
4542
+ }>, {}, any, any, ITag<{
4543
+ metadata?: Record<string, any>;
4544
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2438
4545
  }>;
2439
- retry: ITaskMiddleware<RetryMiddlewareConfig, void, void, any>;
2440
- timeout: ITaskMiddleware<TimeoutMiddlewareConfig, void, void, any>;
4546
+ fallback: ITaskMiddleware<FallbackMiddlewareConfig, void, void, {
4547
+ taskRunner: IResource<void, Promise<TaskRunner>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
4548
+ }> & {
4549
+ journalKeys: {
4550
+ readonly active: JournalKey<boolean>;
4551
+ readonly error: JournalKey<Error>;
4552
+ };
4553
+ };
4554
+ rateLimit: ITaskMiddleware<RateLimitMiddlewareConfig, void, void, {
4555
+ state: IResource<void, Promise<{
4556
+ states: WeakMap<RateLimitMiddlewareConfig, RateLimitState>;
4557
+ }>, {}, any, any, ITag<{
4558
+ metadata?: Record<string, any>;
4559
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
4560
+ }> & {
4561
+ journalKeys: {
4562
+ readonly remaining: JournalKey<number>;
4563
+ readonly resetTime: JournalKey<number>;
4564
+ readonly limit: JournalKey<number>;
4565
+ };
4566
+ };
4567
+ retry: ITaskMiddleware<RetryMiddlewareConfig, void, void, any> & {
4568
+ journalKeys: {
4569
+ readonly attempt: JournalKey<number>;
4570
+ readonly lastError: JournalKey<Error>;
4571
+ };
4572
+ };
4573
+ timeout: ITaskMiddleware<TimeoutMiddlewareConfig, void, void, any> & {
4574
+ journalKeys: {
4575
+ readonly abortController: JournalKey<AbortController>;
4576
+ };
4577
+ };
4578
+ circuitBreaker: ITaskMiddleware<CircuitBreakerMiddlewareConfig, void, void, {
4579
+ state: IResource<void, Promise<{
4580
+ statusMap: Map<string, CircuitBreakerStatus>;
4581
+ }>, {}, any, any, ITag<{
4582
+ metadata?: Record<string, any>;
4583
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
4584
+ }> & {
4585
+ journalKeys: {
4586
+ readonly state: JournalKey<CircuitBreakerState>;
4587
+ readonly failures: JournalKey<number>;
4588
+ };
4589
+ };
2441
4590
  };
2442
4591
  resource: {
2443
4592
  retry: IResourceMiddleware<RetryMiddlewareConfig, void, void, any>;
@@ -2454,6 +4603,7 @@ declare const globals: {
2454
4603
  debug: ITag<DebugFriendlyConfig, void, void>;
2455
4604
  tunnel: ITag<void, void, TunnelRunner>;
2456
4605
  tunnelPolicy: ITag<TunnelTaskMiddlewarePolicyConfig, void, void>;
4606
+ authValidator: ITag<void, void, void>;
2457
4607
  };
2458
4608
  tunnels: Readonly<{
2459
4609
  http: Readonly<{
@@ -2469,4 +4619,4 @@ declare const globals: {
2469
4619
  };
2470
4620
  declare function run(root: any, config?: any): Promise<RunResult<any>>;
2471
4621
 
2472
- export { ASYNC_CONTEXT_TYPES_LOADED, type CommonPayload, type DebugConfig, type DebugFriendlyConfig, type DefaultErrorType, type DependencyMapType, DependencyProcessor, type DependencyValueType, type DependencyValuesType, ERROR_TYPES_LOADED, errors as Errors, type EventDeliveryMode, type EventEmissionInterceptor, type EventHandlerType, EventManager, type EventStoreElementType, type ExposureFetchAuthConfig, type ExposureFetchClient, type ExposureFetchConfig, type ExtractEventPayload, type ExtractResourceConfig, type ExtractResourceValue, type ExtractTaskInput, type ExtractTaskOutput, type HookExecutionInterceptor, type HookStoreElementType, type HttpClient, type HttpClientAuth, type HttpClientConfig, type HttpClientFactory, type HttpClientFactoryConfig, type HttpSmartClient, type HttpSmartClientAuthConfig, type HttpSmartClientConfig, type IAsyncContext, type IAsyncContextDefinition, type IAsyncContextMeta, type ICacheInstance, type IErrorDefinition, type IErrorDefinitionFinal, type IErrorHelper, type IErrorMeta, type IEvent, type IEventDefinition, type IEventEmission, type IEventHandlerOptions, type IEventMeta, type IHook, type IHookDefinition, type ILog, type ILogInfo, type IMeta, type IMiddlewareMeta, type IOptionalDependency, type IPhantomTask, type IResource, type IResourceDefinition, type IResourceMeta, type IResourceMiddleware, type IResourceMiddlewareConfigured, type IResourceMiddlewareDefinition, type IResourceMiddlewareExecutionInput, type IResourceWithConfig, type ITag, type ITagConfigured, type ITagDefinition, type ITagMeta, type ITaggable, type ITask, type ITaskDefinition, type ITaskMeta, type ITaskMiddleware, type ITaskMiddlewareConfigured, type ITaskMiddlewareDefinition, type ITaskMiddlewareExecutionInput, type IValidationSchema, type LogLevels, Logger, MiddlewareManager, type MixedHttpClient, type MixedHttpClientAuthConfig, type MixedHttpClientConfig, type NodeExposureConfig, type NodeExposureDependencyMap, type NodeExposureDeps, type NodeExposureHandlers, type NodeExposureHttpConfig, type NodeExposureHttpCorsConfig, type OnUnhandledError, type OnUnhandledErrorInfo, type OverridableElements, PlatformAdapter, type PrintStrategy, Queue, type RegisterableItems, type RequiredKeys, type ResourceDependencyValueType, type ResourceDependencyValuesType, type ResourceInitFn, ResourceInitializer, type ResourceMiddlewareAttachmentType, type ResourceMiddlewareInterceptor, type ResourceMiddlewareStoreElementType, type ResourceStoreElementType, type RunOptions, RunResult, RunnerMode, Semaphore, type Serializer, Store, type TagType, type TaskDependencyWithIntercept, type TaskLocalInterceptor, type TaskMiddlewareAttachmentType, type TaskMiddlewareInterceptor, type TaskMiddlewareStoreElementType, TaskRunner, type TaskStoreElementType, type TunnelEventSelector, type TunnelMode, type TunnelRunner, type TunnelTagConfig, type TunnelTaskRunner, type TunnelTaskSelector, type UnhandledErrorKind, type UnionToIntersection, allFalse, defineAsyncContext as asyncContext, bindProcessErrorHandler, createContext, createDefaultUnhandledError, createExposureFetch, createHttpClient, createHttpMixedClient, createHttpSmartClient, createNodeFile, createTestResource, debug, debugLevels, defs as definitions, defineEvent as event, getConfig, globals, hasExposureContext, defineHook as hook, isOneOf, levelNormal, levelVerbose, nodeExposure, normalizeError, onAnyOf, defineOverride as override, r, readInputFileToBuffer, defineResource as resource, defineResourceMiddleware as resourceMiddleware, run, safeReportUnhandledError, setPlatform, symbolAsyncContext, symbolError, symbolEvent, symbolFilePath, symbolHook, symbolMiddleware, symbolMiddlewareConfigured, symbolOptionalDependency, symbolPhantomTask, symbolResource, symbolResourceMiddleware, symbolResourceWithConfig, symbolTag, symbolTagConfigured, symbolTask, symbolTaskMiddleware, symbolTunneledBy, defineTag as tag, defineTask as task, defineTaskMiddleware as taskMiddleware, useExposureContext, writeInputFileToPath };
4622
+ export { type BusEvent, type BusEventHandler, type CommonPayload, type DebugConfig, type DebugFriendlyConfig, type DefaultErrorType, type DependencyMapType, DependencyProcessor, type DependencyValueType, type DependencyValuesType, type DurableAuditEmitter, type DurableAuditEntry, type DurableAuditEntryBase, type DurableAuditEntryInput, DurableAuditEntryKind, DurableContext, DurableExecutionError, DurableOperator, DurableResource$1 as DurableResource, type DurableResourceConfig, type DurableResourceRuntimeConfig, DurableService, type DurableServiceConfig, type DurableSignalId, type DurableStepId, type DurableTask, type DurableTestSetup, type DurableTestSetupOptions, DurableWorker, type EmitOptions, type ErrorReference, errors as Errors, type EventDeliveryMode, type EventEmissionInterceptor, type EventHandlerType, EventManager, type EventStoreElementType, type ExecuteOptions, type Execution, type ExecutionJournal, ExecutionStatus, type ExposureFetchAuthConfig, type ExposureFetchClient, type ExposureFetchConfig, type ExtractEventPayload, type ExtractResourceConfig, type ExtractResourceValue, type ExtractTaskInput, type ExtractTaskOutput, type HookExecutionInterceptor, type HookStoreElementType, type HttpClient, type HttpClientAuth, type HttpClientConfig, type HttpClientFactory, type HttpClientFactoryConfig, type HttpSmartClient, type HttpSmartClientAuthConfig, type HttpSmartClientConfig, type IAsyncContext, type IAsyncContextDefinition, type IAsyncContextMeta, type ICacheInstance, type IDurableContext, type IDurableExecutionProcessor, type IDurableResource, type IDurableService, type IDurableStore, type IErrorDefinition, type IErrorDefinitionFinal, type IErrorHelper, type IErrorMeta, type IEvent, type IEventBus, type IEventDefinition, type IEventEmission, type IEventHandlerOptions, type IEventMeta, type IHook, type IHookDefinition, type ILog, type ILogInfo, type IMeta, type IMiddlewareMeta, type IOptionalDependency, type IPhantomTask, type IResource, type IResourceDefinition, type IResourceMeta, type IResourceMiddleware, type IResourceMiddlewareConfigured, type IResourceMiddlewareDefinition, type IResourceMiddlewareExecutionInput, type IResourceWithConfig, type IStepBuilder, type ITag, type ITagConfigured, type ITagDefinition, type ITagMeta, type ITaggable, type ITask, type ITaskDefinition, type ITaskExecutor, type ITaskMeta, type ITaskMiddleware, type ITaskMiddlewareConfigured, type ITaskMiddlewareDefinition, type ITaskMiddlewareExecutionInput, type IValidationSchema, type JournalKey, type JsonLimits, type ListExecutionsOptions, type LogLevels, Logger, MemoryEventBus, MemoryQueue, MemoryStore, MiddlewareManager, type MixedHttpClient, type MixedHttpClientAuthConfig, type MixedHttpClientConfig, type NodeExposureConfig, type NodeExposureDependencyMap, type NodeExposureDeps, type NodeExposureHandlers, type NodeExposureHttpConfig, type NodeExposureHttpCorsConfig, NoopEventBus, type OnUnhandledError, type OnUnhandledErrorInfo, type OverridableElements, PlatformAdapter, type PrintStrategy, Queue, RabbitMQQueue, RedisEventBus, RedisStore, type RegisterableItems, type RequiredKeys, type ResourceDependencyValueType, type ResourceDependencyValuesType, type ResourceForkInfo, type ResourceForkOptions, type ResourceForkRegisterMode, type ResourceInitFn, ResourceInitializer, type ResourceMiddlewareAttachmentType, type ResourceMiddlewareInterceptor, type ResourceMiddlewareStoreElementType, type ResourceStoreElementType, type RunOptions, RunResult, RunnerMode, type Schedule, type ScheduleConfig, type ScheduleOptions, ScheduleStatus, ScheduleType, Semaphore, Serializer, type SerializerOptions, type SignalOptions, type SleepOptions, StepBuilder, type StepOptions, type StepResult, Store, SuspensionSignal, type TagType, type TaskCallOptions, type TaskDependencyWithIntercept, type TaskLocalInterceptor, type TaskMiddlewareAttachmentType, type TaskMiddlewareInterceptor, type TaskMiddlewareStoreElementType, TaskRunner, type TaskStoreElementType, type ThrowsList, type Timer, TimerStatus, TimerType, type TunnelEventSelector, type TunnelMode, type TunnelRunner, type TunnelTagConfig, type TunnelTaskRunner, type TunnelTaskSelector, type TypeDefinition, type UnhandledErrorKind, type UnionToIntersection, allFalse, defineAsyncContext as asyncContext, bindProcessErrorHandler, createContext, createDashboardMiddleware, createDefaultUnhandledError, createDurableAuditEntryId, createDurableRunnerAuditEmitter, createDurableStepId, createDurableTestSetup, createExposureFetch, createHttpClient, createHttpMixedClient, createHttpSmartClient, createNodeFile, createTestResource, debug, debugLevels, defs as definitions, disposeDurableService, durableEvents, durableEventsArray, durableResource, defineEvent as event, getConfig, getDefaultSerializer, globals, hasExposureContext, defineHook as hook, initDurableService, initDurableWorker, isDurableInternalStepId, isOneOf, journal, levelNormal, levelVerbose, nodeExposure, normalizeError, onAnyOf, defineOverride as override, r, readInputFileToBuffer, defineResource as resource, defineResourceMiddleware as resourceMiddleware, run, safeReportUnhandledError, setPlatform, symbolAsyncContext, symbolError, symbolEvent, symbolFilePath, symbolHook, symbolMiddleware, symbolMiddlewareConfigured, symbolOptionalDependency, symbolPhantomTask, symbolResource, symbolResourceForkedFrom, symbolResourceMiddleware, symbolResourceWithConfig, symbolTag, symbolTagConfigured, symbolTask, symbolTaskMiddleware, symbolTunneledBy, defineTag as tag, defineTask as task, defineTaskMiddleware as taskMiddleware, useExposureContext, waitUntil, writeInputFileToPath };