@bluelibs/runner 4.9.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- export { EJSON } from '@bluelibs/ejson';
1
+ import * as lru_cache from 'lru-cache';
2
2
 
3
3
  declare const CONTRACT: unique symbol;
4
4
  type CONTRACT = typeof CONTRACT;
@@ -79,7 +79,7 @@ interface IAsyncContextMeta extends IMeta {
79
79
  interface ITaggable {
80
80
  tags: TagType[];
81
81
  }
82
- interface ITagDefinition<TConfig = void, TEnforceInputContract = void, TEnforceOutputContract = void> {
82
+ interface ITagDefinition<TConfig = void, _TEnforceInputContract = void, _TEnforceOutputContract = void> {
83
83
  id: string;
84
84
  meta?: ITagMeta;
85
85
  configSchema?: IValidationSchema<TConfig>;
@@ -110,7 +110,7 @@ interface ITag<TConfig = void, TEnforceInputContract = void, TEnforceOutputContr
110
110
  [symbolFilePath]: string;
111
111
  [symbolTag]: true;
112
112
  }
113
- type ITagWithOptionalConfig<TValue, TEnforceInputContract, TEnforceOutputContract> = ITag<any, TEnforceInputContract, TEnforceOutputContract> & {
113
+ type ITagWithOptionalConfig<_TValue, TEnforceInputContract, TEnforceOutputContract> = ITag<any, TEnforceInputContract, TEnforceOutputContract> & {
114
114
  readonly __configHasOnlyOptionalKeys: true;
115
115
  };
116
116
  interface ITagConfigured<TConfig = void, TEnforceInputContract = void, TEnforceOutputContract = void> extends ITag<TConfig, TEnforceInputContract, TEnforceOutputContract> {
@@ -152,9 +152,86 @@ declare const symbolFilePath: unique symbol;
152
152
  /** @internal Marks an async context definition */
153
153
  declare const symbolAsyncContext: unique symbol;
154
154
 
155
+ interface IResourceMiddlewareDefinition<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> {
156
+ id: string;
157
+ /** Static or lazy dependency map. */
158
+ dependencies?: TDependencies | ((config: TConfig) => TDependencies);
159
+ /**
160
+ * Optional validation schema for runtime config validation.
161
+ * When provided, middleware config will be validated when .with() is called.
162
+ */
163
+ configSchema?: IValidationSchema<TConfig>;
164
+ /**
165
+ * The middleware body, called with resource execution input.
166
+ */
167
+ run: (input: IResourceMiddlewareExecutionInput<TEnforceInputContract extends void ? any : TEnforceInputContract, TEnforceOutputContract extends void ? any : TEnforceOutputContract>, dependencies: DependencyValuesType<TDependencies>, config: TConfig) => Promise<any>;
168
+ meta?: IMiddlewareMeta;
169
+ tags?: TagType[];
170
+ everywhere?: boolean | ((resource: IResource<any, any, any, any, any>) => boolean);
171
+ }
172
+ interface IResourceMiddleware<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> extends IResourceMiddlewareDefinition<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>, IContractable<TConfig, TEnforceInputContract, TEnforceOutputContract> {
173
+ [symbolResourceMiddleware]: true;
174
+ id: string;
175
+ dependencies: TDependencies | ((config: TConfig) => TDependencies);
176
+ /** Current configuration object (empty by default). */
177
+ config: TConfig;
178
+ /** Configure the middleware and return a marked, configured instance. */
179
+ with: (config: TConfig) => IResourceMiddlewareConfigured<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
180
+ [symbolFilePath]: string;
181
+ tags: TagType[];
182
+ }
183
+ interface IResourceMiddlewareConfigured<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> extends IResourceMiddleware<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies> {
184
+ [symbolMiddlewareConfigured]: true;
185
+ }
186
+ interface IResourceMiddlewareExecutionInput<TResourceConfig = any, TResourceOutput = any> {
187
+ /** Resource hook */
188
+ resource: {
189
+ definition: IResource<TResourceConfig, any, any, any, any>;
190
+ config: TResourceConfig;
191
+ };
192
+ next: (resourceConfig?: TResourceConfig) => Promise<TResourceOutput>;
193
+ }
194
+ type ResourceMiddlewareAttachmentType = IResourceMiddleware<void, any, any, any> | IResourceMiddleware<{
195
+ [K in any]?: any;
196
+ }, any, any, any> | IResourceMiddlewareConfigured<any, any, any, any>;
197
+
198
+ type ErrorReference = string | IErrorHelper<any>;
199
+ type ThrowsList = ReadonlyArray<ErrorReference>;
200
+ interface IErrorDefinition<TData extends DefaultErrorType = DefaultErrorType> {
201
+ id: string;
202
+ serialize?: (data: TData) => string;
203
+ parse?: (data: string) => TData;
204
+ format?: (data: TData) => string;
205
+ /**
206
+ * Validate error data on throw(). If provided, data is parsed first.
207
+ */
208
+ dataSchema?: IValidationSchema<TData>;
209
+ meta?: IErrorMeta;
210
+ }
211
+ interface IErrorDefinitionFinal<TData extends DefaultErrorType> extends IErrorDefinition<TData> {
212
+ format: (data: TData) => string;
213
+ }
214
+ type DefaultErrorType = Record<string, unknown>;
215
+ /**
216
+ * Runtime helper returned by defineError()/r.error().
217
+ * Contains helpers to throw typed errors and perform type-safe checks.
218
+ */
219
+ interface IErrorHelper<TData extends DefaultErrorType = DefaultErrorType> {
220
+ /** Unique id for registration and DI */
221
+ id: string;
222
+ /** Throw a typed error with the given data */
223
+ throw(data: TData): never;
224
+ /** Type guard for checking if an unknown error is this error */
225
+ is(error: unknown): boolean;
226
+ /** Brand symbol for runtime detection */
227
+ [symbolError]: true;
228
+ /** Return an optional dependency wrapper for this error */
229
+ optional(): IOptionalDependency<IErrorHelper<TData>>;
230
+ }
231
+
155
232
  type IsAny<T> = 0 extends 1 & T ? true : false;
156
233
  type IsUnspecified<T> = [T] extends [undefined] ? true : [T] extends [void] ? true : IsAny<T> extends true ? true : false;
157
- 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[]> {
234
+ 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[]> {
158
235
  /** Stable identifier. */
159
236
  id: string;
160
237
  /** Static or lazy dependency map. Receives `config` when provided. */
@@ -184,6 +261,16 @@ interface IResourceDefinition<TConfig = any, TValue extends Promise<any> = Promi
184
261
  */
185
262
  dispose?: (this: any, value: TValue extends Promise<infer U> ? U : TValue, config: TConfig, dependencies: ResourceDependencyValuesType<TDependencies>, context: TContext) => Promise<void>;
186
263
  meta?: TMeta;
264
+ /**
265
+ * Declares which typed errors are part of this resource's contract.
266
+ *
267
+ * This is a declarative contract only:
268
+ * - It does not imply dependency injection
269
+ * - It does not enforce that only these errors can be thrown
270
+ *
271
+ * Use string ids or Error helpers.
272
+ */
273
+ throws?: ThrowsList;
187
274
  /**
188
275
  * Optional validation schema for runtime config validation.
189
276
  * When provided, resource config will be validated when .with() is called.
@@ -220,9 +307,17 @@ interface IResource<TConfig = void, TValue extends Promise<any> = Promise<any>,
220
307
  middleware: TMiddleware;
221
308
  [symbolFilePath]: string;
222
309
  [symbolResource]: true;
310
+ /** Normalized list of error ids declared via `throws`. */
311
+ throws?: readonly string[];
223
312
  /** Return an optional dependency wrapper for this resource. */
224
313
  optional: () => IOptionalDependency<IResource<TConfig, TValue, TDependencies, TContext, TMeta, TTags, TMiddleware>>;
225
314
  tags: TTags;
315
+ /**
316
+ * Create a new resource with a different id but the same definition.
317
+ * Useful for creating multiple instances of a "template" resource.
318
+ * The forked resource should be exported and used as a dependency.
319
+ */
320
+ fork(newId: string): IResource<TConfig, TValue, TDependencies, TContext, TMeta, TTags, TMiddleware>;
226
321
  }
227
322
  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[]> {
228
323
  [symbolResourceWithConfig]: true;
@@ -234,55 +329,34 @@ interface IResourceWithConfig<TConfig = any, TValue extends Promise<any> = Promi
234
329
  config: TConfig;
235
330
  }
236
331
 
237
- interface ITaskDefinition<TInput = undefined, TOutput extends Promise<any> = any, TDependencies extends DependencyMapType = {}, TMeta extends ITaskMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> {
238
- id: string;
239
- /**
240
- * Access other tasks/resources/events. Can be an object or a function when
241
- * you need late or config‑dependent resolution.
242
- */
243
- dependencies?: TDependencies | (() => TDependencies);
244
- /** Middleware applied around task execution. */
245
- middleware?: TMiddleware;
246
- /** Optional metadata used for docs, filtering and tooling. */
247
- meta?: TMeta;
248
- /**
249
- * Optional validation schema for runtime input validation.
250
- * When provided, task input will be validated before execution.
251
- */
252
- inputSchema?: IValidationSchema<TInput>;
253
- /**
254
- * Optional validation schema for the task result.
255
- * When provided, the result will be validated immediately after the task's
256
- * `run` resolves, without considering middleware.
257
- */
258
- resultSchema?: IValidationSchema<TOutput extends Promise<infer U> ? U : never>;
259
- 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;
332
+ /**
333
+ * Typed key used to store/retrieve values from an ExecutionJournal.
334
+ * The `id` is used as the storage slot.
335
+ */
336
+ declare const journalKeyBrand: unique symbol;
337
+ type JournalKey<T> = {
338
+ readonly id: string;
339
+ readonly [journalKeyBrand]?: (value: T) => T;
340
+ };
341
+ /**
342
+ * Options for setting values in the journal.
343
+ */
344
+ interface JournalSetOptions {
260
345
  /**
261
- * Tags applied to the task that might define its behvaiour or impact the systems.
346
+ * If true, allows overwriting an existing value.
347
+ * By default, attempting to set a key that already exists will throw an error.
262
348
  */
263
- tags?: TTags;
349
+ override?: boolean;
264
350
  }
265
- 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> {
266
- [symbolFilePath]: string;
267
- [symbolTask]: true;
268
- /** Present only for phantom tasks. */
269
- [symbolPhantomTask]?: true;
270
- /** Indicates if the task is tunneled through a tunnel client. */
271
- isTunneled?: boolean;
272
- /** Records which tunnel resource owns the task (exclusivity). */
273
- [symbolTunneledBy]?: string;
274
- id: string;
275
- dependencies: TDependencies | (() => TDependencies);
276
- computedDependencies?: DependencyValuesType<TDependencies>;
277
- middleware: TMiddleware;
278
- /** Return an optional dependency wrapper for this task. */
279
- optional: () => IOptionalDependency<ITask<TInput, TOutput, TDependencies, TMeta, TTags, TMiddleware>>;
280
- tags: TTags;
351
+ /**
352
+ * Per-execution registry that allows middleware and tasks to share state.
353
+ * A new journal is created for each top-level task execution unless explicitly forwarded.
354
+ */
355
+ interface ExecutionJournal {
356
+ set<T>(key: JournalKey<T>, value: T, options?: JournalSetOptions): void;
357
+ get<T>(key: JournalKey<T>): T | undefined;
358
+ has<T>(key: JournalKey<T>): boolean;
281
359
  }
282
- /** Narrowed type for phantom tasks (no-op run by default). */
283
- 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> & {
284
- [symbolPhantomTask]: true;
285
- };
286
360
 
287
361
  interface ITaskMiddlewareDefinition<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> {
288
362
  id: string;
@@ -305,7 +379,7 @@ interface ITaskMiddleware<TConfig = any, TEnforceInputContract = void, TEnforceO
305
379
  [symbolTaskMiddleware]: true;
306
380
  [symbolFilePath]: string;
307
381
  id: string;
308
- dependencies: TDependencies | (() => TDependencies);
382
+ dependencies: TDependencies | ((config: TConfig) => TDependencies);
309
383
  /** Current configuration object (empty by default). */
310
384
  config: TConfig;
311
385
  /** Configure the middleware and return a marked, configured instance. */
@@ -323,72 +397,76 @@ interface ITaskMiddlewareExecutionInput<TTaskInput = any, TTaskOutput = any> {
323
397
  input: TTaskInput;
324
398
  };
325
399
  next: (taskInput?: TTaskInput) => Promise<TTaskOutput>;
400
+ /** Per-execution registry for sharing state between middleware and task */
401
+ journal: ExecutionJournal;
326
402
  }
327
403
  type TaskMiddlewareAttachmentType = ITaskMiddleware<void, any, any, any> | ITaskMiddleware<{
328
404
  [K in any]?: any;
329
405
  }, any, any, any> | ITaskMiddlewareConfigured<any, any, any, any>;
330
406
 
331
- interface IResourceMiddlewareDefinition<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> {
407
+ interface ITaskDefinition<TInput = undefined, TOutput extends Promise<any> = any, TDependencies extends DependencyMapType = {}, TMeta extends ITaskMeta = any, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> {
332
408
  id: string;
333
- /** Static or lazy dependency map. */
334
- dependencies?: TDependencies | ((config: TConfig) => TDependencies);
335
409
  /**
336
- * Optional validation schema for runtime config validation.
337
- * When provided, middleware config will be validated when .with() is called.
410
+ * Access other tasks/resources/events. Can be an object or a function when
411
+ * you need late or config‑dependent resolution.
338
412
  */
339
- configSchema?: IValidationSchema<TConfig>;
413
+ dependencies?: TDependencies | (() => TDependencies);
414
+ /** Middleware applied around task execution. */
415
+ middleware?: TMiddleware;
416
+ /** Optional metadata used for docs, filtering and tooling. */
417
+ meta?: TMeta;
340
418
  /**
341
- * The middleware body, called with resource execution input.
419
+ * Optional validation schema for runtime input validation.
420
+ * When provided, task input will be validated before execution.
342
421
  */
343
- run: (input: IResourceMiddlewareExecutionInput<TEnforceInputContract extends void ? any : TEnforceInputContract, TEnforceOutputContract extends void ? any : TEnforceOutputContract>, dependencies: DependencyValuesType<TDependencies>, config: TConfig) => Promise<any>;
344
- meta?: IMiddlewareMeta;
345
- tags?: TagType[];
346
- everywhere?: boolean | ((resource: IResource<any, any, any, any, any>) => boolean);
422
+ inputSchema?: IValidationSchema<TInput>;
423
+ /**
424
+ * Optional validation schema for the task result.
425
+ * When provided, the result will be validated immediately after the task's
426
+ * `run` resolves, without considering middleware.
427
+ */
428
+ resultSchema?: IValidationSchema<TOutput extends Promise<infer U> ? U : never>;
429
+ /**
430
+ * Declares which typed errors are part of this task's contract.
431
+ *
432
+ * This is a declarative contract only:
433
+ * - It does not imply dependency injection
434
+ * - It does not enforce that only these errors can be thrown
435
+ *
436
+ * Use string ids or Error helpers.
437
+ */
438
+ throws?: ThrowsList;
439
+ run: (input: HasInputContracts<[...TTags, ...TMiddleware]> extends true ? [TInput] extends [undefined] ? InferInputOrViolationFromContracts<[...TTags, ...TMiddleware]> : EnsureInputSatisfiesContracts<[...TTags, ...TMiddleware], TInput> : TInput, dependencies: DependencyValuesType<TDependencies>, context?: {
440
+ journal: ExecutionJournal;
441
+ }) => HasOutputContracts<[...TTags, ...TMiddleware]> extends true ? EnsureOutputSatisfiesContracts<[...TTags, ...TMiddleware], TOutput> : TOutput;
442
+ /**
443
+ * Tags applied to the task that might define its behvaiour or impact the systems.
444
+ */
445
+ tags?: TTags;
347
446
  }
348
- interface IResourceMiddleware<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> extends IResourceMiddlewareDefinition<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>, IContractable<TConfig, TEnforceInputContract, TEnforceOutputContract> {
349
- [symbolResourceMiddleware]: true;
350
- id: string;
351
- dependencies: TDependencies | (() => TDependencies);
352
- /** Current configuration object (empty by default). */
353
- config: TConfig;
354
- /** Configure the middleware and return a marked, configured instance. */
355
- with: (config: TConfig) => IResourceMiddlewareConfigured<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
447
+ 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> {
356
448
  [symbolFilePath]: string;
357
- tags: TagType[];
358
- }
359
- interface IResourceMiddlewareConfigured<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> extends IResourceMiddleware<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies> {
360
- [symbolMiddlewareConfigured]: true;
361
- }
362
- interface IResourceMiddlewareExecutionInput<TResourceConfig = any, TResourceOutput = any> {
363
- /** Resource hook */
364
- resource: {
365
- definition: IResource<TResourceConfig, any, any, any, any>;
366
- config: TResourceConfig;
367
- };
368
- next: (resourceConfig?: TResourceConfig) => Promise<TResourceOutput>;
369
- }
370
- type ResourceMiddlewareAttachmentType = IResourceMiddleware<void, any, any, any> | IResourceMiddleware<{
371
- [K in any]?: any;
372
- }, any, any, any> | IResourceMiddlewareConfigured<any, any, any, any>;
373
-
374
- type OnType = "*" | IEventDefinition<any> | readonly IEventDefinition<any>[];
375
- interface IHookDefinition<TDependencies extends DependencyMapType = {}, TOn extends OnType = any, TMeta extends ITaskMeta = any> {
376
- id: string;
377
- dependencies?: TDependencies | (() => TDependencies);
378
- on: TOn;
379
- /** Listener execution order. Lower numbers run first. */
380
- order?: number;
381
- meta?: TMeta;
382
- run: (event: IEventEmission<TOn extends "*" ? any : TOn extends readonly IEventDefinition<any>[] ? CommonPayload<TOn> : ExtractEventPayload<TOn>>, dependencies: DependencyValuesType<TDependencies>) => Promise<any>;
383
- tags?: TagType[];
384
- }
385
- interface IHook<TDependencies extends DependencyMapType = {}, TOn extends OnType = any, TMeta extends ITaskMeta = any> extends IHookDefinition<TDependencies, TOn, TMeta> {
449
+ [symbolTask]: true;
450
+ /** Present only for phantom tasks. */
451
+ [symbolPhantomTask]?: true;
452
+ /** Indicates if the task is tunneled through a tunnel client. */
453
+ isTunneled?: boolean;
454
+ /** Records which tunnel resource owns the task (exclusivity). */
455
+ [symbolTunneledBy]?: string;
386
456
  id: string;
387
457
  dependencies: TDependencies | (() => TDependencies);
388
- [symbolFilePath]: string;
389
- [symbolHook]: true;
390
- tags: TagType[];
458
+ computedDependencies?: DependencyValuesType<TDependencies>;
459
+ middleware: TMiddleware;
460
+ /** Normalized list of error ids declared via `throws`. */
461
+ throws?: readonly string[];
462
+ /** Return an optional dependency wrapper for this task. */
463
+ optional: () => IOptionalDependency<ITask<TInput, TOutput, TDependencies, TMeta, TTags, TMiddleware>>;
464
+ tags: TTags;
391
465
  }
466
+ /** Narrowed type for phantom tasks (no-op run by default). */
467
+ 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> & {
468
+ [symbolPhantomTask]: true;
469
+ };
392
470
 
393
471
  type EventHandlerType<T = any> = (event: IEventEmission<T>) => any | Promise<any>;
394
472
  declare function onAnyOf<T extends readonly IEventDefinition<any>[]>(...defs: T): T;
@@ -466,41 +544,25 @@ interface IEventEmission<TPayload = any> {
466
544
  tags: TagType[];
467
545
  }
468
546
 
469
- declare const ERROR_TYPES_LOADED: true;
470
- interface IErrorDefinition<TData extends DefaultErrorType = DefaultErrorType> {
547
+ type OnType = "*" | IEventDefinition<any> | readonly IEventDefinition<any>[];
548
+ interface IHookDefinition<TDependencies extends DependencyMapType = {}, TOn extends OnType = any, TMeta extends ITaskMeta = any> {
471
549
  id: string;
472
- serialize?: (data: TData) => string;
473
- parse?: (data: string) => TData;
474
- format?: (data: TData) => string;
475
- /**
476
- * Validate error data on throw(). If provided, data is parsed first.
477
- */
478
- dataSchema?: IValidationSchema<TData>;
479
- meta?: IErrorMeta;
480
- }
481
- interface IErrorDefinitionFinal<TData extends DefaultErrorType> extends IErrorDefinition<TData> {
482
- format: (data: TData) => string;
550
+ dependencies?: TDependencies | (() => TDependencies);
551
+ on: TOn;
552
+ /** Listener execution order. Lower numbers run first. */
553
+ order?: number;
554
+ meta?: TMeta;
555
+ run: (event: IEventEmission<TOn extends "*" ? any : TOn extends readonly IEventDefinition<any>[] ? CommonPayload<TOn> : ExtractEventPayload<TOn>>, dependencies: DependencyValuesType<TDependencies>) => Promise<any>;
556
+ tags?: TagType[];
483
557
  }
484
- type DefaultErrorType = Record<string, unknown>;
485
- /**
486
- * Runtime helper returned by defineError()/r.error().
487
- * Contains helpers to throw typed errors and perform type-safe checks.
488
- */
489
- interface IErrorHelper<TData extends DefaultErrorType = DefaultErrorType> {
490
- /** Unique id for registration and DI */
558
+ interface IHook<TDependencies extends DependencyMapType = {}, TOn extends OnType = any, TMeta extends ITaskMeta = any> extends IHookDefinition<TDependencies, TOn, TMeta> {
491
559
  id: string;
492
- /** Throw a typed error with the given data */
493
- throw(data: TData): never;
494
- /** Type guard for checking if an unknown error is this error */
495
- is(error: unknown): boolean;
496
- /** Brand symbol for runtime detection */
497
- [symbolError]: true;
498
- /** Return an optional dependency wrapper for this error */
499
- optional(): IOptionalDependency<IErrorHelper<TData>>;
560
+ dependencies: TDependencies | (() => TDependencies);
561
+ [symbolFilePath]: string;
562
+ [symbolHook]: true;
563
+ tags: TagType[];
500
564
  }
501
565
 
502
- declare const ASYNC_CONTEXT_TYPES_LOADED: true;
503
-
504
566
  interface IAsyncContextDefinition<T> {
505
567
  id: string;
506
568
  serialize?(data: T): string;
@@ -588,20 +650,31 @@ interface IOptionalDependency<T> {
588
650
  /** Brand symbol for optional dependency */
589
651
  [symbolOptionalDependency]: true;
590
652
  }
591
- type ExtractTaskInput<T> = T extends ITask<infer I, any, infer D> ? I : never;
592
- type ExtractTaskOutput<T> = T extends ITask<any, infer O, infer D> ? O : never;
653
+ type ExtractTaskInput<T> = T extends ITask<infer I, any, infer _D> ? I : never;
654
+ type ExtractTaskOutput<T> = T extends ITask<any, infer O, infer _D> ? O : never;
593
655
  type ExtractResourceConfig<T> = T extends IResource<infer C, any, any> ? C : never;
594
- type ExtractResourceValue<T> = T extends IResource<any, infer V, infer D> ? V extends Promise<infer U> ? U : V : never;
656
+ type ExtractResourceValue<T> = T extends IResource<any, infer V, infer _D> ? V extends Promise<infer U> ? U : V : never;
595
657
  type ExtractEventPayload<T> = T extends IEventDefinition<infer P> ? P : T extends IEvent<infer P> ? P : never;
596
658
  type UnionToIntersection<U> = (U extends any ? (x: U) => any : never) extends (x: infer I) => any ? I : never;
597
659
  type CommonPayload<T extends readonly IEventDefinition<any>[] | IEventDefinition<any>> = T extends readonly IEventDefinition<any>[] ? {
598
660
  [K in keyof ExtractEventPayload<T[number]>]: UnionToIntersection<ExtractEventPayload<T[number]> extends any ? ExtractEventPayload<T[number]>[K] : never>;
599
661
  } : ExtractEventPayload<T>;
662
+ /**
663
+ * Options that can be passed when calling a task dependency.
664
+ * Allows forwarding the execution journal to nested task calls.
665
+ */
666
+ interface TaskCallOptions {
667
+ /** Optional journal to forward to the nested task */
668
+ journal?: ExecutionJournal;
669
+ }
600
670
  /**
601
671
  * Task dependencies transform into callable functions: call with the task input
602
- * and you receive the task output.
672
+ * and you receive the task output. Optionally accepts TaskCallOptions for journal forwarding.
603
673
  */
604
- type TaskDependency<I, O> = (...args: I extends null | void ? [] : [I]) => O;
674
+ type TaskDependency<I, O> = I extends null | void ? {
675
+ (options?: TaskCallOptions): O;
676
+ (input?: I, options?: TaskCallOptions): O;
677
+ } : (input: I, options?: TaskCallOptions) => O;
605
678
  /**
606
679
  * Resource dependencies resolve to the resource's value directly.
607
680
  */
@@ -714,6 +787,7 @@ declare class LogPrinter {
714
787
  private formatContext;
715
788
  private normalizeForJson;
716
789
  private static NO_COLORS;
790
+ private static readonly DEFAULT_WRITERS;
717
791
  private static writers;
718
792
  static setWriters(writers: Partial<{
719
793
  log: (msg: any) => void;
@@ -868,7 +942,7 @@ type RunOptions = {
868
942
  * When set, forces runtime cycle detection for event emissions. Disable if you're sure
869
943
  * you don't have event deadlocks to improve event emission performance.
870
944
  */
871
- runtimeCycleDetection?: boolean;
945
+ runtimeEventCycleDetection?: boolean;
872
946
  /**
873
947
  * Specify in which mode to run "dev", "prod" or "test".
874
948
  * If inside Node this is automatically detected from the NODE_ENV environment variable if not provided.
@@ -888,6 +962,8 @@ interface ICacheInstance {
888
962
  set(key: string, value: any): void;
889
963
  get(key: string): any;
890
964
  clear(): void;
965
+ /** Optional presence check to disambiguate cached undefined values */
966
+ has?(key: string): boolean;
891
967
  }
892
968
 
893
969
  type ResourceStoreElementType<C = any, V extends Promise<any> = any, D extends DependencyMapType = {}, TContext = any> = {
@@ -939,13 +1015,12 @@ type EventStoreElementType = {
939
1015
  * - Safe overrides and strong typing around config and register mechanics
940
1016
  */
941
1017
 
942
- declare const defs_ASYNC_CONTEXT_TYPES_LOADED: typeof ASYNC_CONTEXT_TYPES_LOADED;
943
1018
  type defs_CommonPayload<T extends readonly IEventDefinition<any>[] | IEventDefinition<any>> = CommonPayload<T>;
944
1019
  type defs_DefaultErrorType = DefaultErrorType;
945
1020
  type defs_DependencyMapType = DependencyMapType;
946
1021
  type defs_DependencyValueType<T> = DependencyValueType<T>;
947
1022
  type defs_DependencyValuesType<T extends DependencyMapType> = DependencyValuesType<T>;
948
- declare const defs_ERROR_TYPES_LOADED: typeof ERROR_TYPES_LOADED;
1023
+ type defs_ErrorReference = ErrorReference;
949
1024
  type defs_EventHandlerType<T = any> = EventHandlerType<T>;
950
1025
  type defs_EventStoreElementType = EventStoreElementType;
951
1026
  type defs_ExtractEventPayload<T> = ExtractEventPayload<T>;
@@ -973,7 +1048,7 @@ type defs_IMiddlewareMeta = IMiddlewareMeta;
973
1048
  type defs_IOptionalDependency<T> = IOptionalDependency<T>;
974
1049
  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>;
975
1050
  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>;
976
- 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>;
1051
+ 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>;
977
1052
  type defs_IResourceMeta = IResourceMeta;
978
1053
  type defs_IResourceMiddleware<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> = IResourceMiddleware<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
979
1054
  type defs_IResourceMiddlewareConfigured<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> = IResourceMiddlewareConfigured<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
@@ -982,7 +1057,7 @@ type defs_IResourceMiddlewareExecutionInput<TResourceConfig = any, TResourceOutp
982
1057
  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>;
983
1058
  type defs_ITag<TConfig = void, TEnforceInputContract = void, TEnforceOutputContract = void> = ITag<TConfig, TEnforceInputContract, TEnforceOutputContract>;
984
1059
  type defs_ITagConfigured<TConfig = void, TEnforceInputContract = void, TEnforceOutputContract = void> = ITagConfigured<TConfig, TEnforceInputContract, TEnforceOutputContract>;
985
- type defs_ITagDefinition<TConfig = void, TEnforceInputContract = void, TEnforceOutputContract = void> = ITagDefinition<TConfig, TEnforceInputContract, TEnforceOutputContract>;
1060
+ type defs_ITagDefinition<TConfig = void, _TEnforceInputContract = void, _TEnforceOutputContract = void> = ITagDefinition<TConfig, _TEnforceInputContract, _TEnforceOutputContract>;
986
1061
  type defs_ITagMeta = ITagMeta;
987
1062
  type defs_ITaggable = ITaggable;
988
1063
  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>;
@@ -1006,11 +1081,13 @@ type defs_RunOptions = RunOptions;
1006
1081
  type defs_RunnerMode = RunnerMode;
1007
1082
  declare const defs_RunnerMode: typeof RunnerMode;
1008
1083
  type defs_TagType = TagType;
1084
+ type defs_TaskCallOptions = TaskCallOptions;
1009
1085
  type defs_TaskDependencyWithIntercept<TInput, TOutput> = TaskDependencyWithIntercept<TInput, TOutput>;
1010
1086
  type defs_TaskLocalInterceptor<TInput, TOutput> = TaskLocalInterceptor<TInput, TOutput>;
1011
1087
  type defs_TaskMiddlewareAttachmentType = TaskMiddlewareAttachmentType;
1012
1088
  type defs_TaskMiddlewareStoreElementType<TDeps extends DependencyMapType = any> = TaskMiddlewareStoreElementType<TDeps>;
1013
1089
  type defs_TaskStoreElementType<Input = any, Output extends Promise<any> = any, D extends DependencyMapType = any> = TaskStoreElementType<Input, Output, D>;
1090
+ type defs_ThrowsList = ThrowsList;
1014
1091
  type defs_UnionToIntersection<U> = UnionToIntersection<U>;
1015
1092
  declare const defs_isOneOf: typeof isOneOf;
1016
1093
  declare const defs_onAnyOf: typeof onAnyOf;
@@ -1032,7 +1109,7 @@ declare const defs_symbolTask: typeof symbolTask;
1032
1109
  declare const defs_symbolTaskMiddleware: typeof symbolTaskMiddleware;
1033
1110
  declare const defs_symbolTunneledBy: typeof symbolTunneledBy;
1034
1111
  declare namespace defs {
1035
- 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 };
1112
+ 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_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_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 };
1036
1113
  }
1037
1114
 
1038
1115
  interface TaskMiddlewareFluentBuilder<C = any, In = void, Out = void, D extends DependencyMapType = {}> {
@@ -1052,7 +1129,7 @@ interface TaskMiddlewareFluentBuilder<C = any, In = void, Out = void, D extends
1052
1129
  everywhere(flag: boolean | ((task: ITask<any, any, any, any>) => boolean)): TaskMiddlewareFluentBuilder<C, In, Out, D>;
1053
1130
  build(): ITaskMiddleware<C, In, Out, D>;
1054
1131
  }
1055
- declare function taskMiddlewareBuilder<C = void, In = void, Out = void, D extends DependencyMapType = {}>(id: string): TaskMiddlewareFluentBuilder<C, In, Out, D>;
1132
+
1056
1133
  interface ResourceMiddlewareFluentBuilder<C = any, In = void, Out = void, D extends DependencyMapType = {}> {
1057
1134
  id: string;
1058
1135
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | ((config: C) => TNewDeps), options?: {
@@ -1070,35 +1147,29 @@ interface ResourceMiddlewareFluentBuilder<C = any, In = void, Out = void, D exte
1070
1147
  everywhere(flag: boolean | ((resource: IResource<any, any, any, any, any>) => boolean)): ResourceMiddlewareFluentBuilder<C, In, Out, D>;
1071
1148
  build(): IResourceMiddleware<C, In, Out, D>;
1072
1149
  }
1073
- declare function resourceMiddlewareBuilder<C = void, In = void, Out = void, D extends DependencyMapType = {}>(id: string): ResourceMiddlewareFluentBuilder<C, In, Out, D>;
1074
1150
 
1075
- declare class RunnerError<TData extends DefaultErrorType = DefaultErrorType> extends Error {
1076
- readonly id: string;
1077
- readonly data: TData;
1078
- constructor(id: string, message: string, data: TData);
1079
- }
1080
- declare class ErrorHelper<TData extends DefaultErrorType = DefaultErrorType> implements IErrorHelper<TData> {
1081
- private readonly definition;
1082
- [symbolError]: true;
1083
- constructor(definition: IErrorDefinitionFinal<TData>);
1084
- get id(): string;
1085
- throw(data: TData): never;
1086
- is(error: unknown): error is RunnerError<TData>;
1087
- optional(): {
1088
- readonly inner: IErrorHelper<TData>;
1089
- readonly [symbolOptionalDependency]: true;
1090
- };
1091
- }
1151
+ /**
1152
+ * Entry point for creating a task middleware builder.
1153
+ */
1154
+ declare function taskMiddlewareBuilder<C = void, In = void, Out = void, D extends DependencyMapType = {}>(id: string): TaskMiddlewareFluentBuilder<C, In, Out, D>;
1155
+ /**
1156
+ * Entry point for creating a resource middleware builder.
1157
+ */
1158
+ declare function resourceMiddlewareBuilder<C = void, In = void, Out = void, D extends DependencyMapType = {}>(id: string): ResourceMiddlewareFluentBuilder<C, In, Out, D>;
1092
1159
 
1093
1160
  interface ErrorFluentBuilder<TData extends DefaultErrorType = DefaultErrorType> {
1094
1161
  id: string;
1095
1162
  serialize(fn: (data: TData) => string): ErrorFluentBuilder<TData>;
1096
1163
  parse(fn: (raw: string) => TData): ErrorFluentBuilder<TData>;
1097
1164
  dataSchema(schema: IValidationSchema<TData>): ErrorFluentBuilder<TData>;
1098
- build(): ErrorHelper<TData>;
1165
+ build(): IErrorHelper<TData>;
1099
1166
  format(fn: (data: TData) => string): ErrorFluentBuilder<TData>;
1100
1167
  meta<TNewMeta extends IErrorMeta>(m: TNewMeta): ErrorFluentBuilder<TData>;
1101
1168
  }
1169
+
1170
+ /**
1171
+ * Entry point for creating an error builder.
1172
+ */
1102
1173
  declare function errorBuilder<TData extends DefaultErrorType = DefaultErrorType>(id: string): ErrorFluentBuilder<TData>;
1103
1174
 
1104
1175
  interface AsyncContextFluentBuilder<T = unknown> {
@@ -1109,6 +1180,10 @@ interface AsyncContextFluentBuilder<T = unknown> {
1109
1180
  meta<TNewMeta extends IAsyncContextMeta>(m: TNewMeta): AsyncContextFluentBuilder<T>;
1110
1181
  build(): IAsyncContext<T>;
1111
1182
  }
1183
+
1184
+ /**
1185
+ * Entry point for creating an async context builder.
1186
+ */
1112
1187
  declare function asyncContextBuilder<T = unknown>(id: string): AsyncContextFluentBuilder<T>;
1113
1188
 
1114
1189
  interface TagFluentBuilder<TConfig = void, TEnforceIn = void, TEnforceOut = void> {
@@ -1118,11 +1193,19 @@ interface TagFluentBuilder<TConfig = void, TEnforceIn = void, TEnforceOut = void
1118
1193
  config<TNewConfig>(config: TNewConfig): TagFluentBuilder<TNewConfig, TEnforceIn, TEnforceOut>;
1119
1194
  build(): ITag<TConfig, TEnforceIn, TEnforceOut>;
1120
1195
  }
1196
+
1197
+ /**
1198
+ * Entry point for creating a tag builder.
1199
+ */
1121
1200
  declare function tagBuilder<TConfig = void, TEnforceIn = void, TEnforceOut = void>(id: string): TagFluentBuilder<TConfig, TEnforceIn, TEnforceOut>;
1122
1201
 
1123
- interface HookFluentBuilder<TDeps extends DependencyMapType = {}, TOn extends "*" | IEventDefinition<any> | readonly IEventDefinition<any>[] = any, TMeta extends ITaskMeta = ITaskMeta> {
1202
+ /** Valid event targets for hook's .on() method */
1203
+ type ValidOnTarget = "*" | IEventDefinition<any> | readonly IEventDefinition<any>[];
1204
+ /** Resolved TOn when valid, or `any` when undefined (build will throw at runtime) */
1205
+ type ResolvedOn<TOn> = TOn extends ValidOnTarget ? TOn : any;
1206
+ interface HookFluentBuilder<TDeps extends DependencyMapType = {}, TOn extends ValidOnTarget | undefined = undefined, TMeta extends ITaskMeta = ITaskMeta> {
1124
1207
  id: string;
1125
- on<TNewOn extends "*" | IEventDefinition<any> | readonly IEventDefinition<any>[]>(on: TNewOn): HookFluentBuilder<TDeps, TNewOn, TMeta>;
1208
+ on<TNewOn extends ValidOnTarget>(on: TNewOn): HookFluentBuilder<TDeps, TNewOn, TMeta>;
1126
1209
  order(order: number): HookFluentBuilder<TDeps, TOn, TMeta>;
1127
1210
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | (() => TNewDeps), options?: {
1128
1211
  override?: false;
@@ -1134,10 +1217,20 @@ interface HookFluentBuilder<TDeps extends DependencyMapType = {}, TOn extends "*
1134
1217
  override?: boolean;
1135
1218
  }): HookFluentBuilder<TDeps, TOn, TMeta>;
1136
1219
  meta<TNewMeta extends ITaskMeta>(m: TNewMeta): HookFluentBuilder<TDeps, TOn, TNewMeta>;
1137
- run(fn: IHookDefinition<TDeps, TOn, TMeta>["run"]): HookFluentBuilder<TDeps, TOn, TMeta>;
1138
- build(): IHook<TDeps, TOn, TMeta>;
1220
+ /** Set the hook's run handler. Required before build(). */
1221
+ run(fn: IHookDefinition<TDeps, ResolvedOn<TOn>, TMeta>["run"]): HookFluentBuilder<TDeps, TOn, TMeta>;
1222
+ /**
1223
+ * Build the hook definition. Requires .on() and .run() to be called first.
1224
+ * @throws {Error} if on or run are not set
1225
+ */
1226
+ build(): IHook<TDeps, ResolvedOn<TOn>, TMeta>;
1139
1227
  }
1140
- declare function hookBuilder(id: string): HookFluentBuilder<{}, any, ITaskMeta>;
1228
+
1229
+ /**
1230
+ * Entry point for creating a hook builder.
1231
+ * Requires calling .on() and .run() before .build().
1232
+ */
1233
+ declare function hookBuilder(id: string): HookFluentBuilder<{}, undefined, ITaskMeta>;
1141
1234
 
1142
1235
  interface EventFluentBuilder<TPayload = void> {
1143
1236
  id: string;
@@ -1156,69 +1249,98 @@ interface EventFluentBuilder<TPayload = void> {
1156
1249
  parallel(enabled?: boolean): EventFluentBuilder<TPayload>;
1157
1250
  build(): IEvent<TPayload>;
1158
1251
  }
1159
- declare function eventBuilder(id: string): EventFluentBuilder<void>;
1160
1252
 
1161
- interface PhantomTaskFluentBuilder<TInput = undefined, TResolved = any, TDeps extends DependencyMapType = {}, TMeta extends ITaskMeta = ITaskMeta, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> {
1253
+ /**
1254
+ * Entry point for creating an event builder.
1255
+ */
1256
+ declare function eventBuilder<TPayload = void>(id: string): EventFluentBuilder<TPayload>;
1257
+
1258
+ type ShouldReplaceInput<T> = [T] extends [undefined] ? true : [T] extends [void] ? true : 0 extends 1 & T ? true : false;
1259
+ type ResolveInput<TExisting, TProposed> = ShouldReplaceInput<TExisting> extends true ? TProposed : TExisting;
1260
+
1261
+ /**
1262
+ * Fluent builder interface for constructing tasks.
1263
+ */
1264
+ 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[]> {
1162
1265
  id: string;
1163
1266
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | (() => TNewDeps), options?: {
1164
1267
  override?: false;
1165
- }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps & TNewDeps, TMeta, TTags, TMiddleware>;
1268
+ }): TaskFluentBuilder<TInput, TOutput, TDeps & TNewDeps, TMeta, TTags, TMiddleware>;
1166
1269
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | (() => TNewDeps), options: {
1167
1270
  override: true;
1168
- }): PhantomTaskFluentBuilder<TInput, TResolved, TNewDeps, TMeta, TTags, TMiddleware>;
1271
+ }): TaskFluentBuilder<TInput, TOutput, TNewDeps, TMeta, TTags, TMiddleware>;
1169
1272
  middleware<TNewMw extends TaskMiddlewareAttachmentType[]>(mw: TNewMw, options?: {
1170
1273
  override?: boolean;
1171
- }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, TTags, TNewMw>;
1274
+ }): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, TTags, TNewMw>;
1172
1275
  tags<TNewTags extends TagType[]>(t: TNewTags, options?: {
1173
1276
  override?: false;
1174
- }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, [
1277
+ }): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, [
1175
1278
  ...TTags,
1176
1279
  ...TNewTags
1177
1280
  ], TMiddleware>;
1178
1281
  tags<TNewTags extends TagType[]>(t: TNewTags, options: {
1179
1282
  override: true;
1180
- }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, TNewTags, TMiddleware>;
1181
- inputSchema<TNewInput>(schema: IValidationSchema<TNewInput>): PhantomTaskFluentBuilder<TNewInput, TResolved, TDeps, TMeta, TTags, TMiddleware>;
1182
- resultSchema<TNewResolved>(schema: IValidationSchema<TNewResolved>): PhantomTaskFluentBuilder<TInput, TNewResolved, TDeps, TMeta, TTags, TMiddleware>;
1183
- meta<TNewMeta extends ITaskMeta>(m: TNewMeta): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TNewMeta, TTags, TMiddleware>;
1184
- build(): IPhantomTask<TInput, TResolved, TDeps, TMeta, TTags, TMiddleware>;
1283
+ }): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, TNewTags, TMiddleware>;
1284
+ inputSchema<TNewInput>(schema: IValidationSchema<TNewInput>): TaskFluentBuilder<TNewInput, TOutput, TDeps, TMeta, TTags, TMiddleware>;
1285
+ resultSchema<TResolved>(schema: IValidationSchema<TResolved>): TaskFluentBuilder<TInput, Promise<TResolved>, TDeps, TMeta, TTags, TMiddleware>;
1286
+ 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>;
1287
+ throws(list: ThrowsList): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, TTags, TMiddleware>;
1288
+ meta<TNewMeta extends ITaskMeta>(m: TNewMeta): TaskFluentBuilder<TInput, TOutput, TDeps, TNewMeta, TTags, TMiddleware>;
1289
+ build(): ITask<TInput, TOutput, TDeps, TMeta, TTags, TMiddleware>;
1185
1290
  }
1186
1291
 
1187
- type ShouldReplaceInput<T> = [T] extends [undefined] ? true : [T] extends [void] ? true : (0 extends 1 & T ? true : false);
1188
- type ResolveInput<TExisting, TProposed> = ShouldReplaceInput<TExisting> extends true ? TProposed : TExisting;
1189
- 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[]> {
1292
+ /**
1293
+ * Fluent builder interface for constructing phantom tasks.
1294
+ */
1295
+ interface PhantomTaskFluentBuilder<TInput = undefined, TResolved = any, TDeps extends DependencyMapType = {}, TMeta extends ITaskMeta = ITaskMeta, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> {
1190
1296
  id: string;
1191
1297
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | (() => TNewDeps), options?: {
1192
1298
  override?: false;
1193
- }): TaskFluentBuilder<TInput, TOutput, TDeps & TNewDeps, TMeta, TTags, TMiddleware>;
1299
+ }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps & TNewDeps, TMeta, TTags, TMiddleware>;
1194
1300
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | (() => TNewDeps), options: {
1195
1301
  override: true;
1196
- }): TaskFluentBuilder<TInput, TOutput, TNewDeps, TMeta, TTags, TMiddleware>;
1302
+ }): PhantomTaskFluentBuilder<TInput, TResolved, TNewDeps, TMeta, TTags, TMiddleware>;
1197
1303
  middleware<TNewMw extends TaskMiddlewareAttachmentType[]>(mw: TNewMw, options?: {
1198
1304
  override?: boolean;
1199
- }): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, TTags, TNewMw>;
1305
+ }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, TTags, TNewMw>;
1200
1306
  tags<TNewTags extends TagType[]>(t: TNewTags, options?: {
1201
1307
  override?: false;
1202
- }): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, [
1308
+ }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, [
1203
1309
  ...TTags,
1204
1310
  ...TNewTags
1205
1311
  ], TMiddleware>;
1206
1312
  tags<TNewTags extends TagType[]>(t: TNewTags, options: {
1207
1313
  override: true;
1208
- }): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, TNewTags, TMiddleware>;
1209
- inputSchema<TNewInput>(schema: IValidationSchema<TNewInput>): TaskFluentBuilder<TNewInput, TOutput, TDeps, TMeta, TTags, TMiddleware>;
1210
- resultSchema<TResolved>(schema: IValidationSchema<TResolved>): TaskFluentBuilder<TInput, Promise<TResolved>, TDeps, TMeta, TTags, TMiddleware>;
1211
- 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>;
1212
- meta<TNewMeta extends ITaskMeta>(m: TNewMeta): TaskFluentBuilder<TInput, TOutput, TDeps, TNewMeta, TTags, TMiddleware>;
1213
- build(): ITask<TInput, TOutput, TDeps, TMeta, TTags, TMiddleware>;
1314
+ }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, TNewTags, TMiddleware>;
1315
+ inputSchema<TNewInput>(schema: IValidationSchema<TNewInput>): PhantomTaskFluentBuilder<TNewInput, TResolved, TDeps, TMeta, TTags, TMiddleware>;
1316
+ resultSchema<TNewResolved>(schema: IValidationSchema<TNewResolved>): PhantomTaskFluentBuilder<TInput, TNewResolved, TDeps, TMeta, TTags, TMiddleware>;
1317
+ meta<TNewMeta extends ITaskMeta>(m: TNewMeta): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TNewMeta, TTags, TMiddleware>;
1318
+ throws(list: ThrowsList): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, TTags, TMiddleware>;
1319
+ build(): IPhantomTask<TInput, TResolved, TDeps, TMeta, TTags, TMiddleware>;
1214
1320
  }
1321
+
1322
+ /**
1323
+ * Entry point for creating a phantom task builder.
1324
+ */
1325
+ declare function phantomTaskBuilder<TInput = undefined, TResolved = any>(id: string): PhantomTaskFluentBuilder<TInput, TResolved, {}, ITaskMeta, TagType[], TaskMiddlewareAttachmentType[]>;
1215
1326
  interface TaskBuilderWithPhantom {
1216
1327
  (id: string): TaskFluentBuilder<undefined, Promise<any>, {}, ITaskMeta, TagType[], TaskMiddlewareAttachmentType[]>;
1217
- phantom: <TInput = undefined, TResolved = any>(id: string) => PhantomTaskFluentBuilder<TInput, TResolved, {}, ITaskMeta, TagType[], TaskMiddlewareAttachmentType[]>;
1328
+ phantom: typeof phantomTaskBuilder;
1218
1329
  }
1219
1330
 
1331
+ /**
1332
+ * Helper type to determine if config should be replaced.
1333
+ */
1220
1334
  type ShouldReplaceConfig<T> = [T] extends [void] ? true : [T] extends [undefined] ? true : false;
1335
+ /**
1336
+ * Resolves the config type - uses proposed if existing is void/undefined.
1337
+ */
1221
1338
  type ResolveConfig<TExisting, TProposed> = ShouldReplaceConfig<TExisting> extends true ? TProposed : TExisting;
1339
+
1340
+ /**
1341
+ * Fluent builder interface for constructing resources.
1342
+ * Each method returns a new builder with updated type parameters.
1343
+ */
1222
1344
  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[]> {
1223
1345
  id: string;
1224
1346
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | ((config: TConfig) => TNewDeps), options?: {
@@ -1248,19 +1370,220 @@ interface ResourceFluentBuilder<TConfig = void, TValue extends Promise<any> = Pr
1248
1370
  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>;
1249
1371
  dispose(fn: NonNullable<IResourceDefinition<TConfig, TValue, TDeps, TContext, any, any, TMeta, TTags, TMiddleware>["dispose"]>): ResourceFluentBuilder<TConfig, TValue, TDeps, TContext, TMeta, TTags, TMiddleware>;
1250
1372
  meta<TNewMeta extends IResourceMeta>(m: TNewMeta): ResourceFluentBuilder<TConfig, TValue, TDeps, TContext, TNewMeta, TTags, TMiddleware>;
1373
+ throws(list: ThrowsList): ResourceFluentBuilder<TConfig, TValue, TDeps, TContext, TMeta, TTags, TMiddleware>;
1251
1374
  overrides(o: Array<OverridableElements>, options?: {
1252
1375
  override?: boolean;
1253
1376
  }): ResourceFluentBuilder<TConfig, TValue, TDeps, TContext, TMeta, TTags, TMiddleware>;
1254
1377
  build(): IResource<TConfig, TValue, TDeps, TContext, TMeta, TTags, TMiddleware>;
1255
1378
  }
1256
- declare function resourceBuilder<TConfig = void>(id: string): ResourceFluentBuilder<TConfig, Promise<any>, {}, any, IResourceMeta, TagType[], ResourceMiddlewareAttachmentType[]>;
1257
-
1258
- interface Serializer {
1379
+
1380
+ /**
1381
+ * Creates a new resource builder with the given id.
1382
+ * Overload allows callers to seed the config type at the entry point for convenience.
1383
+ */
1384
+ declare function resourceBuilder<TConfig = void>(id: string): ResourceFluentBuilder<TConfig, Promise<any>, {}, any, IResourceMeta, TagType[], ResourceMiddlewareAttachmentType[]>;
1385
+
1386
+ /**
1387
+ * Type definitions for the Serializer class
1388
+ */
1389
+ /**
1390
+ * Definition for a custom type that can be serialized/deserialized
1391
+ */
1392
+ interface TypeDefinition<TInstance = unknown, TSerialized = unknown> {
1393
+ /** Unique identifier for the type */
1394
+ id: string;
1395
+ /** Predicate function to check if an object matches this type */
1396
+ is: (obj: unknown) => obj is TInstance;
1397
+ /** Function to serialize the object */
1398
+ serialize: (obj: TInstance) => TSerialized;
1399
+ /** Function to deserialize the data back to the original object */
1400
+ deserialize: (data: TSerialized) => TInstance;
1401
+ /** Optional factory used to create a placeholder during deserialization */
1402
+ create?: () => TInstance;
1403
+ /** Serialization strategy: 'value' (inline, no identity) or 'ref' (graph node, identity preserved). Default: 'ref' */
1404
+ strategy?: "value" | "ref";
1405
+ }
1406
+ /** Reference to another object in the serialization */
1407
+ interface ObjectReference {
1408
+ /** Reference to object ID */
1409
+ __ref: string;
1410
+ }
1411
+ /**
1412
+ * Discriminated union describing the serialized graph payload.
1413
+ * Each node captures either an array, plain object, or typed payload.
1414
+ */
1415
+ type SerializedNode = {
1416
+ kind: "array";
1417
+ value: SerializedValue[];
1418
+ } | {
1419
+ kind: "object";
1420
+ value: Record<string, SerializedValue>;
1421
+ } | {
1422
+ kind: "type";
1423
+ type: string;
1424
+ value: SerializedValue;
1425
+ };
1426
+ /**
1427
+ * Serialization context for tracking object references
1428
+ */
1429
+ interface SerializationContext {
1430
+ /** Map of objects to their IDs */
1431
+ objectIds: WeakMap<object, string>;
1432
+ /** Counter for generating unique IDs */
1433
+ idCounter: number;
1434
+ /** Number of graph nodes recorded */
1435
+ nodeCount: number;
1436
+ /** Nodes collected during serialization (id -> serialized node) */
1437
+ nodes: Record<string, SerializedNode>;
1438
+ }
1439
+ /**
1440
+ * Deserialization context used when materialising a graph payload.
1441
+ */
1442
+ interface DeserializationContext {
1443
+ nodes: Record<string, SerializedNode>;
1444
+ resolved: Map<string, unknown>;
1445
+ resolving: Set<string>;
1446
+ /**
1447
+ * Tracks reference ids that were requested while still being resolved.
1448
+ * Used to detect circular references that rely on placeholders.
1449
+ */
1450
+ resolvingRefs: Set<string>;
1451
+ }
1452
+ /**
1453
+ * Union type for serialized values
1454
+ */
1455
+ type JsonPrimitive = string | number | boolean | null;
1456
+ interface SerializedTypeRecord {
1457
+ __type: string;
1458
+ value: SerializedValue;
1459
+ }
1460
+ type SerializedValue = JsonPrimitive | ObjectReference | SerializedTypeRecord | SerializedValue[] | {
1461
+ [key: string]: SerializedValue;
1462
+ };
1463
+ declare enum SymbolPolicy {
1464
+ AllowAll = "AllowAll",
1465
+ WellKnownOnly = "WellKnownOnly",
1466
+ Disabled = "Disabled"
1467
+ }
1468
+ /**
1469
+ * Main serializer options
1470
+ */
1471
+ interface SerializerOptions {
1472
+ /** Whether to pretty-print JSON (for debugging) */
1473
+ pretty?: boolean;
1474
+ /** Maximum recursion depth allowed during serialize/deserialize */
1475
+ maxDepth?: number;
1476
+ /** Restrict deserialization to this list of type IDs */
1477
+ allowedTypes?: readonly string[];
1478
+ /** Controls which Symbol payloads may be deserialized */
1479
+ symbolPolicy?: SymbolPolicy;
1480
+ /** Maximum accepted RegExp pattern length during deserialization */
1481
+ maxRegExpPatternLength?: number;
1482
+ /** Allow RegExp patterns that fail the safety heuristic */
1483
+ allowUnsafeRegExp?: boolean;
1484
+ }
1485
+ /**
1486
+ * Minimal serializer contract used across transports and persistence.
1487
+ * Implementations must be able to round-trip JSON-compatible payloads and
1488
+ * should support custom value types via `addType`.
1489
+ */
1490
+ interface SerializerLike {
1259
1491
  stringify(value: unknown): string;
1260
1492
  parse<T = unknown>(text: string): T;
1261
- addType?<TJson = unknown, T = unknown>(name: string, factory: (json: TJson) => T): void;
1493
+ addType?<TJson = unknown, TInstance = unknown>(name: string, factory: (json: TJson) => TInstance): void;
1494
+ }
1495
+
1496
+ /**
1497
+ * Graph-aware serializer/deserializer with circular reference
1498
+ * handling and pluggable type support.
1499
+ *
1500
+ * Internal protocol reference: `readmes/SERIALIZER_PROTOCOL.md`.
1501
+ */
1502
+
1503
+ declare class Serializer {
1504
+ /** Type registry for managing custom types */
1505
+ private readonly typeRegistry;
1506
+ private readonly runtimeOptions;
1507
+ /** JSON indentation width when pretty printing is enabled */
1508
+ private readonly indent;
1509
+ /** Maximum recursion depth allowed */
1510
+ private readonly maxDepth;
1511
+ /** Maximum allowed RegExp pattern length during deserialization */
1512
+ private readonly maxRegExpPatternLength;
1513
+ /** Allow RegExp patterns that fail the safety heuristic */
1514
+ private readonly allowUnsafeRegExp;
1515
+ /** Disallowed keys that can lead to prototype pollution */
1516
+ private readonly unsafeKeys;
1517
+ constructor(options?: SerializerOptions);
1518
+ /**
1519
+ * Alias of `serialize()` to match the historical tunnel serializer surface.
1520
+ */
1521
+ stringify<T>(value: T): string;
1522
+ /**
1523
+ * Alias of `deserialize()` to match the historical tunnel serializer surface.
1524
+ */
1525
+ parse<T = unknown>(payload: string): T;
1526
+ /**
1527
+ * Serialize an arbitrary value into a JSON string.
1528
+ */
1529
+ serialize<T>(value: T, context?: SerializationContext): string;
1530
+ /**
1531
+ * Deserialize a JSON string back to its original value.
1532
+ */
1533
+ deserialize<T = unknown>(payload: string): T;
1534
+ /**
1535
+ * Register a custom type for serialization/deserialization.
1536
+ */
1537
+ addType<TInstance, TSerialized>(typeDef: TypeDefinition<TInstance, TSerialized>): void;
1538
+ addType<TJson = unknown, TInstance = unknown>(name: string, factory: (json: TJson) => TInstance): void;
1539
+ /**
1540
+ * @internal - Exposed for testing RegExp safety validation
1541
+ */
1542
+ readonly isRegExpPatternSafe: (pattern: string) => boolean;
1543
+ /**
1544
+ * @internal - Exposed for testing quantifier detection
1545
+ */
1546
+ readonly isQuantifierAt: (pattern: string, index: number) => boolean;
1547
+ /**
1548
+ * @internal - Exposed for testing quantifier character detection
1549
+ */
1550
+ readonly isQuantifierChar: (char: string, pattern: string, index: number) => boolean;
1551
+ /**
1552
+ * @internal - Exposed for testing bounded quantifier detection
1553
+ */
1554
+ readonly isBoundedQuantifier: (pattern: string, index: number) => boolean;
1555
+ /**
1556
+ * @internal - Exposed for test compatibility
1557
+ */
1558
+ toNodeRecord(nodes: Record<string, SerializedNode>): Record<string, SerializedNode>;
1559
+ /**
1560
+ * @internal - Exposed for test compatibility
1561
+ */
1562
+ deserializeValue(value: SerializedValue, context: DeserializationContext, depth?: number): unknown;
1563
+ /**
1564
+ * @internal - Exposed for test compatibility
1565
+ */
1566
+ resolveReference(id: string, context: DeserializationContext, depth?: number): unknown;
1567
+ /**
1568
+ * @internal - Exposed for test compatibility
1569
+ */
1570
+ mergePlaceholder(placeholder: unknown, result: unknown): unknown;
1571
+ /**
1572
+ * @internal - Exposed for test compatibility
1573
+ */
1574
+ isSerializedTypeRecord(value: unknown): value is {
1575
+ __type: string;
1576
+ value: unknown;
1577
+ };
1578
+ private jsonStringify;
1262
1579
  }
1263
1580
 
1581
+ /**
1582
+ * Main export module for the Serializer
1583
+ */
1584
+
1585
+ declare function getDefaultSerializer(): Serializer;
1586
+
1264
1587
  type TunnelMode = "client" | "server" | "both" | "none";
1265
1588
  type TunnelTaskSelector = Array<string | ITask<any, any, any, any, any, any>> | ((task: ITask<any, any, any, any, any, any>) => boolean);
1266
1589
  type TunnelEventSelector = Array<string | IEvent<any>> | ((event: IEvent<any>) => boolean);
@@ -1286,17 +1609,23 @@ interface ExposureFetchConfig {
1286
1609
  auth?: ExposureFetchAuthConfig;
1287
1610
  timeoutMs?: number;
1288
1611
  fetchImpl?: typeof fetch;
1289
- serializer: Serializer;
1612
+ serializer: SerializerLike;
1290
1613
  onRequest?: (ctx: {
1291
1614
  url: string;
1292
1615
  headers: Record<string, string>;
1293
1616
  }) => void | Promise<void>;
1294
- contexts?: Array<IAsyncContext<any>>;
1617
+ contexts?: Array<IAsyncContext<unknown>>;
1295
1618
  errorRegistry?: Map<string, IErrorHelper<any>>;
1296
1619
  }
1297
1620
  interface ExposureFetchClient {
1298
1621
  task<I = unknown, O = unknown>(id: string, input?: I): Promise<O>;
1299
1622
  event<P = unknown>(id: string, payload?: P): Promise<void>;
1623
+ /**
1624
+ * Emits an event and returns the final payload as seen by the remote Runner.
1625
+ * Requires server support; older servers will respond with `{ ok: true }`
1626
+ * without `result`, in which case clients should throw.
1627
+ */
1628
+ eventWithResult?<P = unknown>(id: string, payload?: P): Promise<P>;
1300
1629
  }
1301
1630
 
1302
1631
  declare function normalizeError(input: unknown): Error;
@@ -1319,7 +1648,7 @@ interface HttpCreateClientConfig {
1319
1648
  auth?: HttpClientAuthConfig;
1320
1649
  timeoutMs?: number;
1321
1650
  fetchImpl?: typeof fetch;
1322
- serializer: Serializer;
1651
+ serializer: SerializerLike;
1323
1652
  onRequest?: (ctx: {
1324
1653
  url: string;
1325
1654
  headers: Record<string, string>;
@@ -1327,19 +1656,27 @@ interface HttpCreateClientConfig {
1327
1656
  }
1328
1657
 
1329
1658
  type TunnelMiddlewareId = string | ITaskMiddleware<any, any, any, any>;
1659
+ interface TunnelTaskMiddlewareSidePolicy {
1660
+ /**
1661
+ * Middleware ids/definitions allowed to run on this side when the task is tunneled.
1662
+ * If omitted, defaults to allowing none (caller-side middleware is skipped by default).
1663
+ */
1664
+ middlewareAllowList?: TunnelMiddlewareId[];
1665
+ }
1666
+ type TunnelTaskMiddlewarePolicySideConfig = TunnelTaskMiddlewareSidePolicy | TunnelMiddlewareId[];
1330
1667
  interface TunnelTaskMiddlewarePolicyConfig {
1331
1668
  /**
1332
- * Whitelist of middleware ids/definitions allowed to run on the caller side
1333
- * when the task is tunneled (mode: "client"). If omitted, defaults to
1334
- * allowing all (the framework default remains "both").
1669
+ * Preferred configuration shape: explicit per-side allowlist.
1335
1670
  */
1336
- client?: TunnelMiddlewareId[];
1671
+ client?: TunnelTaskMiddlewarePolicySideConfig;
1672
+ server?: TunnelTaskMiddlewarePolicySideConfig;
1337
1673
  /**
1338
- * Whitelist of middleware ids/definitions intended to run on the executor side.
1339
- * Note: The local runner cannot enforce server-side policy; this is a declarative
1340
- * contract that a Runner-based executor can consume to apply a symmetric filter.
1674
+ * Backwards-compatible configuration shape (previous): grouped allowlists.
1341
1675
  */
1342
- server?: TunnelMiddlewareId[];
1676
+ middlewareAllowList?: {
1677
+ client?: TunnelMiddlewareId[];
1678
+ server?: TunnelMiddlewareId[];
1679
+ };
1343
1680
  }
1344
1681
 
1345
1682
  interface TimeoutMiddlewareConfig {
@@ -1370,6 +1707,182 @@ interface RetryMiddlewareConfig {
1370
1707
  delayStrategy?: (attempt: number, error: Error) => number;
1371
1708
  }
1372
1709
 
1710
+ interface FallbackMiddlewareConfig {
1711
+ /**
1712
+ * The fallback to use if the task fails.
1713
+ * Can be a value, a function that returns a value (or promise), or another task.
1714
+ */
1715
+ fallback: any;
1716
+ }
1717
+
1718
+ declare const SemaphoreEvents: {
1719
+ readonly queued: IEvent<SemaphoreEvent>;
1720
+ readonly acquired: IEvent<SemaphoreEvent>;
1721
+ readonly released: IEvent<SemaphoreEvent>;
1722
+ readonly timeout: IEvent<SemaphoreEvent>;
1723
+ readonly aborted: IEvent<SemaphoreEvent>;
1724
+ readonly disposed: IEvent<SemaphoreEvent>;
1725
+ };
1726
+ type SemaphoreEventType = keyof typeof SemaphoreEvents;
1727
+ type SemaphoreEvent = {
1728
+ type: SemaphoreEventType;
1729
+ permits: number;
1730
+ waiting: number;
1731
+ maxPermits: number;
1732
+ disposed: boolean;
1733
+ };
1734
+ /**
1735
+ * A semaphore that limits the number of concurrent operations.
1736
+ * Used to prevent connection pool exhaustion by limiting concurrent
1737
+ * database operations to the pool size.
1738
+ */
1739
+ declare class Semaphore {
1740
+ private permits;
1741
+ private waitingHead;
1742
+ private waitingTail;
1743
+ private waitingCount;
1744
+ private disposed;
1745
+ private readonly maxPermits;
1746
+ private readonly eventManager;
1747
+ private listenerId;
1748
+ private activeListeners;
1749
+ constructor(maxPermits: number);
1750
+ /**
1751
+ * Acquire a permit. If no permits are available, waits until one becomes available.
1752
+ */
1753
+ acquire(options?: {
1754
+ timeout?: number;
1755
+ signal?: AbortSignal;
1756
+ }): Promise<void>;
1757
+ /**
1758
+ * Release a permit, allowing waiting operations to proceed.
1759
+ */
1760
+ release(): void;
1761
+ private removeFromQueue;
1762
+ /**
1763
+ * Execute a function with a permit, automatically releasing it afterwards.
1764
+ */
1765
+ withPermit<T>(fn: () => Promise<T>, options?: {
1766
+ timeout?: number;
1767
+ signal?: AbortSignal;
1768
+ }): Promise<T>;
1769
+ /**
1770
+ * Dispose the semaphore, rejecting all waiting operations and preventing new ones.
1771
+ */
1772
+ dispose(): void;
1773
+ /**
1774
+ * Get current number of available permits (for debugging)
1775
+ */
1776
+ getAvailablePermits(): number;
1777
+ /**
1778
+ * Get current number of waiting operations (for debugging)
1779
+ */
1780
+ getWaitingCount(): number;
1781
+ /**
1782
+ * Get maximum number of permits
1783
+ */
1784
+ getMaxPermits(): number;
1785
+ /**
1786
+ * Check if the semaphore has been disposed
1787
+ */
1788
+ isDisposed(): boolean;
1789
+ /**
1790
+ * Get metrics about the current state of the semaphore
1791
+ */
1792
+ getMetrics(): {
1793
+ availablePermits: number;
1794
+ waitingCount: number;
1795
+ maxPermits: number;
1796
+ utilization: number;
1797
+ disposed: boolean;
1798
+ };
1799
+ on(type: SemaphoreEventType, handler: (event: SemaphoreEvent) => any): () => void;
1800
+ once(type: SemaphoreEventType, handler: (event: SemaphoreEvent) => any): () => void;
1801
+ private enqueue;
1802
+ private dequeue;
1803
+ private emit;
1804
+ private buildEvent;
1805
+ }
1806
+
1807
+ interface ConcurrencyMiddlewareConfig {
1808
+ /**
1809
+ * Maximum number of concurrent executions.
1810
+ * If provided, a Semaphore will be created and shared for this config object.
1811
+ */
1812
+ limit?: number;
1813
+ /**
1814
+ * Optional key to identify a shared semaphore.
1815
+ * If provided, the semaphore will be shared across all tasks using the same key.
1816
+ */
1817
+ key?: string;
1818
+ /**
1819
+ * An existing Semaphore instance to use.
1820
+ */
1821
+ semaphore?: Semaphore;
1822
+ }
1823
+
1824
+ interface TemporalMiddlewareConfig {
1825
+ ms: number;
1826
+ }
1827
+ interface DebounceState {
1828
+ timeoutId?: NodeJS.Timeout;
1829
+ latestInput?: any;
1830
+ resolveList: ((value: any) => void)[];
1831
+ rejectList: ((error: any) => void)[];
1832
+ }
1833
+ interface ThrottleState {
1834
+ lastExecution: number;
1835
+ timeoutId?: NodeJS.Timeout;
1836
+ latestInput?: any;
1837
+ resolveList: ((value: any) => void)[];
1838
+ rejectList: ((error: any) => void)[];
1839
+ currentPromise?: Promise<any>;
1840
+ }
1841
+
1842
+ /**
1843
+ * States of the Circuit Breaker
1844
+ */
1845
+ declare enum CircuitBreakerState {
1846
+ CLOSED = "CLOSED",
1847
+ OPEN = "OPEN",
1848
+ HALF_OPEN = "HALF_OPEN"
1849
+ }
1850
+ /**
1851
+ * Configuration for the Circuit Breaker middleware
1852
+ */
1853
+ interface CircuitBreakerMiddlewareConfig {
1854
+ /**
1855
+ * Number of failures before tripping the circuit
1856
+ * @default 5
1857
+ */
1858
+ failureThreshold?: number;
1859
+ /**
1860
+ * Time in milliseconds before transitioning from OPEN to HALF_OPEN
1861
+ * @default 30000 (30 seconds)
1862
+ */
1863
+ resetTimeout?: number;
1864
+ }
1865
+ interface CircuitBreakerStatus {
1866
+ state: CircuitBreakerState;
1867
+ failures: number;
1868
+ lastFailureTime: number;
1869
+ }
1870
+
1871
+ interface RateLimitMiddlewareConfig {
1872
+ /**
1873
+ * Time window in milliseconds
1874
+ */
1875
+ windowMs: number;
1876
+ /**
1877
+ * Maximum number of requests within the window
1878
+ */
1879
+ max: number;
1880
+ }
1881
+ interface RateLimitState {
1882
+ count: number;
1883
+ resetTime: number;
1884
+ }
1885
+
1373
1886
  /**
1374
1887
  * Options for configuring event listeners.
1375
1888
  */
@@ -1404,9 +1917,9 @@ declare class EventManager {
1404
1917
  private hookInterceptors;
1405
1918
  private readonly registry;
1406
1919
  private readonly cycleContext;
1407
- private readonly runtimeCycleDetection;
1920
+ private readonly runtimeEventCycleDetection;
1408
1921
  constructor(options?: {
1409
- runtimeCycleDetection?: boolean;
1922
+ runtimeEventCycleDetection?: boolean;
1410
1923
  });
1411
1924
  /**
1412
1925
  * Gets the current lock status of the EventManager
@@ -1425,6 +1938,16 @@ declare class EventManager {
1425
1938
  * @param source - The source identifier of the event emitter
1426
1939
  */
1427
1940
  emit<TInput>(eventDefinition: IEvent<TInput>, data: TInput, source: string): Promise<void>;
1941
+ /**
1942
+ * Emits an event and returns the final payload.
1943
+ * The payload is taken from the deepest emission object that reached either:
1944
+ * - the base listener executor, or
1945
+ * - an interceptor that short-circuited the emission.
1946
+ *
1947
+ * This enables tunnel transports to return the final payload after local and/or remote delivery.
1948
+ */
1949
+ emitWithResult<TInput>(eventDefinition: IEvent<TInput>, data: TInput, source: string): Promise<TInput>;
1950
+ private emitAndReturnEmission;
1428
1951
  /**
1429
1952
  * Registers an event listener for specific event(s).
1430
1953
  * Listeners are ordered by priority and executed in ascending order.
@@ -1479,6 +2002,16 @@ declare class EventManager {
1479
2002
  * Throws an error if the EventManager is locked
1480
2003
  */
1481
2004
  private checkLock;
2005
+ /**
2006
+ * Clears all listeners and interceptors.
2007
+ * Call this to release references and free memory.
2008
+ */
2009
+ clear(): void;
2010
+ /**
2011
+ * Disposes the EventManager, releasing all listeners and interceptors.
2012
+ * Alias for clear() following the IResource disposal pattern.
2013
+ */
2014
+ dispose(): void;
1482
2015
  /**
1483
2016
  * Retrieves cached merged listeners for an event, or creates them if not cached.
1484
2017
  * Kept for backward compatibility (tests spy on this).
@@ -1490,7 +2023,7 @@ declare class TaskRunner {
1490
2023
  protected readonly store: Store;
1491
2024
  protected readonly eventManager: EventManager;
1492
2025
  protected readonly logger: Logger;
1493
- protected readonly runnerStore: Map<string | symbol, (input: any) => Promise<any>>;
2026
+ protected readonly runnerStore: Map<string | symbol, (input: any, journal?: ExecutionJournal) => Promise<any>>;
1494
2027
  constructor(store: Store, eventManager: EventManager, logger: Logger);
1495
2028
  private readonly middlewareManager;
1496
2029
  /**
@@ -1498,8 +2031,9 @@ declare class TaskRunner {
1498
2031
  * This function can throw only if any of the event listeners or run function throws
1499
2032
  * @param task the task to be run
1500
2033
  * @param input the input to be passed to the task
2034
+ * @param options optional call options including journal for forwarding
1501
2035
  */
1502
- run<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>, input?: TInput): Promise<TOutput | undefined>;
2036
+ run<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>, input?: TInput, options?: TaskCallOptions): Promise<TOutput | undefined>;
1503
2037
  /**
1504
2038
  * Creates the function with the chain of middleware.
1505
2039
  * @param task
@@ -1507,7 +2041,7 @@ declare class TaskRunner {
1507
2041
  * @param taskDependencies
1508
2042
  * @returns
1509
2043
  */
1510
- protected createRunnerWithMiddleware<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>): (input: TInput) => Promise<Awaited<TOutput>>;
2044
+ protected createRunnerWithMiddleware<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>): (input: TInput, parentJournal?: ExecutionJournal) => Promise<Awaited<TOutput>>;
1511
2045
  }
1512
2046
 
1513
2047
  /**
@@ -1571,7 +2105,7 @@ declare class MiddlewareManager {
1571
2105
  * Compose a runner for a task with its local interceptors and applicable middlewares.
1572
2106
  * Returns a function that accepts the task input and resolves to the task output.
1573
2107
  */
1574
- composeTaskRunner<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>): (input: TInput) => Promise<Awaited<TOutput>>;
2108
+ composeTaskRunner<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>): (input: TInput, parentJournal?: ExecutionJournal) => Promise<Awaited<TOutput>>;
1575
2109
  /**
1576
2110
  * Run a resource init wrapped with its applicable middlewares.
1577
2111
  */
@@ -1602,6 +2136,7 @@ declare class Store {
1602
2136
  private validator;
1603
2137
  private taskRunner?;
1604
2138
  private middlewareManager;
2139
+ private readonly initializedResourceIds;
1605
2140
  mode: RunnerMode;
1606
2141
  constructor(eventManager: EventManager, logger: Logger, onUnhandledError: OnUnhandledError, mode?: RunnerMode);
1607
2142
  get tasks(): Map<string, TaskStoreElementType>;
@@ -1613,7 +2148,7 @@ declare class Store {
1613
2148
  get taskMiddlewares(): Map<string, TaskMiddlewareStoreElementType>;
1614
2149
  get resourceMiddlewares(): Map<string, ResourceMiddlewareStoreElementType>;
1615
2150
  get tags(): Map<string, ITag<void, void, void>>;
1616
- get overrides(): Map<string, IResourceMiddleware<any, void, void, any> | ITask<any, any, {}, any, TagType[], TaskMiddlewareAttachmentType[]> | IHook<{}, any, any> | IResource<void, Promise<any>, any, any, any, TagType[], ResourceMiddlewareAttachmentType[]> | ITaskMiddleware<any, void, void, any> | IResourceWithConfig<any, Promise<any>, any, any, any, TagType[], IResourceMiddleware<any, void, void, any>[]>>;
2151
+ get overrides(): Map<string, ITask<any, any, {}, any, TagType[], TaskMiddlewareAttachmentType[]> | IResourceMiddleware<any, void, void, any> | IHook<{}, any, any> | IResource<void, Promise<any>, any, any, any, TagType[], ResourceMiddlewareAttachmentType[]> | ITaskMiddleware<any, void, void, any> | IResourceWithConfig<any, Promise<any>, any, any, any, TagType[], IResourceMiddleware<any, void, void, any>[]>>;
1617
2152
  get overrideRequests(): Set<{
1618
2153
  source: string;
1619
2154
  override: RegisterableItems;
@@ -1629,6 +2164,8 @@ declare class Store {
1629
2164
  validateEventEmissionGraph(): void;
1630
2165
  initializeStore(root: IResource<any, any, any, any, any>, config: any): void;
1631
2166
  dispose(): Promise<void>;
2167
+ recordResourceInitialized(resourceId: string): void;
2168
+ private getResourcesInDisposeOrder;
1632
2169
  /**
1633
2170
  * Internal, avoid using this method directly.
1634
2171
  */
@@ -1664,16 +2201,14 @@ declare class ResourceInitializer {
1664
2201
  * This function can throw only if any of the event listeners or run function throws
1665
2202
  */
1666
2203
  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<{
1667
- value: TValue;
2204
+ value: TValue | undefined;
1668
2205
  context: TContext;
1669
2206
  }>;
1670
2207
  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>;
1671
2208
  }
1672
2209
 
1673
2210
  /**
1674
- * This class is responsible of setting up dependencies with their respective computedValues.
1675
- * Note that all elements must have been previously registered otherwise errors will be thrown
1676
- * when trying to depend on something not in the store.
2211
+ * Resolves and caches computed dependencies for store items (resources, tasks, middleware, hooks).
1677
2212
  */
1678
2213
  declare class DependencyProcessor {
1679
2214
  protected readonly store: Store;
@@ -1683,21 +2218,21 @@ declare class DependencyProcessor {
1683
2218
  protected readonly logger: Logger;
1684
2219
  constructor(store: Store, eventManager: EventManager, taskRunner: TaskRunner, logger: Logger);
1685
2220
  /**
1686
- * This function is going to go through all the resources, tasks and middleware to compute their required dependencies.
2221
+ * Computes and caches dependencies for all registered store items.
1687
2222
  */
1688
2223
  computeAllDependencies(): Promise<void>;
1689
2224
  private computeTaskDependencies;
1690
2225
  initializeUninitializedResources(): Promise<void>;
2226
+ private rethrowResourceInitError;
1691
2227
  /**
1692
- * Processes dependencies and hooks
1693
- * @param resource
2228
+ * Computes and caches dependencies for a resource (if not already computed).
1694
2229
  */
1695
2230
  protected processResourceDependencies<TD extends DependencyMapType>(resource: ResourceStoreElementType<any, any, TD>): Promise<void>;
1696
2231
  private wrapResourceDependencies;
1697
2232
  private makeTaskWithIntercept;
1698
2233
  initializeRoot(): Promise<void>;
1699
2234
  /**
1700
- * Processes all hooks, should run before emission of any event.
2235
+ * Attaches listeners for all hooks. Must run before emitting events.
1701
2236
  */
1702
2237
  attachListeners(): void;
1703
2238
  extractDependencies<T extends DependencyMapType>(map: T, source: string): Promise<DependencyValuesType<T>>;
@@ -1708,72 +2243,25 @@ declare class DependencyProcessor {
1708
2243
  * @returns
1709
2244
  */
1710
2245
  extractEventDependency(object: IEvent<any>, source: string): (input: any) => Promise<void>;
1711
- extractTaskDependency(object: ITask<any, any, {}>): Promise<(input: unknown) => Promise<any>>;
2246
+ extractTaskDependency(object: ITask<any, any, {}>): Promise<(input: unknown, options?: TaskCallOptions) => Promise<any>>;
1712
2247
  extractResourceDependency(object: IResource<any, any, any>): Promise<any>;
1713
2248
  }
1714
2249
 
1715
- /**
1716
- * A semaphore that limits the number of concurrent operations.
1717
- * Used to prevent connection pool exhaustion by limiting concurrent
1718
- * database operations to the pool size.
1719
- */
1720
- declare class Semaphore {
1721
- private permits;
1722
- private readonly waitingQueue;
1723
- private disposed;
1724
- private readonly maxPermits;
1725
- constructor(maxPermits: number);
1726
- /**
1727
- * Acquire a permit. If no permits are available, waits until one becomes available.
1728
- */
1729
- acquire(options?: {
1730
- timeout?: number;
1731
- signal?: AbortSignal;
1732
- }): Promise<void>;
1733
- /**
1734
- * Release a permit, allowing waiting operations to proceed.
1735
- */
1736
- release(): void;
1737
- private removeFromQueue;
1738
- /**
1739
- * Execute a function with a permit, automatically releasing it afterwards.
1740
- */
1741
- withPermit<T>(fn: () => Promise<T>, options?: {
1742
- timeout?: number;
1743
- signal?: AbortSignal;
1744
- }): Promise<T>;
1745
- /**
1746
- * Dispose the semaphore, rejecting all waiting operations and preventing new ones.
1747
- */
1748
- dispose(): void;
1749
- /**
1750
- * Get current number of available permits (for debugging)
1751
- */
1752
- getAvailablePermits(): number;
1753
- /**
1754
- * Get current number of waiting operations (for debugging)
1755
- */
1756
- getWaitingCount(): number;
1757
- /**
1758
- * Get maximum number of permits
1759
- */
1760
- getMaxPermits(): number;
1761
- /**
1762
- * Check if the semaphore has been disposed
1763
- */
1764
- isDisposed(): boolean;
1765
- /**
1766
- * Get metrics about the current state of the semaphore
1767
- */
1768
- getMetrics(): {
1769
- availablePermits: number;
1770
- waitingCount: number;
1771
- maxPermits: number;
1772
- utilization: number;
1773
- disposed: boolean;
1774
- };
1775
- }
1776
-
2250
+ declare const QueueEvents: {
2251
+ readonly enqueue: IEvent<QueueEvent>;
2252
+ readonly start: IEvent<QueueEvent>;
2253
+ readonly finish: IEvent<QueueEvent>;
2254
+ readonly error: IEvent<QueueEvent>;
2255
+ readonly cancel: IEvent<QueueEvent>;
2256
+ readonly disposed: IEvent<QueueEvent>;
2257
+ };
2258
+ type QueueEventType = keyof typeof QueueEvents;
2259
+ type QueueEvent = {
2260
+ type: QueueEventType;
2261
+ taskId: number;
2262
+ disposed: boolean;
2263
+ error?: Error;
2264
+ };
1777
2265
  /**
1778
2266
  * Cooperative task queue.
1779
2267
  * • Tasks run one‑after‑another (FIFO ordering).
@@ -1784,6 +2272,10 @@ declare class Queue {
1784
2272
  private tail;
1785
2273
  private disposed;
1786
2274
  private abortController;
2275
+ private readonly eventManager;
2276
+ private nextTaskId;
2277
+ private listenerId;
2278
+ private activeListeners;
1787
2279
  private readonly executionContext;
1788
2280
  private readonly hasAsyncLocalStorage;
1789
2281
  /**
@@ -1799,6 +2291,9 @@ declare class Queue {
1799
2291
  dispose(options?: {
1800
2292
  cancel?: boolean;
1801
2293
  }): Promise<void>;
2294
+ on(type: QueueEventType, handler: (event: QueueEvent) => any): () => void;
2295
+ once(type: QueueEventType, handler: (event: QueueEvent) => any): () => void;
2296
+ private emit;
1802
2297
  }
1803
2298
 
1804
2299
  declare class RunResult<V> {
@@ -1876,8 +2371,9 @@ type AnyResource = IResource<any, any, any, any, any, any, any>;
1876
2371
  type AnyTaskMiddleware = ITaskMiddleware<any, any, any, any>;
1877
2372
  type AnyResourceMiddleware = IResourceMiddleware<any, any, any, any>;
1878
2373
  type AnyHook = IHook<any, any, any>;
1879
- 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;
1880
- declare function defineOverride<T extends AnyTask | AnyResource | AnyTaskMiddleware | AnyResourceMiddleware | AnyHook>(base: T, patch: OverridePatch<T>): T;
2374
+ type AnyOverrideable = AnyTask | AnyResource | AnyTaskMiddleware | AnyResourceMiddleware | AnyHook;
2375
+ type OverridePatch<TBase extends AnyOverrideable> = Readonly<TBase extends AnyHook ? Omit<Partial<TBase>, "id" | "on"> : Omit<Partial<TBase>, "id">>;
2376
+ declare function defineOverride<TBase extends AnyOverrideable>(base: TBase, patch: OverridePatch<TBase>): TBase;
1881
2377
 
1882
2378
  /**
1883
2379
  * Create a tag definition.
@@ -1932,68 +2428,83 @@ declare class PlatformAdapter implements IPlatformAdapter {
1932
2428
  clearTimeout: typeof clearTimeout;
1933
2429
  }
1934
2430
 
1935
- declare const duplicateRegistrationError: ErrorHelper<{
2431
+ declare const duplicateRegistrationError: IErrorHelper<{
1936
2432
  type: string;
1937
2433
  id: string;
1938
2434
  } & DefaultErrorType>;
1939
- declare const dependencyNotFoundError: ErrorHelper<{
2435
+ declare const dependencyNotFoundError: IErrorHelper<{
1940
2436
  key: string;
1941
2437
  } & DefaultErrorType>;
1942
- declare const unknownItemTypeError: ErrorHelper<{
2438
+ declare const unknownItemTypeError: IErrorHelper<{
1943
2439
  item: unknown;
1944
2440
  } & DefaultErrorType>;
1945
- declare const contextError: ErrorHelper<{
2441
+ declare const contextError: IErrorHelper<{
1946
2442
  details?: string;
1947
2443
  } & DefaultErrorType>;
1948
- declare const circularDependenciesError: ErrorHelper<{
2444
+ declare const circularDependenciesError: IErrorHelper<{
1949
2445
  cycles: string[];
1950
2446
  } & DefaultErrorType>;
1951
- declare const eventNotFoundError: ErrorHelper<{
2447
+ declare const eventNotFoundError: IErrorHelper<{
1952
2448
  id: string;
1953
2449
  } & DefaultErrorType>;
1954
- declare const resourceNotFoundError: ErrorHelper<{
2450
+ declare const resourceNotFoundError: IErrorHelper<{
1955
2451
  id: string;
1956
2452
  } & DefaultErrorType>;
1957
- declare const middlewareNotRegisteredError: ErrorHelper<{
2453
+ declare const middlewareNotRegisteredError: IErrorHelper<{
1958
2454
  type: "task" | "resource";
1959
2455
  source: string;
1960
2456
  middlewareId: string;
1961
2457
  } & DefaultErrorType>;
1962
- declare const tagNotFoundError: ErrorHelper<{
2458
+ declare const tagNotFoundError: IErrorHelper<{
1963
2459
  id: string;
1964
2460
  } & DefaultErrorType>;
1965
- declare const lockedError: ErrorHelper<{
2461
+ declare const lockedError: IErrorHelper<{
1966
2462
  what: string;
1967
2463
  } & DefaultErrorType>;
1968
- declare const storeAlreadyInitializedError: ErrorHelper<DefaultErrorType>;
1969
- declare const validationError: ErrorHelper<{
2464
+ declare const storeAlreadyInitializedError: IErrorHelper<DefaultErrorType>;
2465
+ declare const validationError: IErrorHelper<{
1970
2466
  subject: string;
1971
2467
  id: string;
1972
2468
  originalError: string | Error;
1973
2469
  } & DefaultErrorType>;
1974
- declare const eventCycleError: ErrorHelper<{
2470
+ declare const eventCycleError: IErrorHelper<{
1975
2471
  path: Array<{
1976
2472
  id: string;
1977
2473
  source: string;
1978
2474
  }>;
1979
2475
  } & DefaultErrorType>;
1980
- declare const eventEmissionCycleError: ErrorHelper<{
2476
+ declare const eventEmissionCycleError: IErrorHelper<{
1981
2477
  cycles: string[];
1982
2478
  } & DefaultErrorType>;
1983
- declare const platformUnsupportedFunctionError: ErrorHelper<{
2479
+ declare const platformUnsupportedFunctionError: IErrorHelper<{
1984
2480
  functionName: string;
1985
2481
  } & DefaultErrorType>;
1986
- declare const cancellationError: ErrorHelper<{
2482
+ declare const cancellationError: IErrorHelper<{
1987
2483
  reason?: string;
1988
2484
  } & DefaultErrorType>;
1989
- declare const tunnelOwnershipConflictError: ErrorHelper<{
2485
+ declare const tunnelOwnershipConflictError: IErrorHelper<{
1990
2486
  taskId: string;
1991
2487
  currentOwnerId: string;
1992
2488
  attemptedOwnerId: string;
1993
2489
  } & DefaultErrorType>;
2490
+ declare const phantomTaskNotRoutedError: IErrorHelper<{
2491
+ taskId: string;
2492
+ } & DefaultErrorType>;
2493
+ declare const taskNotRegisteredError: IErrorHelper<{
2494
+ taskId: string;
2495
+ } & DefaultErrorType>;
2496
+ /** Builder types that require validation before build() */
2497
+ type BuilderType = "hook" | "task-middleware" | "resource-middleware";
2498
+ declare const builderIncompleteError: IErrorHelper<{
2499
+ type: BuilderType;
2500
+ builderId: string;
2501
+ missingFields: string[];
2502
+ } & DefaultErrorType>;
1994
2503
  declare function isCancellationError(err: unknown): boolean;
1995
2504
 
2505
+ type errors_BuilderType = BuilderType;
1996
2506
  type errors_IErrorHelper<TData extends DefaultErrorType = DefaultErrorType> = IErrorHelper<TData>;
2507
+ declare const errors_builderIncompleteError: typeof builderIncompleteError;
1997
2508
  declare const errors_cancellationError: typeof cancellationError;
1998
2509
  declare const errors_circularDependenciesError: typeof circularDependenciesError;
1999
2510
  declare const errors_contextError: typeof contextError;
@@ -2005,15 +2516,17 @@ declare const errors_eventNotFoundError: typeof eventNotFoundError;
2005
2516
  declare const errors_isCancellationError: typeof isCancellationError;
2006
2517
  declare const errors_lockedError: typeof lockedError;
2007
2518
  declare const errors_middlewareNotRegisteredError: typeof middlewareNotRegisteredError;
2519
+ declare const errors_phantomTaskNotRoutedError: typeof phantomTaskNotRoutedError;
2008
2520
  declare const errors_platformUnsupportedFunctionError: typeof platformUnsupportedFunctionError;
2009
2521
  declare const errors_resourceNotFoundError: typeof resourceNotFoundError;
2010
2522
  declare const errors_storeAlreadyInitializedError: typeof storeAlreadyInitializedError;
2011
2523
  declare const errors_tagNotFoundError: typeof tagNotFoundError;
2524
+ declare const errors_taskNotRegisteredError: typeof taskNotRegisteredError;
2012
2525
  declare const errors_tunnelOwnershipConflictError: typeof tunnelOwnershipConflictError;
2013
2526
  declare const errors_unknownItemTypeError: typeof unknownItemTypeError;
2014
2527
  declare const errors_validationError: typeof validationError;
2015
2528
  declare namespace errors {
2016
- 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 };
2529
+ 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 };
2017
2530
  }
2018
2531
 
2019
2532
  /**
@@ -2061,6 +2574,27 @@ declare function buildTestFacade(deps: {
2061
2574
  eventManager: EventManager;
2062
2575
  };
2063
2576
 
2577
+ type HookOn = "*" | IEventDefinition<any> | readonly IEventDefinition<any>[];
2578
+ interface HookOverrideBuilder<TDeps extends DependencyMapType, TOn extends HookOn, TMeta extends ITaskMeta> {
2579
+ id: string;
2580
+ order(order: number): HookOverrideBuilder<TDeps, TOn, TMeta>;
2581
+ dependencies<TNewDeps extends DependencyMapType, TIsOverride extends boolean = false>(deps: TNewDeps | (() => TNewDeps), options?: {
2582
+ override?: TIsOverride;
2583
+ }): HookOverrideBuilder<TIsOverride extends true ? TNewDeps : TDeps & TNewDeps, TOn, TMeta>;
2584
+ tags<TNewTags extends TagType[]>(t: TNewTags, options?: {
2585
+ override?: boolean;
2586
+ }): HookOverrideBuilder<TDeps, TOn, TMeta>;
2587
+ meta<TNewMeta extends ITaskMeta>(m: TNewMeta): HookOverrideBuilder<TDeps, TOn, TNewMeta>;
2588
+ run(fn: IHookDefinition<TDeps, TOn, TMeta>["run"]): HookOverrideBuilder<TDeps, TOn, TMeta>;
2589
+ build(): IHook<TDeps, TOn, TMeta>;
2590
+ }
2591
+
2592
+ 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>;
2593
+ 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>;
2594
+ declare function override<TDeps extends DependencyMapType, TOn extends HookOn, TMeta extends ITaskMeta>(base: IHook<TDeps, TOn, TMeta>): HookOverrideBuilder<TDeps, TOn, TMeta>;
2595
+ declare function override<C, In, Out, D extends DependencyMapType>(base: ITaskMiddleware<C, In, Out, D>): TaskMiddlewareFluentBuilder<C, In, Out, D>;
2596
+ declare function override<C, In, Out, D extends DependencyMapType>(base: IResourceMiddleware<C, In, Out, D>): ResourceMiddlewareFluentBuilder<C, In, Out, D>;
2597
+
2064
2598
  declare const debugLevels: {
2065
2599
  normal: DebugConfig;
2066
2600
  verbose: DebugConfig;
@@ -2081,23 +2615,24 @@ interface HttpClientConfig {
2081
2615
  auth?: HttpClientAuth;
2082
2616
  timeoutMs?: number;
2083
2617
  fetchImpl?: typeof fetch;
2084
- serializer: Serializer;
2618
+ serializer: SerializerLike;
2085
2619
  onRequest?: (ctx: {
2086
2620
  url: string;
2087
2621
  headers: Record<string, string>;
2088
2622
  }) => void | Promise<void>;
2089
- contexts?: Array<IAsyncContext<any>>;
2623
+ contexts?: Array<IAsyncContext<unknown>>;
2090
2624
  errorRegistry?: Map<string, IErrorHelper<any>>;
2091
2625
  }
2092
2626
  interface HttpClient {
2093
2627
  task<I = unknown, O = unknown>(id: string, input?: I): Promise<O>;
2094
2628
  event<P = unknown>(id: string, payload?: P): Promise<void>;
2629
+ eventWithResult?<P = unknown>(id: string, payload?: P): Promise<P>;
2095
2630
  }
2096
2631
  declare function createHttpClient(cfg: HttpClientConfig): HttpClient;
2097
2632
 
2098
2633
  /**
2099
2634
  * Factory for creating HTTP clients with automatic injection of:
2100
- * - serializer (EJSON-compatible)
2635
+ * - serializer
2101
2636
  * - error registry (from Store)
2102
2637
  * - async contexts (from Store)
2103
2638
  *
@@ -2114,6 +2649,40 @@ interface HttpClientFactoryConfig {
2114
2649
  }
2115
2650
  type HttpClientFactory = (config: HttpClientFactoryConfig) => HttpClient;
2116
2651
 
2652
+ /**
2653
+ * Implementation of ExecutionJournal.
2654
+ * Created per task execution and passed through the middleware chain.
2655
+ */
2656
+ declare class ExecutionJournalImpl implements ExecutionJournal {
2657
+ private readonly store;
2658
+ /**
2659
+ * Store a value in the journal.
2660
+ * Throws an error if the key already exists unless { override: true } is passed.
2661
+ */
2662
+ set<T>(key: JournalKey<T>, value: T, options?: JournalSetOptions): void;
2663
+ get<T>(key: JournalKey<T>): T | undefined;
2664
+ has<T>(key: JournalKey<T>): boolean;
2665
+ }
2666
+ /**
2667
+ * Creates a typed journal key for use with ExecutionJournal.
2668
+ *
2669
+ * @example
2670
+ * ```typescript
2671
+ * const abortController = journal.createKey<AbortController>("timeout.abortController");
2672
+ * journal.set(abortController, new AbortController());
2673
+ * const ctrl = journal.get(abortController); // AbortController | undefined
2674
+ * ```
2675
+ */
2676
+ declare function createKey<T>(id: string): JournalKey<T>;
2677
+ declare const journal: {
2678
+ createKey: typeof createKey;
2679
+ /**
2680
+ * Creates a new empty ExecutionJournal.
2681
+ * Useful when you need to pass a specific journal instance to `runTask` or nested calls.
2682
+ */
2683
+ create: () => ExecutionJournalImpl;
2684
+ };
2685
+
2117
2686
  declare const globals: {
2118
2687
  events: {
2119
2688
  readonly ready: IEvent<void>;
@@ -2124,15 +2693,15 @@ declare const globals: {
2124
2693
  readonly eventManager: IResource<void, Promise<EventManager>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2125
2694
  readonly taskRunner: IResource<void, Promise<TaskRunner>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2126
2695
  readonly logger: IResource<void, Promise<Logger>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2127
- readonly serializer: IResource<void, Promise<Serializer>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2696
+ readonly serializer: IResource<void, Promise<SerializerLike>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2128
2697
  readonly cache: IResource<{
2129
2698
  defaultOptions?: any;
2130
2699
  }, Promise<{
2131
2700
  map: Map<string, ICacheInstance>;
2132
- cacheFactoryTask: TaskDependencyWithIntercept<any, Promise<ICacheInstance>>;
2701
+ cacheFactoryTask: TaskDependencyWithIntercept<lru_cache.LRUCache.Options<any, any, any>, Promise<ICacheInstance>>;
2133
2702
  defaultOptions: any;
2134
2703
  }>, {
2135
- cacheFactoryTask: ITask<any, Promise<ICacheInstance>, any, any, TagType[], TaskMiddlewareAttachmentType[]>;
2704
+ cacheFactoryTask: ITask<lru_cache.LRUCache.Options<any, any, any>, Promise<ICacheInstance>, any, any, TagType[], TaskMiddlewareAttachmentType[]>;
2136
2705
  }, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2137
2706
  readonly queue: IResource<void, Promise<{
2138
2707
  map: Map<string, Queue>;
@@ -2144,12 +2713,37 @@ declare const globals: {
2144
2713
  description: string;
2145
2714
  }, TagType[], ResourceMiddlewareAttachmentType[]>;
2146
2715
  readonly httpClientFactory: IResource<void, Promise<HttpClientFactory>, {
2147
- serializer: IResource<void, Promise<Serializer>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2716
+ serializer: IResource<void, Promise<SerializerLike>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2148
2717
  store: IResource<void, Promise<Store>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2149
2718
  }, any, {
2150
2719
  title: string;
2151
2720
  description: string;
2152
2721
  }, TagType[], ResourceMiddlewareAttachmentType[]>;
2722
+ readonly rateLimit: IResource<void, Promise<{
2723
+ states: WeakMap<RateLimitMiddlewareConfig, RateLimitState>;
2724
+ }>, {}, any, any, ITag<{
2725
+ metadata?: Record<string, any>;
2726
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2727
+ readonly circuitBreaker: IResource<void, Promise<{
2728
+ statusMap: Map<string, CircuitBreakerStatus>;
2729
+ }>, {}, any, any, ITag<{
2730
+ metadata?: Record<string, any>;
2731
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2732
+ readonly temporal: IResource<void, Promise<{
2733
+ debounceStates: WeakMap<TemporalMiddlewareConfig, DebounceState>;
2734
+ throttleStates: WeakMap<TemporalMiddlewareConfig, ThrottleState>;
2735
+ }>, {}, any, any, ITag<{
2736
+ metadata?: Record<string, any>;
2737
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2738
+ readonly concurrency: IResource<void, Promise<{
2739
+ semaphoresByConfig: WeakMap<ConcurrencyMiddlewareConfig, Semaphore>;
2740
+ semaphoresByKey: Map<string, {
2741
+ semaphore: Semaphore;
2742
+ limit: number;
2743
+ }>;
2744
+ }>, {}, any, any, ITag<{
2745
+ metadata?: Record<string, any>;
2746
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2153
2747
  };
2154
2748
  middleware: {
2155
2749
  requireContext: ITaskMiddleware<{
@@ -2164,14 +2758,87 @@ declare const globals: {
2164
2758
  defaultOptions?: any;
2165
2759
  }, Promise<{
2166
2760
  map: Map<string, ICacheInstance>;
2167
- cacheFactoryTask: TaskDependencyWithIntercept<any, Promise<ICacheInstance>>;
2761
+ cacheFactoryTask: TaskDependencyWithIntercept<lru_cache.LRUCache.Options<any, any, any>, Promise<ICacheInstance>>;
2168
2762
  defaultOptions: any;
2169
2763
  }>, {
2170
- cacheFactoryTask: ITask<any, Promise<ICacheInstance>, any, any, TagType[], TaskMiddlewareAttachmentType[]>;
2764
+ cacheFactoryTask: ITask<lru_cache.LRUCache.Options<any, any, any>, Promise<ICacheInstance>, any, any, TagType[], TaskMiddlewareAttachmentType[]>;
2171
2765
  }, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2766
+ }> & {
2767
+ journalKeys: {
2768
+ readonly hit: JournalKey<boolean>;
2769
+ };
2770
+ };
2771
+ concurrency: ITaskMiddleware<ConcurrencyMiddlewareConfig, void, void, {
2772
+ state: IResource<void, Promise<{
2773
+ semaphoresByConfig: WeakMap<ConcurrencyMiddlewareConfig, Semaphore>;
2774
+ semaphoresByKey: Map<string, {
2775
+ semaphore: Semaphore;
2776
+ limit: number;
2777
+ }>;
2778
+ }>, {}, any, any, ITag<{
2779
+ metadata?: Record<string, any>;
2780
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2781
+ }>;
2782
+ debounce: ITaskMiddleware<TemporalMiddlewareConfig, void, void, {
2783
+ state: IResource<void, Promise<{
2784
+ debounceStates: WeakMap<TemporalMiddlewareConfig, DebounceState>;
2785
+ throttleStates: WeakMap<TemporalMiddlewareConfig, ThrottleState>;
2786
+ }>, {}, any, any, ITag<{
2787
+ metadata?: Record<string, any>;
2788
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2789
+ }>;
2790
+ throttle: ITaskMiddleware<TemporalMiddlewareConfig, void, void, {
2791
+ state: IResource<void, Promise<{
2792
+ debounceStates: WeakMap<TemporalMiddlewareConfig, DebounceState>;
2793
+ throttleStates: WeakMap<TemporalMiddlewareConfig, ThrottleState>;
2794
+ }>, {}, any, any, ITag<{
2795
+ metadata?: Record<string, any>;
2796
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2172
2797
  }>;
2173
- retry: ITaskMiddleware<RetryMiddlewareConfig, void, void, any>;
2174
- timeout: ITaskMiddleware<TimeoutMiddlewareConfig, void, void, any>;
2798
+ fallback: ITaskMiddleware<FallbackMiddlewareConfig, void, void, {
2799
+ taskRunner: IResource<void, Promise<TaskRunner>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2800
+ }> & {
2801
+ journalKeys: {
2802
+ readonly active: JournalKey<boolean>;
2803
+ readonly error: JournalKey<Error>;
2804
+ };
2805
+ };
2806
+ rateLimit: ITaskMiddleware<RateLimitMiddlewareConfig, void, void, {
2807
+ state: IResource<void, Promise<{
2808
+ states: WeakMap<RateLimitMiddlewareConfig, RateLimitState>;
2809
+ }>, {}, any, any, ITag<{
2810
+ metadata?: Record<string, any>;
2811
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2812
+ }> & {
2813
+ journalKeys: {
2814
+ readonly remaining: JournalKey<number>;
2815
+ readonly resetTime: JournalKey<number>;
2816
+ readonly limit: JournalKey<number>;
2817
+ };
2818
+ };
2819
+ retry: ITaskMiddleware<RetryMiddlewareConfig, void, void, any> & {
2820
+ journalKeys: {
2821
+ readonly attempt: JournalKey<number>;
2822
+ readonly lastError: JournalKey<Error>;
2823
+ };
2824
+ };
2825
+ timeout: ITaskMiddleware<TimeoutMiddlewareConfig, void, void, any> & {
2826
+ journalKeys: {
2827
+ readonly abortController: JournalKey<AbortController>;
2828
+ };
2829
+ };
2830
+ circuitBreaker: ITaskMiddleware<CircuitBreakerMiddlewareConfig, void, void, {
2831
+ state: IResource<void, Promise<{
2832
+ statusMap: Map<string, CircuitBreakerStatus>;
2833
+ }>, {}, any, any, ITag<{
2834
+ metadata?: Record<string, any>;
2835
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2836
+ }> & {
2837
+ journalKeys: {
2838
+ readonly state: JournalKey<CircuitBreakerState>;
2839
+ readonly failures: JournalKey<number>;
2840
+ };
2841
+ };
2175
2842
  };
2176
2843
  resource: {
2177
2844
  retry: IResourceMiddleware<RetryMiddlewareConfig, void, void, any>;
@@ -2188,6 +2855,7 @@ declare const globals: {
2188
2855
  debug: ITag<DebugFriendlyConfig, void, void>;
2189
2856
  tunnel: ITag<void, void, TunnelRunner>;
2190
2857
  tunnelPolicy: ITag<TunnelTaskMiddlewarePolicyConfig, void, void>;
2858
+ authValidator: ITag<void, void, void>;
2191
2859
  };
2192
2860
  tunnels: Readonly<{
2193
2861
  http: Readonly<{
@@ -2210,6 +2878,7 @@ declare const r: Readonly<{
2210
2878
  event: typeof eventBuilder;
2211
2879
  hook: typeof hookBuilder;
2212
2880
  tag: typeof tagBuilder;
2881
+ override: typeof override;
2213
2882
  asyncContext: typeof asyncContextBuilder;
2214
2883
  error: typeof errorBuilder;
2215
2884
  middleware: Readonly<{
@@ -2218,4 +2887,4 @@ declare const r: Readonly<{
2218
2887
  }>;
2219
2888
  }>;
2220
2889
 
2221
- 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 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 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, createTestResource, debug, debugLevels, defs as definitions, defineEvent as event, getConfig, globals, defineHook as hook, isOneOf, levelNormal, levelVerbose, normalizeError, onAnyOf, defineOverride as override, r, 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 };
2890
+ export { type CommonPayload, type DebugConfig, type DebugFriendlyConfig, type DefaultErrorType, type DependencyMapType, DependencyProcessor, type DependencyValueType, type DependencyValuesType, type ErrorReference, errors as Errors, type EventDeliveryMode, type EventEmissionInterceptor, type EventHandlerType, EventManager, type EventStoreElementType, type ExecutionJournal, 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 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 JournalKey, type LogLevels, Logger, MiddlewareManager, 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, Serializer, type SerializerOptions, Store, type TagType, type TaskCallOptions, type TaskDependencyWithIntercept, type TaskLocalInterceptor, type TaskMiddlewareAttachmentType, type TaskMiddlewareInterceptor, type TaskMiddlewareStoreElementType, TaskRunner, type TaskStoreElementType, type ThrowsList, type TunnelEventSelector, type TunnelMode, type TunnelRunner, type TunnelTagConfig, type TunnelTaskRunner, type TunnelTaskSelector, type TypeDefinition, type UnhandledErrorKind, type UnionToIntersection, allFalse, defineAsyncContext as asyncContext, bindProcessErrorHandler, createContext, createDefaultUnhandledError, createExposureFetch, createHttpClient, createTestResource, debug, debugLevels, defs as definitions, defineEvent as event, getConfig, getDefaultSerializer, globals, defineHook as hook, isOneOf, journal, levelNormal, levelVerbose, normalizeError, onAnyOf, defineOverride as override, r, 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 };