@bluelibs/runner 4.9.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,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> {
@@ -129,6 +129,8 @@ declare const symbolTask: unique symbol;
129
129
  /** Marks a task as a phantom task (no-op run; meant to be tunneled/routed). */
130
130
  declare const symbolPhantomTask: unique symbol;
131
131
  declare const symbolResource: unique symbol;
132
+ /** @internal Marks forked resources and records fork provenance */
133
+ declare const symbolResourceForkedFrom: unique symbol;
132
134
  declare const symbolResourceWithConfig: unique symbol;
133
135
  declare const symbolEvent: unique symbol;
134
136
  /** @internal Marks an error helper definition */
@@ -152,9 +154,107 @@ declare const symbolFilePath: unique symbol;
152
154
  /** @internal Marks an async context definition */
153
155
  declare const symbolAsyncContext: unique symbol;
154
156
 
157
+ interface IResourceMiddlewareDefinition<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> {
158
+ id: string;
159
+ /** Static or lazy dependency map. */
160
+ dependencies?: TDependencies | ((config: TConfig) => TDependencies);
161
+ /**
162
+ * Optional validation schema for runtime config validation.
163
+ * When provided, middleware config will be validated when .with() is called.
164
+ */
165
+ configSchema?: IValidationSchema<TConfig>;
166
+ /**
167
+ * The middleware body, called with resource execution input.
168
+ */
169
+ run: (input: IResourceMiddlewareExecutionInput<TEnforceInputContract extends void ? any : TEnforceInputContract, TEnforceOutputContract extends void ? any : TEnforceOutputContract>, dependencies: DependencyValuesType<TDependencies>, config: TConfig) => Promise<any>;
170
+ meta?: IMiddlewareMeta;
171
+ tags?: TagType[];
172
+ everywhere?: boolean | ((resource: IResource<any, any, any, any, any>) => boolean);
173
+ }
174
+ interface IResourceMiddleware<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> extends IResourceMiddlewareDefinition<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>, IContractable<TConfig, TEnforceInputContract, TEnforceOutputContract> {
175
+ [symbolResourceMiddleware]: true;
176
+ id: string;
177
+ dependencies: TDependencies | ((config: TConfig) => TDependencies);
178
+ /** Current configuration object (empty by default). */
179
+ config: TConfig;
180
+ /** Configure the middleware and return a marked, configured instance. */
181
+ with: (config: TConfig) => IResourceMiddlewareConfigured<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
182
+ [symbolFilePath]: string;
183
+ tags: TagType[];
184
+ }
185
+ interface IResourceMiddlewareConfigured<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> extends IResourceMiddleware<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies> {
186
+ [symbolMiddlewareConfigured]: true;
187
+ }
188
+ interface IResourceMiddlewareExecutionInput<TResourceConfig = any, TResourceOutput = any> {
189
+ /** Resource hook */
190
+ resource: {
191
+ definition: IResource<TResourceConfig, any, any, any, any>;
192
+ config: TResourceConfig;
193
+ };
194
+ next: (resourceConfig?: TResourceConfig) => Promise<TResourceOutput>;
195
+ }
196
+ type ResourceMiddlewareAttachmentType = IResourceMiddleware<void, any, any, any> | IResourceMiddleware<{
197
+ [K in any]?: any;
198
+ }, any, any, any> | IResourceMiddlewareConfigured<any, any, any, any>;
199
+
200
+ type ErrorReference = string | IErrorHelper<any>;
201
+ type ThrowsList = ReadonlyArray<ErrorReference>;
202
+ interface IErrorDefinition<TData extends DefaultErrorType = DefaultErrorType> {
203
+ id: string;
204
+ serialize?: (data: TData) => string;
205
+ parse?: (data: string) => TData;
206
+ format?: (data: TData) => string;
207
+ /**
208
+ * Validate error data on throw(). If provided, data is parsed first.
209
+ */
210
+ dataSchema?: IValidationSchema<TData>;
211
+ meta?: IErrorMeta;
212
+ }
213
+ interface IErrorDefinitionFinal<TData extends DefaultErrorType> extends IErrorDefinition<TData> {
214
+ format: (data: TData) => string;
215
+ }
216
+ type DefaultErrorType = Record<string, unknown>;
217
+ /**
218
+ * Runtime helper returned by defineError()/r.error().
219
+ * Contains helpers to throw typed errors and perform type-safe checks.
220
+ */
221
+ interface IErrorHelper<TData extends DefaultErrorType = DefaultErrorType> {
222
+ /** Unique id for registration and DI */
223
+ id: string;
224
+ /** Throw a typed error with the given data */
225
+ throw(data: TData): never;
226
+ /** Type guard for checking if an unknown error is this error */
227
+ is(error: unknown): boolean;
228
+ /** Brand symbol for runtime detection */
229
+ [symbolError]: true;
230
+ /** Return an optional dependency wrapper for this error */
231
+ optional(): IOptionalDependency<IErrorHelper<TData>>;
232
+ }
233
+
234
+ type ResourceForkRegisterMode = "keep" | "drop" | "deep";
235
+ interface ResourceForkOptions {
236
+ /**
237
+ * Control whether the fork keeps the base `register` list.
238
+ * - "keep" (default) keeps registration items
239
+ * - "drop" clears registration items
240
+ * - "deep" deep-forks registered resources with new ids (resource tree)
241
+ */
242
+ register?: ResourceForkRegisterMode;
243
+ /**
244
+ * Used with `register: "deep"` to derive ids for deep-forked resources.
245
+ * Defaults to `(id) => \`\${newId}.\${id}\``.
246
+ */
247
+ reId?: (id: string) => string;
248
+ }
249
+ interface ResourceForkInfo {
250
+ /** The id of the resource that was forked. */
251
+ readonly fromId: string;
252
+ /** Best-effort call-site file path for the fork operation. */
253
+ readonly forkedAtFilePath: string;
254
+ }
155
255
  type IsAny<T> = 0 extends 1 & T ? true : false;
156
256
  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[]> {
257
+ 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
258
  /** Stable identifier. */
159
259
  id: string;
160
260
  /** Static or lazy dependency map. Receives `config` when provided. */
@@ -184,6 +284,16 @@ interface IResourceDefinition<TConfig = any, TValue extends Promise<any> = Promi
184
284
  */
185
285
  dispose?: (this: any, value: TValue extends Promise<infer U> ? U : TValue, config: TConfig, dependencies: ResourceDependencyValuesType<TDependencies>, context: TContext) => Promise<void>;
186
286
  meta?: TMeta;
287
+ /**
288
+ * Declares which typed errors are part of this resource's contract.
289
+ *
290
+ * This is a declarative contract only:
291
+ * - It does not imply dependency injection
292
+ * - It does not enforce that only these errors can be thrown
293
+ *
294
+ * Use string ids or Error helpers.
295
+ */
296
+ throws?: ThrowsList;
187
297
  /**
188
298
  * Optional validation schema for runtime config validation.
189
299
  * When provided, resource config will be validated when .with() is called.
@@ -220,9 +330,19 @@ interface IResource<TConfig = void, TValue extends Promise<any> = Promise<any>,
220
330
  middleware: TMiddleware;
221
331
  [symbolFilePath]: string;
222
332
  [symbolResource]: true;
333
+ /** Present only on forked resources. */
334
+ [symbolResourceForkedFrom]?: ResourceForkInfo;
335
+ /** Normalized list of error ids declared via `throws`. */
336
+ throws?: readonly string[];
223
337
  /** Return an optional dependency wrapper for this resource. */
224
338
  optional: () => IOptionalDependency<IResource<TConfig, TValue, TDependencies, TContext, TMeta, TTags, TMiddleware>>;
225
339
  tags: TTags;
340
+ /**
341
+ * Create a new resource with a different id but the same definition.
342
+ * Useful for creating multiple instances of a "template" resource.
343
+ * The forked resource should be exported and used as a dependency.
344
+ */
345
+ fork(newId: string, options?: ResourceForkOptions): IResource<TConfig, TValue, TDependencies, TContext, TMeta, TTags, TMiddleware>;
226
346
  }
227
347
  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
348
  [symbolResourceWithConfig]: true;
@@ -234,55 +354,34 @@ interface IResourceWithConfig<TConfig = any, TValue extends Promise<any> = Promi
234
354
  config: TConfig;
235
355
  }
236
356
 
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;
357
+ /**
358
+ * Typed key used to store/retrieve values from an ExecutionJournal.
359
+ * The `id` is used as the storage slot.
360
+ */
361
+ declare const journalKeyBrand: unique symbol;
362
+ type JournalKey<T> = {
363
+ readonly id: string;
364
+ readonly [journalKeyBrand]?: (value: T) => T;
365
+ };
366
+ /**
367
+ * Options for setting values in the journal.
368
+ */
369
+ interface JournalSetOptions {
260
370
  /**
261
- * Tags applied to the task that might define its behvaiour or impact the systems.
371
+ * If true, allows overwriting an existing value.
372
+ * By default, attempting to set a key that already exists will throw an error.
262
373
  */
263
- tags?: TTags;
374
+ override?: boolean;
264
375
  }
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;
376
+ /**
377
+ * Per-execution registry that allows middleware and tasks to share state.
378
+ * A new journal is created for each top-level task execution unless explicitly forwarded.
379
+ */
380
+ interface ExecutionJournal {
381
+ set<T>(key: JournalKey<T>, value: T, options?: JournalSetOptions): void;
382
+ get<T>(key: JournalKey<T>): T | undefined;
383
+ has<T>(key: JournalKey<T>): boolean;
281
384
  }
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
385
 
287
386
  interface ITaskMiddlewareDefinition<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> {
288
387
  id: string;
@@ -305,7 +404,7 @@ interface ITaskMiddleware<TConfig = any, TEnforceInputContract = void, TEnforceO
305
404
  [symbolTaskMiddleware]: true;
306
405
  [symbolFilePath]: string;
307
406
  id: string;
308
- dependencies: TDependencies | (() => TDependencies);
407
+ dependencies: TDependencies | ((config: TConfig) => TDependencies);
309
408
  /** Current configuration object (empty by default). */
310
409
  config: TConfig;
311
410
  /** Configure the middleware and return a marked, configured instance. */
@@ -323,72 +422,76 @@ interface ITaskMiddlewareExecutionInput<TTaskInput = any, TTaskOutput = any> {
323
422
  input: TTaskInput;
324
423
  };
325
424
  next: (taskInput?: TTaskInput) => Promise<TTaskOutput>;
425
+ /** Per-execution registry for sharing state between middleware and task */
426
+ journal: ExecutionJournal;
326
427
  }
327
428
  type TaskMiddlewareAttachmentType = ITaskMiddleware<void, any, any, any> | ITaskMiddleware<{
328
429
  [K in any]?: any;
329
430
  }, any, any, any> | ITaskMiddlewareConfigured<any, any, any, any>;
330
431
 
331
- interface IResourceMiddlewareDefinition<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> {
432
+ 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
433
  id: string;
333
- /** Static or lazy dependency map. */
334
- dependencies?: TDependencies | ((config: TConfig) => TDependencies);
335
434
  /**
336
- * Optional validation schema for runtime config validation.
337
- * When provided, middleware config will be validated when .with() is called.
435
+ * Access other tasks/resources/events. Can be an object or a function when
436
+ * you need late or config‑dependent resolution.
338
437
  */
339
- configSchema?: IValidationSchema<TConfig>;
438
+ dependencies?: TDependencies | (() => TDependencies);
439
+ /** Middleware applied around task execution. */
440
+ middleware?: TMiddleware;
441
+ /** Optional metadata used for docs, filtering and tooling. */
442
+ meta?: TMeta;
340
443
  /**
341
- * The middleware body, called with resource execution input.
444
+ * Optional validation schema for runtime input validation.
445
+ * When provided, task input will be validated before execution.
342
446
  */
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);
447
+ inputSchema?: IValidationSchema<TInput>;
448
+ /**
449
+ * Optional validation schema for the task result.
450
+ * When provided, the result will be validated immediately after the task's
451
+ * `run` resolves, without considering middleware.
452
+ */
453
+ resultSchema?: IValidationSchema<TOutput extends Promise<infer U> ? U : never>;
454
+ /**
455
+ * Declares which typed errors are part of this task's contract.
456
+ *
457
+ * This is a declarative contract only:
458
+ * - It does not imply dependency injection
459
+ * - It does not enforce that only these errors can be thrown
460
+ *
461
+ * Use string ids or Error helpers.
462
+ */
463
+ throws?: ThrowsList;
464
+ run: (input: HasInputContracts<[...TTags, ...TMiddleware]> extends true ? [TInput] extends [undefined] ? InferInputOrViolationFromContracts<[...TTags, ...TMiddleware]> : EnsureInputSatisfiesContracts<[...TTags, ...TMiddleware], TInput> : TInput, dependencies: DependencyValuesType<TDependencies>, context?: {
465
+ journal: ExecutionJournal;
466
+ }) => HasOutputContracts<[...TTags, ...TMiddleware]> extends true ? EnsureOutputSatisfiesContracts<[...TTags, ...TMiddleware], TOutput> : TOutput;
467
+ /**
468
+ * Tags applied to the task that might define its behvaiour or impact the systems.
469
+ */
470
+ tags?: TTags;
347
471
  }
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>;
472
+ 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
473
  [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> {
474
+ [symbolTask]: true;
475
+ /** Present only for phantom tasks. */
476
+ [symbolPhantomTask]?: true;
477
+ /** Indicates if the task is tunneled through a tunnel client. */
478
+ isTunneled?: boolean;
479
+ /** Records which tunnel resource owns the task (exclusivity). */
480
+ [symbolTunneledBy]?: string;
386
481
  id: string;
387
482
  dependencies: TDependencies | (() => TDependencies);
388
- [symbolFilePath]: string;
389
- [symbolHook]: true;
390
- tags: TagType[];
483
+ computedDependencies?: DependencyValuesType<TDependencies>;
484
+ middleware: TMiddleware;
485
+ /** Normalized list of error ids declared via `throws`. */
486
+ throws?: readonly string[];
487
+ /** Return an optional dependency wrapper for this task. */
488
+ optional: () => IOptionalDependency<ITask<TInput, TOutput, TDependencies, TMeta, TTags, TMiddleware>>;
489
+ tags: TTags;
391
490
  }
491
+ /** Narrowed type for phantom tasks (no-op run by default). */
492
+ 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> & {
493
+ [symbolPhantomTask]: true;
494
+ };
392
495
 
393
496
  type EventHandlerType<T = any> = (event: IEventEmission<T>) => any | Promise<any>;
394
497
  declare function onAnyOf<T extends readonly IEventDefinition<any>[]>(...defs: T): T;
@@ -466,41 +569,25 @@ interface IEventEmission<TPayload = any> {
466
569
  tags: TagType[];
467
570
  }
468
571
 
469
- declare const ERROR_TYPES_LOADED: true;
470
- interface IErrorDefinition<TData extends DefaultErrorType = DefaultErrorType> {
572
+ type OnType = "*" | IEventDefinition<any> | readonly IEventDefinition<any>[];
573
+ interface IHookDefinition<TDependencies extends DependencyMapType = {}, TOn extends OnType = any, TMeta extends ITaskMeta = any> {
471
574
  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;
575
+ dependencies?: TDependencies | (() => TDependencies);
576
+ on: TOn;
577
+ /** Listener execution order. Lower numbers run first. */
578
+ order?: number;
579
+ meta?: TMeta;
580
+ run: (event: IEventEmission<TOn extends "*" ? any : TOn extends readonly IEventDefinition<any>[] ? CommonPayload<TOn> : ExtractEventPayload<TOn>>, dependencies: DependencyValuesType<TDependencies>) => Promise<any>;
581
+ tags?: TagType[];
483
582
  }
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 */
583
+ interface IHook<TDependencies extends DependencyMapType = {}, TOn extends OnType = any, TMeta extends ITaskMeta = any> extends IHookDefinition<TDependencies, TOn, TMeta> {
491
584
  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>>;
585
+ dependencies: TDependencies | (() => TDependencies);
586
+ [symbolFilePath]: string;
587
+ [symbolHook]: true;
588
+ tags: TagType[];
500
589
  }
501
590
 
502
- declare const ASYNC_CONTEXT_TYPES_LOADED: true;
503
-
504
591
  interface IAsyncContextDefinition<T> {
505
592
  id: string;
506
593
  serialize?(data: T): string;
@@ -588,20 +675,31 @@ interface IOptionalDependency<T> {
588
675
  /** Brand symbol for optional dependency */
589
676
  [symbolOptionalDependency]: true;
590
677
  }
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;
678
+ type ExtractTaskInput<T> = T extends ITask<infer I, any, infer _D> ? I : never;
679
+ type ExtractTaskOutput<T> = T extends ITask<any, infer O, infer _D> ? O : never;
593
680
  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;
681
+ type ExtractResourceValue<T> = T extends IResource<any, infer V, infer _D> ? V extends Promise<infer U> ? U : V : never;
595
682
  type ExtractEventPayload<T> = T extends IEventDefinition<infer P> ? P : T extends IEvent<infer P> ? P : never;
596
683
  type UnionToIntersection<U> = (U extends any ? (x: U) => any : never) extends (x: infer I) => any ? I : never;
597
684
  type CommonPayload<T extends readonly IEventDefinition<any>[] | IEventDefinition<any>> = T extends readonly IEventDefinition<any>[] ? {
598
685
  [K in keyof ExtractEventPayload<T[number]>]: UnionToIntersection<ExtractEventPayload<T[number]> extends any ? ExtractEventPayload<T[number]>[K] : never>;
599
686
  } : ExtractEventPayload<T>;
687
+ /**
688
+ * Options that can be passed when calling a task dependency.
689
+ * Allows forwarding the execution journal to nested task calls.
690
+ */
691
+ interface TaskCallOptions {
692
+ /** Optional journal to forward to the nested task */
693
+ journal?: ExecutionJournal;
694
+ }
600
695
  /**
601
696
  * Task dependencies transform into callable functions: call with the task input
602
- * and you receive the task output.
697
+ * and you receive the task output. Optionally accepts TaskCallOptions for journal forwarding.
603
698
  */
604
- type TaskDependency<I, O> = (...args: I extends null | void ? [] : [I]) => O;
699
+ type TaskDependency<I, O> = I extends null | void ? {
700
+ (options?: TaskCallOptions): O;
701
+ (input?: I, options?: TaskCallOptions): O;
702
+ } : (input: I, options?: TaskCallOptions) => O;
605
703
  /**
606
704
  * Resource dependencies resolve to the resource's value directly.
607
705
  */
@@ -714,6 +812,7 @@ declare class LogPrinter {
714
812
  private formatContext;
715
813
  private normalizeForJson;
716
814
  private static NO_COLORS;
815
+ private static readonly DEFAULT_WRITERS;
717
816
  private static writers;
718
817
  static setWriters(writers: Partial<{
719
818
  log: (msg: any) => void;
@@ -868,7 +967,7 @@ type RunOptions = {
868
967
  * When set, forces runtime cycle detection for event emissions. Disable if you're sure
869
968
  * you don't have event deadlocks to improve event emission performance.
870
969
  */
871
- runtimeCycleDetection?: boolean;
970
+ runtimeEventCycleDetection?: boolean;
872
971
  /**
873
972
  * Specify in which mode to run "dev", "prod" or "test".
874
973
  * If inside Node this is automatically detected from the NODE_ENV environment variable if not provided.
@@ -888,6 +987,8 @@ interface ICacheInstance {
888
987
  set(key: string, value: any): void;
889
988
  get(key: string): any;
890
989
  clear(): void;
990
+ /** Optional presence check to disambiguate cached undefined values */
991
+ has?(key: string): boolean;
891
992
  }
892
993
 
893
994
  type ResourceStoreElementType<C = any, V extends Promise<any> = any, D extends DependencyMapType = {}, TContext = any> = {
@@ -939,13 +1040,12 @@ type EventStoreElementType = {
939
1040
  * - Safe overrides and strong typing around config and register mechanics
940
1041
  */
941
1042
 
942
- declare const defs_ASYNC_CONTEXT_TYPES_LOADED: typeof ASYNC_CONTEXT_TYPES_LOADED;
943
1043
  type defs_CommonPayload<T extends readonly IEventDefinition<any>[] | IEventDefinition<any>> = CommonPayload<T>;
944
1044
  type defs_DefaultErrorType = DefaultErrorType;
945
1045
  type defs_DependencyMapType = DependencyMapType;
946
1046
  type defs_DependencyValueType<T> = DependencyValueType<T>;
947
1047
  type defs_DependencyValuesType<T extends DependencyMapType> = DependencyValuesType<T>;
948
- declare const defs_ERROR_TYPES_LOADED: typeof ERROR_TYPES_LOADED;
1048
+ type defs_ErrorReference = ErrorReference;
949
1049
  type defs_EventHandlerType<T = any> = EventHandlerType<T>;
950
1050
  type defs_EventStoreElementType = EventStoreElementType;
951
1051
  type defs_ExtractEventPayload<T> = ExtractEventPayload<T>;
@@ -973,7 +1073,7 @@ type defs_IMiddlewareMeta = IMiddlewareMeta;
973
1073
  type defs_IOptionalDependency<T> = IOptionalDependency<T>;
974
1074
  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
1075
  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>;
1076
+ 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
1077
  type defs_IResourceMeta = IResourceMeta;
978
1078
  type defs_IResourceMiddleware<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> = IResourceMiddleware<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
979
1079
  type defs_IResourceMiddlewareConfigured<TConfig = any, TEnforceInputContract = void, TEnforceOutputContract = void, TDependencies extends DependencyMapType = any> = IResourceMiddlewareConfigured<TConfig, TEnforceInputContract, TEnforceOutputContract, TDependencies>;
@@ -982,7 +1082,7 @@ type defs_IResourceMiddlewareExecutionInput<TResourceConfig = any, TResourceOutp
982
1082
  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
1083
  type defs_ITag<TConfig = void, TEnforceInputContract = void, TEnforceOutputContract = void> = ITag<TConfig, TEnforceInputContract, TEnforceOutputContract>;
984
1084
  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>;
1085
+ type defs_ITagDefinition<TConfig = void, _TEnforceInputContract = void, _TEnforceOutputContract = void> = ITagDefinition<TConfig, _TEnforceInputContract, _TEnforceOutputContract>;
986
1086
  type defs_ITagMeta = ITagMeta;
987
1087
  type defs_ITaggable = ITaggable;
988
1088
  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>;
@@ -998,6 +1098,9 @@ type defs_RegisterableItems = RegisterableItems;
998
1098
  type defs_RequiredKeys<T> = RequiredKeys<T>;
999
1099
  type defs_ResourceDependencyValueType<T> = ResourceDependencyValueType<T>;
1000
1100
  type defs_ResourceDependencyValuesType<T extends DependencyMapType> = ResourceDependencyValuesType<T>;
1101
+ type defs_ResourceForkInfo = ResourceForkInfo;
1102
+ type defs_ResourceForkOptions = ResourceForkOptions;
1103
+ type defs_ResourceForkRegisterMode = ResourceForkRegisterMode;
1001
1104
  type defs_ResourceInitFn<TConfig, TValue extends Promise<any>, TDependencies extends DependencyMapType, TContext, TMeta extends IResourceMeta, TTags extends TagType[], TMiddleware extends ResourceMiddlewareAttachmentType[]> = ResourceInitFn<TConfig, TValue, TDependencies, TContext, TMeta, TTags, TMiddleware>;
1002
1105
  type defs_ResourceMiddlewareAttachmentType = ResourceMiddlewareAttachmentType;
1003
1106
  type defs_ResourceMiddlewareStoreElementType<TDeps extends DependencyMapType = any> = ResourceMiddlewareStoreElementType<TDeps>;
@@ -1006,11 +1109,13 @@ type defs_RunOptions = RunOptions;
1006
1109
  type defs_RunnerMode = RunnerMode;
1007
1110
  declare const defs_RunnerMode: typeof RunnerMode;
1008
1111
  type defs_TagType = TagType;
1112
+ type defs_TaskCallOptions = TaskCallOptions;
1009
1113
  type defs_TaskDependencyWithIntercept<TInput, TOutput> = TaskDependencyWithIntercept<TInput, TOutput>;
1010
1114
  type defs_TaskLocalInterceptor<TInput, TOutput> = TaskLocalInterceptor<TInput, TOutput>;
1011
1115
  type defs_TaskMiddlewareAttachmentType = TaskMiddlewareAttachmentType;
1012
1116
  type defs_TaskMiddlewareStoreElementType<TDeps extends DependencyMapType = any> = TaskMiddlewareStoreElementType<TDeps>;
1013
1117
  type defs_TaskStoreElementType<Input = any, Output extends Promise<any> = any, D extends DependencyMapType = any> = TaskStoreElementType<Input, Output, D>;
1118
+ type defs_ThrowsList = ThrowsList;
1014
1119
  type defs_UnionToIntersection<U> = UnionToIntersection<U>;
1015
1120
  declare const defs_isOneOf: typeof isOneOf;
1016
1121
  declare const defs_onAnyOf: typeof onAnyOf;
@@ -1024,6 +1129,7 @@ declare const defs_symbolMiddlewareConfigured: typeof symbolMiddlewareConfigured
1024
1129
  declare const defs_symbolOptionalDependency: typeof symbolOptionalDependency;
1025
1130
  declare const defs_symbolPhantomTask: typeof symbolPhantomTask;
1026
1131
  declare const defs_symbolResource: typeof symbolResource;
1132
+ declare const defs_symbolResourceForkedFrom: typeof symbolResourceForkedFrom;
1027
1133
  declare const defs_symbolResourceMiddleware: typeof symbolResourceMiddleware;
1028
1134
  declare const defs_symbolResourceWithConfig: typeof symbolResourceWithConfig;
1029
1135
  declare const defs_symbolTag: typeof symbolTag;
@@ -1032,7 +1138,7 @@ declare const defs_symbolTask: typeof symbolTask;
1032
1138
  declare const defs_symbolTaskMiddleware: typeof symbolTaskMiddleware;
1033
1139
  declare const defs_symbolTunneledBy: typeof symbolTunneledBy;
1034
1140
  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 };
1141
+ export { type defs_CommonPayload as CommonPayload, type defs_DefaultErrorType as DefaultErrorType, type defs_DependencyMapType as DependencyMapType, type defs_DependencyValueType as DependencyValueType, type defs_DependencyValuesType as DependencyValuesType, type defs_ErrorReference as ErrorReference, type defs_EventHandlerType as EventHandlerType, type defs_EventStoreElementType as EventStoreElementType, type defs_ExtractEventPayload as ExtractEventPayload, type defs_ExtractResourceConfig as ExtractResourceConfig, type defs_ExtractResourceValue as ExtractResourceValue, type defs_ExtractTaskInput as ExtractTaskInput, type defs_ExtractTaskOutput as ExtractTaskOutput, type defs_HookStoreElementType as HookStoreElementType, type defs_IAsyncContext as IAsyncContext, type defs_IAsyncContextDefinition as IAsyncContextDefinition, type defs_IAsyncContextMeta as IAsyncContextMeta, type defs_ICacheInstance as ICacheInstance, type defs_IErrorDefinition as IErrorDefinition, type defs_IErrorDefinitionFinal as IErrorDefinitionFinal, type defs_IErrorHelper as IErrorHelper, type defs_IErrorMeta as IErrorMeta, type defs_IEvent as IEvent, type defs_IEventDefinition as IEventDefinition, type defs_IEventEmission as IEventEmission, type defs_IEventMeta as IEventMeta, type defs_IHook as IHook, type defs_IHookDefinition as IHookDefinition, type defs_IMeta as IMeta, type defs_IMiddlewareMeta as IMiddlewareMeta, type defs_IOptionalDependency as IOptionalDependency, type defs_IPhantomTask as IPhantomTask, type defs_IResource as IResource, type defs_IResourceDefinition as IResourceDefinition, type defs_IResourceMeta as IResourceMeta, type defs_IResourceMiddleware as IResourceMiddleware, type defs_IResourceMiddlewareConfigured as IResourceMiddlewareConfigured, type defs_IResourceMiddlewareDefinition as IResourceMiddlewareDefinition, type defs_IResourceMiddlewareExecutionInput as IResourceMiddlewareExecutionInput, type defs_IResourceWithConfig as IResourceWithConfig, type defs_ITag as ITag, type defs_ITagConfigured as ITagConfigured, type defs_ITagDefinition as ITagDefinition, type defs_ITagMeta as ITagMeta, type defs_ITaggable as ITaggable, type defs_ITask as ITask, type defs_ITaskDefinition as ITaskDefinition, type defs_ITaskMeta as ITaskMeta, type defs_ITaskMiddleware as ITaskMiddleware, type defs_ITaskMiddlewareConfigured as ITaskMiddlewareConfigured, type defs_ITaskMiddlewareDefinition as ITaskMiddlewareDefinition, type defs_ITaskMiddlewareExecutionInput as ITaskMiddlewareExecutionInput, type defs_IValidationSchema as IValidationSchema, type defs_OverridableElements as OverridableElements, type defs_RegisterableItems as RegisterableItems, type defs_RequiredKeys as RequiredKeys, type defs_ResourceDependencyValueType as ResourceDependencyValueType, type defs_ResourceDependencyValuesType as ResourceDependencyValuesType, type defs_ResourceForkInfo as ResourceForkInfo, type defs_ResourceForkOptions as ResourceForkOptions, type defs_ResourceForkRegisterMode as ResourceForkRegisterMode, type defs_ResourceInitFn as ResourceInitFn, type defs_ResourceMiddlewareAttachmentType as ResourceMiddlewareAttachmentType, type defs_ResourceMiddlewareStoreElementType as ResourceMiddlewareStoreElementType, type defs_ResourceStoreElementType as ResourceStoreElementType, type defs_RunOptions as RunOptions, defs_RunnerMode as RunnerMode, type defs_TagType as TagType, type defs_TaskCallOptions as TaskCallOptions, type defs_TaskDependencyWithIntercept as TaskDependencyWithIntercept, type defs_TaskLocalInterceptor as TaskLocalInterceptor, type defs_TaskMiddlewareAttachmentType as TaskMiddlewareAttachmentType, type defs_TaskMiddlewareStoreElementType as TaskMiddlewareStoreElementType, type defs_TaskStoreElementType as TaskStoreElementType, type defs_ThrowsList as ThrowsList, type defs_UnionToIntersection as UnionToIntersection, defs_isOneOf as isOneOf, defs_onAnyOf as onAnyOf, defs_symbolAsyncContext as symbolAsyncContext, defs_symbolError as symbolError, defs_symbolEvent as symbolEvent, defs_symbolFilePath as symbolFilePath, defs_symbolHook as symbolHook, defs_symbolMiddleware as symbolMiddleware, defs_symbolMiddlewareConfigured as symbolMiddlewareConfigured, defs_symbolOptionalDependency as symbolOptionalDependency, defs_symbolPhantomTask as symbolPhantomTask, defs_symbolResource as symbolResource, defs_symbolResourceForkedFrom as symbolResourceForkedFrom, defs_symbolResourceMiddleware as symbolResourceMiddleware, defs_symbolResourceWithConfig as symbolResourceWithConfig, defs_symbolTag as symbolTag, defs_symbolTagConfigured as symbolTagConfigured, defs_symbolTask as symbolTask, defs_symbolTaskMiddleware as symbolTaskMiddleware, defs_symbolTunneledBy as symbolTunneledBy };
1036
1142
  }
1037
1143
 
1038
1144
  interface TaskMiddlewareFluentBuilder<C = any, In = void, Out = void, D extends DependencyMapType = {}> {
@@ -1052,7 +1158,7 @@ interface TaskMiddlewareFluentBuilder<C = any, In = void, Out = void, D extends
1052
1158
  everywhere(flag: boolean | ((task: ITask<any, any, any, any>) => boolean)): TaskMiddlewareFluentBuilder<C, In, Out, D>;
1053
1159
  build(): ITaskMiddleware<C, In, Out, D>;
1054
1160
  }
1055
- declare function taskMiddlewareBuilder<C = void, In = void, Out = void, D extends DependencyMapType = {}>(id: string): TaskMiddlewareFluentBuilder<C, In, Out, D>;
1161
+
1056
1162
  interface ResourceMiddlewareFluentBuilder<C = any, In = void, Out = void, D extends DependencyMapType = {}> {
1057
1163
  id: string;
1058
1164
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | ((config: C) => TNewDeps), options?: {
@@ -1070,35 +1176,29 @@ interface ResourceMiddlewareFluentBuilder<C = any, In = void, Out = void, D exte
1070
1176
  everywhere(flag: boolean | ((resource: IResource<any, any, any, any, any>) => boolean)): ResourceMiddlewareFluentBuilder<C, In, Out, D>;
1071
1177
  build(): IResourceMiddleware<C, In, Out, D>;
1072
1178
  }
1073
- declare function resourceMiddlewareBuilder<C = void, In = void, Out = void, D extends DependencyMapType = {}>(id: string): ResourceMiddlewareFluentBuilder<C, In, Out, D>;
1074
1179
 
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
- }
1180
+ /**
1181
+ * Entry point for creating a task middleware builder.
1182
+ */
1183
+ declare function taskMiddlewareBuilder<C = void, In = void, Out = void, D extends DependencyMapType = {}>(id: string): TaskMiddlewareFluentBuilder<C, In, Out, D>;
1184
+ /**
1185
+ * Entry point for creating a resource middleware builder.
1186
+ */
1187
+ declare function resourceMiddlewareBuilder<C = void, In = void, Out = void, D extends DependencyMapType = {}>(id: string): ResourceMiddlewareFluentBuilder<C, In, Out, D>;
1092
1188
 
1093
1189
  interface ErrorFluentBuilder<TData extends DefaultErrorType = DefaultErrorType> {
1094
1190
  id: string;
1095
1191
  serialize(fn: (data: TData) => string): ErrorFluentBuilder<TData>;
1096
1192
  parse(fn: (raw: string) => TData): ErrorFluentBuilder<TData>;
1097
1193
  dataSchema(schema: IValidationSchema<TData>): ErrorFluentBuilder<TData>;
1098
- build(): ErrorHelper<TData>;
1194
+ build(): IErrorHelper<TData>;
1099
1195
  format(fn: (data: TData) => string): ErrorFluentBuilder<TData>;
1100
1196
  meta<TNewMeta extends IErrorMeta>(m: TNewMeta): ErrorFluentBuilder<TData>;
1101
1197
  }
1198
+
1199
+ /**
1200
+ * Entry point for creating an error builder.
1201
+ */
1102
1202
  declare function errorBuilder<TData extends DefaultErrorType = DefaultErrorType>(id: string): ErrorFluentBuilder<TData>;
1103
1203
 
1104
1204
  interface AsyncContextFluentBuilder<T = unknown> {
@@ -1109,6 +1209,10 @@ interface AsyncContextFluentBuilder<T = unknown> {
1109
1209
  meta<TNewMeta extends IAsyncContextMeta>(m: TNewMeta): AsyncContextFluentBuilder<T>;
1110
1210
  build(): IAsyncContext<T>;
1111
1211
  }
1212
+
1213
+ /**
1214
+ * Entry point for creating an async context builder.
1215
+ */
1112
1216
  declare function asyncContextBuilder<T = unknown>(id: string): AsyncContextFluentBuilder<T>;
1113
1217
 
1114
1218
  interface TagFluentBuilder<TConfig = void, TEnforceIn = void, TEnforceOut = void> {
@@ -1118,11 +1222,19 @@ interface TagFluentBuilder<TConfig = void, TEnforceIn = void, TEnforceOut = void
1118
1222
  config<TNewConfig>(config: TNewConfig): TagFluentBuilder<TNewConfig, TEnforceIn, TEnforceOut>;
1119
1223
  build(): ITag<TConfig, TEnforceIn, TEnforceOut>;
1120
1224
  }
1225
+
1226
+ /**
1227
+ * Entry point for creating a tag builder.
1228
+ */
1121
1229
  declare function tagBuilder<TConfig = void, TEnforceIn = void, TEnforceOut = void>(id: string): TagFluentBuilder<TConfig, TEnforceIn, TEnforceOut>;
1122
1230
 
1123
- interface HookFluentBuilder<TDeps extends DependencyMapType = {}, TOn extends "*" | IEventDefinition<any> | readonly IEventDefinition<any>[] = any, TMeta extends ITaskMeta = ITaskMeta> {
1231
+ /** Valid event targets for hook's .on() method */
1232
+ type ValidOnTarget = "*" | IEventDefinition<any> | readonly IEventDefinition<any>[];
1233
+ /** Resolved TOn when valid, or `any` when undefined (build will throw at runtime) */
1234
+ type ResolvedOn<TOn> = TOn extends ValidOnTarget ? TOn : any;
1235
+ interface HookFluentBuilder<TDeps extends DependencyMapType = {}, TOn extends ValidOnTarget | undefined = undefined, TMeta extends ITaskMeta = ITaskMeta> {
1124
1236
  id: string;
1125
- on<TNewOn extends "*" | IEventDefinition<any> | readonly IEventDefinition<any>[]>(on: TNewOn): HookFluentBuilder<TDeps, TNewOn, TMeta>;
1237
+ on<TNewOn extends ValidOnTarget>(on: TNewOn): HookFluentBuilder<TDeps, TNewOn, TMeta>;
1126
1238
  order(order: number): HookFluentBuilder<TDeps, TOn, TMeta>;
1127
1239
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | (() => TNewDeps), options?: {
1128
1240
  override?: false;
@@ -1134,10 +1246,20 @@ interface HookFluentBuilder<TDeps extends DependencyMapType = {}, TOn extends "*
1134
1246
  override?: boolean;
1135
1247
  }): HookFluentBuilder<TDeps, TOn, TMeta>;
1136
1248
  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>;
1249
+ /** Set the hook's run handler. Required before build(). */
1250
+ run(fn: IHookDefinition<TDeps, ResolvedOn<TOn>, TMeta>["run"]): HookFluentBuilder<TDeps, TOn, TMeta>;
1251
+ /**
1252
+ * Build the hook definition. Requires .on() and .run() to be called first.
1253
+ * @throws {Error} if on or run are not set
1254
+ */
1255
+ build(): IHook<TDeps, ResolvedOn<TOn>, TMeta>;
1139
1256
  }
1140
- declare function hookBuilder(id: string): HookFluentBuilder<{}, any, ITaskMeta>;
1257
+
1258
+ /**
1259
+ * Entry point for creating a hook builder.
1260
+ * Requires calling .on() and .run() before .build().
1261
+ */
1262
+ declare function hookBuilder(id: string): HookFluentBuilder<{}, undefined, ITaskMeta>;
1141
1263
 
1142
1264
  interface EventFluentBuilder<TPayload = void> {
1143
1265
  id: string;
@@ -1156,69 +1278,98 @@ interface EventFluentBuilder<TPayload = void> {
1156
1278
  parallel(enabled?: boolean): EventFluentBuilder<TPayload>;
1157
1279
  build(): IEvent<TPayload>;
1158
1280
  }
1159
- declare function eventBuilder(id: string): EventFluentBuilder<void>;
1160
1281
 
1161
- interface PhantomTaskFluentBuilder<TInput = undefined, TResolved = any, TDeps extends DependencyMapType = {}, TMeta extends ITaskMeta = ITaskMeta, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> {
1282
+ /**
1283
+ * Entry point for creating an event builder.
1284
+ */
1285
+ declare function eventBuilder<TPayload = void>(id: string): EventFluentBuilder<TPayload>;
1286
+
1287
+ type ShouldReplaceInput<T> = [T] extends [undefined] ? true : [T] extends [void] ? true : 0 extends 1 & T ? true : false;
1288
+ type ResolveInput<TExisting, TProposed> = ShouldReplaceInput<TExisting> extends true ? TProposed : TExisting;
1289
+
1290
+ /**
1291
+ * Fluent builder interface for constructing tasks.
1292
+ */
1293
+ 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
1294
  id: string;
1163
1295
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | (() => TNewDeps), options?: {
1164
1296
  override?: false;
1165
- }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps & TNewDeps, TMeta, TTags, TMiddleware>;
1297
+ }): TaskFluentBuilder<TInput, TOutput, TDeps & TNewDeps, TMeta, TTags, TMiddleware>;
1166
1298
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | (() => TNewDeps), options: {
1167
1299
  override: true;
1168
- }): PhantomTaskFluentBuilder<TInput, TResolved, TNewDeps, TMeta, TTags, TMiddleware>;
1300
+ }): TaskFluentBuilder<TInput, TOutput, TNewDeps, TMeta, TTags, TMiddleware>;
1169
1301
  middleware<TNewMw extends TaskMiddlewareAttachmentType[]>(mw: TNewMw, options?: {
1170
1302
  override?: boolean;
1171
- }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, TTags, TNewMw>;
1303
+ }): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, TTags, TNewMw>;
1172
1304
  tags<TNewTags extends TagType[]>(t: TNewTags, options?: {
1173
1305
  override?: false;
1174
- }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, [
1306
+ }): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, [
1175
1307
  ...TTags,
1176
1308
  ...TNewTags
1177
1309
  ], TMiddleware>;
1178
1310
  tags<TNewTags extends TagType[]>(t: TNewTags, options: {
1179
1311
  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>;
1312
+ }): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, TNewTags, TMiddleware>;
1313
+ inputSchema<TNewInput>(schema: IValidationSchema<TNewInput>): TaskFluentBuilder<TNewInput, TOutput, TDeps, TMeta, TTags, TMiddleware>;
1314
+ resultSchema<TResolved>(schema: IValidationSchema<TResolved>): TaskFluentBuilder<TInput, Promise<TResolved>, TDeps, TMeta, TTags, TMiddleware>;
1315
+ 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>;
1316
+ throws(list: ThrowsList): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, TTags, TMiddleware>;
1317
+ meta<TNewMeta extends ITaskMeta>(m: TNewMeta): TaskFluentBuilder<TInput, TOutput, TDeps, TNewMeta, TTags, TMiddleware>;
1318
+ build(): ITask<TInput, TOutput, TDeps, TMeta, TTags, TMiddleware>;
1185
1319
  }
1186
1320
 
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[]> {
1321
+ /**
1322
+ * Fluent builder interface for constructing phantom tasks.
1323
+ */
1324
+ interface PhantomTaskFluentBuilder<TInput = undefined, TResolved = any, TDeps extends DependencyMapType = {}, TMeta extends ITaskMeta = ITaskMeta, TTags extends TagType[] = TagType[], TMiddleware extends TaskMiddlewareAttachmentType[] = TaskMiddlewareAttachmentType[]> {
1190
1325
  id: string;
1191
1326
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | (() => TNewDeps), options?: {
1192
1327
  override?: false;
1193
- }): TaskFluentBuilder<TInput, TOutput, TDeps & TNewDeps, TMeta, TTags, TMiddleware>;
1328
+ }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps & TNewDeps, TMeta, TTags, TMiddleware>;
1194
1329
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | (() => TNewDeps), options: {
1195
1330
  override: true;
1196
- }): TaskFluentBuilder<TInput, TOutput, TNewDeps, TMeta, TTags, TMiddleware>;
1331
+ }): PhantomTaskFluentBuilder<TInput, TResolved, TNewDeps, TMeta, TTags, TMiddleware>;
1197
1332
  middleware<TNewMw extends TaskMiddlewareAttachmentType[]>(mw: TNewMw, options?: {
1198
1333
  override?: boolean;
1199
- }): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, TTags, TNewMw>;
1334
+ }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, TTags, TNewMw>;
1200
1335
  tags<TNewTags extends TagType[]>(t: TNewTags, options?: {
1201
1336
  override?: false;
1202
- }): TaskFluentBuilder<TInput, TOutput, TDeps, TMeta, [
1337
+ }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, [
1203
1338
  ...TTags,
1204
1339
  ...TNewTags
1205
1340
  ], TMiddleware>;
1206
1341
  tags<TNewTags extends TagType[]>(t: TNewTags, options: {
1207
1342
  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>;
1343
+ }): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, TNewTags, TMiddleware>;
1344
+ inputSchema<TNewInput>(schema: IValidationSchema<TNewInput>): PhantomTaskFluentBuilder<TNewInput, TResolved, TDeps, TMeta, TTags, TMiddleware>;
1345
+ resultSchema<TNewResolved>(schema: IValidationSchema<TNewResolved>): PhantomTaskFluentBuilder<TInput, TNewResolved, TDeps, TMeta, TTags, TMiddleware>;
1346
+ meta<TNewMeta extends ITaskMeta>(m: TNewMeta): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TNewMeta, TTags, TMiddleware>;
1347
+ throws(list: ThrowsList): PhantomTaskFluentBuilder<TInput, TResolved, TDeps, TMeta, TTags, TMiddleware>;
1348
+ build(): IPhantomTask<TInput, TResolved, TDeps, TMeta, TTags, TMiddleware>;
1214
1349
  }
1350
+
1351
+ /**
1352
+ * Entry point for creating a phantom task builder.
1353
+ */
1354
+ declare function phantomTaskBuilder<TInput = undefined, TResolved = any>(id: string): PhantomTaskFluentBuilder<TInput, TResolved, {}, ITaskMeta, TagType[], TaskMiddlewareAttachmentType[]>;
1215
1355
  interface TaskBuilderWithPhantom {
1216
1356
  (id: string): TaskFluentBuilder<undefined, Promise<any>, {}, ITaskMeta, TagType[], TaskMiddlewareAttachmentType[]>;
1217
- phantom: <TInput = undefined, TResolved = any>(id: string) => PhantomTaskFluentBuilder<TInput, TResolved, {}, ITaskMeta, TagType[], TaskMiddlewareAttachmentType[]>;
1357
+ phantom: typeof phantomTaskBuilder;
1218
1358
  }
1219
1359
 
1360
+ /**
1361
+ * Helper type to determine if config should be replaced.
1362
+ */
1220
1363
  type ShouldReplaceConfig<T> = [T] extends [void] ? true : [T] extends [undefined] ? true : false;
1364
+ /**
1365
+ * Resolves the config type - uses proposed if existing is void/undefined.
1366
+ */
1221
1367
  type ResolveConfig<TExisting, TProposed> = ShouldReplaceConfig<TExisting> extends true ? TProposed : TExisting;
1368
+
1369
+ /**
1370
+ * Fluent builder interface for constructing resources.
1371
+ * Each method returns a new builder with updated type parameters.
1372
+ */
1222
1373
  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
1374
  id: string;
1224
1375
  dependencies<TNewDeps extends DependencyMapType>(deps: TNewDeps | ((config: TConfig) => TNewDeps), options?: {
@@ -1248,19 +1399,220 @@ interface ResourceFluentBuilder<TConfig = void, TValue extends Promise<any> = Pr
1248
1399
  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
1400
  dispose(fn: NonNullable<IResourceDefinition<TConfig, TValue, TDeps, TContext, any, any, TMeta, TTags, TMiddleware>["dispose"]>): ResourceFluentBuilder<TConfig, TValue, TDeps, TContext, TMeta, TTags, TMiddleware>;
1250
1401
  meta<TNewMeta extends IResourceMeta>(m: TNewMeta): ResourceFluentBuilder<TConfig, TValue, TDeps, TContext, TNewMeta, TTags, TMiddleware>;
1402
+ throws(list: ThrowsList): ResourceFluentBuilder<TConfig, TValue, TDeps, TContext, TMeta, TTags, TMiddleware>;
1251
1403
  overrides(o: Array<OverridableElements>, options?: {
1252
1404
  override?: boolean;
1253
1405
  }): ResourceFluentBuilder<TConfig, TValue, TDeps, TContext, TMeta, TTags, TMiddleware>;
1254
1406
  build(): IResource<TConfig, TValue, TDeps, TContext, TMeta, TTags, TMiddleware>;
1255
1407
  }
1256
- declare function resourceBuilder<TConfig = void>(id: string): ResourceFluentBuilder<TConfig, Promise<any>, {}, any, IResourceMeta, TagType[], ResourceMiddlewareAttachmentType[]>;
1257
-
1258
- interface Serializer {
1408
+
1409
+ /**
1410
+ * Creates a new resource builder with the given id.
1411
+ * Overload allows callers to seed the config type at the entry point for convenience.
1412
+ */
1413
+ declare function resourceBuilder<TConfig = void>(id: string): ResourceFluentBuilder<TConfig, Promise<any>, {}, any, IResourceMeta, TagType[], ResourceMiddlewareAttachmentType[]>;
1414
+
1415
+ /**
1416
+ * Type definitions for the Serializer class
1417
+ */
1418
+ /**
1419
+ * Definition for a custom type that can be serialized/deserialized
1420
+ */
1421
+ interface TypeDefinition<TInstance = unknown, TSerialized = unknown> {
1422
+ /** Unique identifier for the type */
1423
+ id: string;
1424
+ /** Predicate function to check if an object matches this type */
1425
+ is: (obj: unknown) => obj is TInstance;
1426
+ /** Function to serialize the object */
1427
+ serialize: (obj: TInstance) => TSerialized;
1428
+ /** Function to deserialize the data back to the original object */
1429
+ deserialize: (data: TSerialized) => TInstance;
1430
+ /** Optional factory used to create a placeholder during deserialization */
1431
+ create?: () => TInstance;
1432
+ /** Serialization strategy: 'value' (inline, no identity) or 'ref' (graph node, identity preserved). Default: 'ref' */
1433
+ strategy?: "value" | "ref";
1434
+ }
1435
+ /** Reference to another object in the serialization */
1436
+ interface ObjectReference {
1437
+ /** Reference to object ID */
1438
+ __ref: string;
1439
+ }
1440
+ /**
1441
+ * Discriminated union describing the serialized graph payload.
1442
+ * Each node captures either an array, plain object, or typed payload.
1443
+ */
1444
+ type SerializedNode = {
1445
+ kind: "array";
1446
+ value: SerializedValue[];
1447
+ } | {
1448
+ kind: "object";
1449
+ value: Record<string, SerializedValue>;
1450
+ } | {
1451
+ kind: "type";
1452
+ type: string;
1453
+ value: SerializedValue;
1454
+ };
1455
+ /**
1456
+ * Serialization context for tracking object references
1457
+ */
1458
+ interface SerializationContext {
1459
+ /** Map of objects to their IDs */
1460
+ objectIds: WeakMap<object, string>;
1461
+ /** Counter for generating unique IDs */
1462
+ idCounter: number;
1463
+ /** Number of graph nodes recorded */
1464
+ nodeCount: number;
1465
+ /** Nodes collected during serialization (id -> serialized node) */
1466
+ nodes: Record<string, SerializedNode>;
1467
+ }
1468
+ /**
1469
+ * Deserialization context used when materialising a graph payload.
1470
+ */
1471
+ interface DeserializationContext {
1472
+ nodes: Record<string, SerializedNode>;
1473
+ resolved: Map<string, unknown>;
1474
+ resolving: Set<string>;
1475
+ /**
1476
+ * Tracks reference ids that were requested while still being resolved.
1477
+ * Used to detect circular references that rely on placeholders.
1478
+ */
1479
+ resolvingRefs: Set<string>;
1480
+ }
1481
+ /**
1482
+ * Union type for serialized values
1483
+ */
1484
+ type JsonPrimitive = string | number | boolean | null;
1485
+ interface SerializedTypeRecord {
1486
+ __type: string;
1487
+ value: SerializedValue;
1488
+ }
1489
+ type SerializedValue = JsonPrimitive | ObjectReference | SerializedTypeRecord | SerializedValue[] | {
1490
+ [key: string]: SerializedValue;
1491
+ };
1492
+ declare enum SymbolPolicy {
1493
+ AllowAll = "AllowAll",
1494
+ WellKnownOnly = "WellKnownOnly",
1495
+ Disabled = "Disabled"
1496
+ }
1497
+ /**
1498
+ * Main serializer options
1499
+ */
1500
+ interface SerializerOptions {
1501
+ /** Whether to pretty-print JSON (for debugging) */
1502
+ pretty?: boolean;
1503
+ /** Maximum recursion depth allowed during serialize/deserialize */
1504
+ maxDepth?: number;
1505
+ /** Restrict deserialization to this list of type IDs */
1506
+ allowedTypes?: readonly string[];
1507
+ /** Controls which Symbol payloads may be deserialized */
1508
+ symbolPolicy?: SymbolPolicy;
1509
+ /** Maximum accepted RegExp pattern length during deserialization */
1510
+ maxRegExpPatternLength?: number;
1511
+ /** Allow RegExp patterns that fail the safety heuristic */
1512
+ allowUnsafeRegExp?: boolean;
1513
+ }
1514
+ /**
1515
+ * Minimal serializer contract used across transports and persistence.
1516
+ * Implementations must be able to round-trip JSON-compatible payloads and
1517
+ * should support custom value types via `addType`.
1518
+ */
1519
+ interface SerializerLike {
1259
1520
  stringify(value: unknown): string;
1260
1521
  parse<T = unknown>(text: string): T;
1261
- addType?<TJson = unknown, T = unknown>(name: string, factory: (json: TJson) => T): void;
1522
+ addType?<TJson = unknown, TInstance = unknown>(name: string, factory: (json: TJson) => TInstance): void;
1523
+ }
1524
+
1525
+ /**
1526
+ * Graph-aware serializer/deserializer with circular reference
1527
+ * handling and pluggable type support.
1528
+ *
1529
+ * Internal protocol reference: `readmes/SERIALIZER_PROTOCOL.md`.
1530
+ */
1531
+
1532
+ declare class Serializer {
1533
+ /** Type registry for managing custom types */
1534
+ private readonly typeRegistry;
1535
+ private readonly runtimeOptions;
1536
+ /** JSON indentation width when pretty printing is enabled */
1537
+ private readonly indent;
1538
+ /** Maximum recursion depth allowed */
1539
+ private readonly maxDepth;
1540
+ /** Maximum allowed RegExp pattern length during deserialization */
1541
+ private readonly maxRegExpPatternLength;
1542
+ /** Allow RegExp patterns that fail the safety heuristic */
1543
+ private readonly allowUnsafeRegExp;
1544
+ /** Disallowed keys that can lead to prototype pollution */
1545
+ private readonly unsafeKeys;
1546
+ constructor(options?: SerializerOptions);
1547
+ /**
1548
+ * Alias of `serialize()` to match the historical tunnel serializer surface.
1549
+ */
1550
+ stringify<T>(value: T): string;
1551
+ /**
1552
+ * Alias of `deserialize()` to match the historical tunnel serializer surface.
1553
+ */
1554
+ parse<T = unknown>(payload: string): T;
1555
+ /**
1556
+ * Serialize an arbitrary value into a JSON string.
1557
+ */
1558
+ serialize<T>(value: T, context?: SerializationContext): string;
1559
+ /**
1560
+ * Deserialize a JSON string back to its original value.
1561
+ */
1562
+ deserialize<T = unknown>(payload: string): T;
1563
+ /**
1564
+ * Register a custom type for serialization/deserialization.
1565
+ */
1566
+ addType<TInstance, TSerialized>(typeDef: TypeDefinition<TInstance, TSerialized>): void;
1567
+ addType<TJson = unknown, TInstance = unknown>(name: string, factory: (json: TJson) => TInstance): void;
1568
+ /**
1569
+ * @internal - Exposed for testing RegExp safety validation
1570
+ */
1571
+ readonly isRegExpPatternSafe: (pattern: string) => boolean;
1572
+ /**
1573
+ * @internal - Exposed for testing quantifier detection
1574
+ */
1575
+ readonly isQuantifierAt: (pattern: string, index: number) => boolean;
1576
+ /**
1577
+ * @internal - Exposed for testing quantifier character detection
1578
+ */
1579
+ readonly isQuantifierChar: (char: string, pattern: string, index: number) => boolean;
1580
+ /**
1581
+ * @internal - Exposed for testing bounded quantifier detection
1582
+ */
1583
+ readonly isBoundedQuantifier: (pattern: string, index: number) => boolean;
1584
+ /**
1585
+ * @internal - Exposed for test compatibility
1586
+ */
1587
+ toNodeRecord(nodes: Record<string, SerializedNode>): Record<string, SerializedNode>;
1588
+ /**
1589
+ * @internal - Exposed for test compatibility
1590
+ */
1591
+ deserializeValue(value: SerializedValue, context: DeserializationContext, depth?: number): unknown;
1592
+ /**
1593
+ * @internal - Exposed for test compatibility
1594
+ */
1595
+ resolveReference(id: string, context: DeserializationContext, depth?: number): unknown;
1596
+ /**
1597
+ * @internal - Exposed for test compatibility
1598
+ */
1599
+ mergePlaceholder(placeholder: unknown, result: unknown): unknown;
1600
+ /**
1601
+ * @internal - Exposed for test compatibility
1602
+ */
1603
+ isSerializedTypeRecord(value: unknown): value is {
1604
+ __type: string;
1605
+ value: unknown;
1606
+ };
1607
+ private jsonStringify;
1262
1608
  }
1263
1609
 
1610
+ /**
1611
+ * Main export module for the Serializer
1612
+ */
1613
+
1614
+ declare function getDefaultSerializer(): Serializer;
1615
+
1264
1616
  type TunnelMode = "client" | "server" | "both" | "none";
1265
1617
  type TunnelTaskSelector = Array<string | ITask<any, any, any, any, any, any>> | ((task: ITask<any, any, any, any, any, any>) => boolean);
1266
1618
  type TunnelEventSelector = Array<string | IEvent<any>> | ((event: IEvent<any>) => boolean);
@@ -1286,17 +1638,23 @@ interface ExposureFetchConfig {
1286
1638
  auth?: ExposureFetchAuthConfig;
1287
1639
  timeoutMs?: number;
1288
1640
  fetchImpl?: typeof fetch;
1289
- serializer: Serializer;
1641
+ serializer: SerializerLike;
1290
1642
  onRequest?: (ctx: {
1291
1643
  url: string;
1292
1644
  headers: Record<string, string>;
1293
1645
  }) => void | Promise<void>;
1294
- contexts?: Array<IAsyncContext<any>>;
1646
+ contexts?: Array<IAsyncContext<unknown>>;
1295
1647
  errorRegistry?: Map<string, IErrorHelper<any>>;
1296
1648
  }
1297
1649
  interface ExposureFetchClient {
1298
1650
  task<I = unknown, O = unknown>(id: string, input?: I): Promise<O>;
1299
1651
  event<P = unknown>(id: string, payload?: P): Promise<void>;
1652
+ /**
1653
+ * Emits an event and returns the final payload as seen by the remote Runner.
1654
+ * Requires server support; older servers will respond with `{ ok: true }`
1655
+ * without `result`, in which case clients should throw.
1656
+ */
1657
+ eventWithResult?<P = unknown>(id: string, payload?: P): Promise<P>;
1300
1658
  }
1301
1659
 
1302
1660
  declare function normalizeError(input: unknown): Error;
@@ -1319,7 +1677,7 @@ interface HttpCreateClientConfig {
1319
1677
  auth?: HttpClientAuthConfig;
1320
1678
  timeoutMs?: number;
1321
1679
  fetchImpl?: typeof fetch;
1322
- serializer: Serializer;
1680
+ serializer: SerializerLike;
1323
1681
  onRequest?: (ctx: {
1324
1682
  url: string;
1325
1683
  headers: Record<string, string>;
@@ -1327,19 +1685,27 @@ interface HttpCreateClientConfig {
1327
1685
  }
1328
1686
 
1329
1687
  type TunnelMiddlewareId = string | ITaskMiddleware<any, any, any, any>;
1688
+ interface TunnelTaskMiddlewareSidePolicy {
1689
+ /**
1690
+ * Middleware ids/definitions allowed to run on this side when the task is tunneled.
1691
+ * If omitted, defaults to allowing none (caller-side middleware is skipped by default).
1692
+ */
1693
+ middlewareAllowList?: TunnelMiddlewareId[];
1694
+ }
1695
+ type TunnelTaskMiddlewarePolicySideConfig = TunnelTaskMiddlewareSidePolicy | TunnelMiddlewareId[];
1330
1696
  interface TunnelTaskMiddlewarePolicyConfig {
1331
1697
  /**
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").
1698
+ * Preferred configuration shape: explicit per-side allowlist.
1335
1699
  */
1336
- client?: TunnelMiddlewareId[];
1700
+ client?: TunnelTaskMiddlewarePolicySideConfig;
1701
+ server?: TunnelTaskMiddlewarePolicySideConfig;
1337
1702
  /**
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.
1703
+ * Backwards-compatible configuration shape (previous): grouped allowlists.
1341
1704
  */
1342
- server?: TunnelMiddlewareId[];
1705
+ middlewareAllowList?: {
1706
+ client?: TunnelMiddlewareId[];
1707
+ server?: TunnelMiddlewareId[];
1708
+ };
1343
1709
  }
1344
1710
 
1345
1711
  interface TimeoutMiddlewareConfig {
@@ -1370,6 +1736,182 @@ interface RetryMiddlewareConfig {
1370
1736
  delayStrategy?: (attempt: number, error: Error) => number;
1371
1737
  }
1372
1738
 
1739
+ interface FallbackMiddlewareConfig {
1740
+ /**
1741
+ * The fallback to use if the task fails.
1742
+ * Can be a value, a function that returns a value (or promise), or another task.
1743
+ */
1744
+ fallback: any;
1745
+ }
1746
+
1747
+ declare const SemaphoreEvents: {
1748
+ readonly queued: IEvent<SemaphoreEvent>;
1749
+ readonly acquired: IEvent<SemaphoreEvent>;
1750
+ readonly released: IEvent<SemaphoreEvent>;
1751
+ readonly timeout: IEvent<SemaphoreEvent>;
1752
+ readonly aborted: IEvent<SemaphoreEvent>;
1753
+ readonly disposed: IEvent<SemaphoreEvent>;
1754
+ };
1755
+ type SemaphoreEventType = keyof typeof SemaphoreEvents;
1756
+ type SemaphoreEvent = {
1757
+ type: SemaphoreEventType;
1758
+ permits: number;
1759
+ waiting: number;
1760
+ maxPermits: number;
1761
+ disposed: boolean;
1762
+ };
1763
+ /**
1764
+ * A semaphore that limits the number of concurrent operations.
1765
+ * Used to prevent connection pool exhaustion by limiting concurrent
1766
+ * database operations to the pool size.
1767
+ */
1768
+ declare class Semaphore {
1769
+ private permits;
1770
+ private waitingHead;
1771
+ private waitingTail;
1772
+ private waitingCount;
1773
+ private disposed;
1774
+ private readonly maxPermits;
1775
+ private readonly eventManager;
1776
+ private listenerId;
1777
+ private activeListeners;
1778
+ constructor(maxPermits: number);
1779
+ /**
1780
+ * Acquire a permit. If no permits are available, waits until one becomes available.
1781
+ */
1782
+ acquire(options?: {
1783
+ timeout?: number;
1784
+ signal?: AbortSignal;
1785
+ }): Promise<void>;
1786
+ /**
1787
+ * Release a permit, allowing waiting operations to proceed.
1788
+ */
1789
+ release(): void;
1790
+ private removeFromQueue;
1791
+ /**
1792
+ * Execute a function with a permit, automatically releasing it afterwards.
1793
+ */
1794
+ withPermit<T>(fn: () => Promise<T>, options?: {
1795
+ timeout?: number;
1796
+ signal?: AbortSignal;
1797
+ }): Promise<T>;
1798
+ /**
1799
+ * Dispose the semaphore, rejecting all waiting operations and preventing new ones.
1800
+ */
1801
+ dispose(): void;
1802
+ /**
1803
+ * Get current number of available permits (for debugging)
1804
+ */
1805
+ getAvailablePermits(): number;
1806
+ /**
1807
+ * Get current number of waiting operations (for debugging)
1808
+ */
1809
+ getWaitingCount(): number;
1810
+ /**
1811
+ * Get maximum number of permits
1812
+ */
1813
+ getMaxPermits(): number;
1814
+ /**
1815
+ * Check if the semaphore has been disposed
1816
+ */
1817
+ isDisposed(): boolean;
1818
+ /**
1819
+ * Get metrics about the current state of the semaphore
1820
+ */
1821
+ getMetrics(): {
1822
+ availablePermits: number;
1823
+ waitingCount: number;
1824
+ maxPermits: number;
1825
+ utilization: number;
1826
+ disposed: boolean;
1827
+ };
1828
+ on(type: SemaphoreEventType, handler: (event: SemaphoreEvent) => any): () => void;
1829
+ once(type: SemaphoreEventType, handler: (event: SemaphoreEvent) => any): () => void;
1830
+ private enqueue;
1831
+ private dequeue;
1832
+ private emit;
1833
+ private buildEvent;
1834
+ }
1835
+
1836
+ interface ConcurrencyMiddlewareConfig {
1837
+ /**
1838
+ * Maximum number of concurrent executions.
1839
+ * If provided, a Semaphore will be created and shared for this config object.
1840
+ */
1841
+ limit?: number;
1842
+ /**
1843
+ * Optional key to identify a shared semaphore.
1844
+ * If provided, the semaphore will be shared across all tasks using the same key.
1845
+ */
1846
+ key?: string;
1847
+ /**
1848
+ * An existing Semaphore instance to use.
1849
+ */
1850
+ semaphore?: Semaphore;
1851
+ }
1852
+
1853
+ interface TemporalMiddlewareConfig {
1854
+ ms: number;
1855
+ }
1856
+ interface DebounceState {
1857
+ timeoutId?: NodeJS.Timeout;
1858
+ latestInput?: any;
1859
+ resolveList: ((value: any) => void)[];
1860
+ rejectList: ((error: any) => void)[];
1861
+ }
1862
+ interface ThrottleState {
1863
+ lastExecution: number;
1864
+ timeoutId?: NodeJS.Timeout;
1865
+ latestInput?: any;
1866
+ resolveList: ((value: any) => void)[];
1867
+ rejectList: ((error: any) => void)[];
1868
+ currentPromise?: Promise<any>;
1869
+ }
1870
+
1871
+ /**
1872
+ * States of the Circuit Breaker
1873
+ */
1874
+ declare enum CircuitBreakerState {
1875
+ CLOSED = "CLOSED",
1876
+ OPEN = "OPEN",
1877
+ HALF_OPEN = "HALF_OPEN"
1878
+ }
1879
+ /**
1880
+ * Configuration for the Circuit Breaker middleware
1881
+ */
1882
+ interface CircuitBreakerMiddlewareConfig {
1883
+ /**
1884
+ * Number of failures before tripping the circuit
1885
+ * @default 5
1886
+ */
1887
+ failureThreshold?: number;
1888
+ /**
1889
+ * Time in milliseconds before transitioning from OPEN to HALF_OPEN
1890
+ * @default 30000 (30 seconds)
1891
+ */
1892
+ resetTimeout?: number;
1893
+ }
1894
+ interface CircuitBreakerStatus {
1895
+ state: CircuitBreakerState;
1896
+ failures: number;
1897
+ lastFailureTime: number;
1898
+ }
1899
+
1900
+ interface RateLimitMiddlewareConfig {
1901
+ /**
1902
+ * Time window in milliseconds
1903
+ */
1904
+ windowMs: number;
1905
+ /**
1906
+ * Maximum number of requests within the window
1907
+ */
1908
+ max: number;
1909
+ }
1910
+ interface RateLimitState {
1911
+ count: number;
1912
+ resetTime: number;
1913
+ }
1914
+
1373
1915
  /**
1374
1916
  * Options for configuring event listeners.
1375
1917
  */
@@ -1404,9 +1946,9 @@ declare class EventManager {
1404
1946
  private hookInterceptors;
1405
1947
  private readonly registry;
1406
1948
  private readonly cycleContext;
1407
- private readonly runtimeCycleDetection;
1949
+ private readonly runtimeEventCycleDetection;
1408
1950
  constructor(options?: {
1409
- runtimeCycleDetection?: boolean;
1951
+ runtimeEventCycleDetection?: boolean;
1410
1952
  });
1411
1953
  /**
1412
1954
  * Gets the current lock status of the EventManager
@@ -1425,6 +1967,16 @@ declare class EventManager {
1425
1967
  * @param source - The source identifier of the event emitter
1426
1968
  */
1427
1969
  emit<TInput>(eventDefinition: IEvent<TInput>, data: TInput, source: string): Promise<void>;
1970
+ /**
1971
+ * Emits an event and returns the final payload.
1972
+ * The payload is taken from the deepest emission object that reached either:
1973
+ * - the base listener executor, or
1974
+ * - an interceptor that short-circuited the emission.
1975
+ *
1976
+ * This enables tunnel transports to return the final payload after local and/or remote delivery.
1977
+ */
1978
+ emitWithResult<TInput>(eventDefinition: IEvent<TInput>, data: TInput, source: string): Promise<TInput>;
1979
+ private emitAndReturnEmission;
1428
1980
  /**
1429
1981
  * Registers an event listener for specific event(s).
1430
1982
  * Listeners are ordered by priority and executed in ascending order.
@@ -1479,6 +2031,16 @@ declare class EventManager {
1479
2031
  * Throws an error if the EventManager is locked
1480
2032
  */
1481
2033
  private checkLock;
2034
+ /**
2035
+ * Clears all listeners and interceptors.
2036
+ * Call this to release references and free memory.
2037
+ */
2038
+ clear(): void;
2039
+ /**
2040
+ * Disposes the EventManager, releasing all listeners and interceptors.
2041
+ * Alias for clear() following the IResource disposal pattern.
2042
+ */
2043
+ dispose(): void;
1482
2044
  /**
1483
2045
  * Retrieves cached merged listeners for an event, or creates them if not cached.
1484
2046
  * Kept for backward compatibility (tests spy on this).
@@ -1490,7 +2052,7 @@ declare class TaskRunner {
1490
2052
  protected readonly store: Store;
1491
2053
  protected readonly eventManager: EventManager;
1492
2054
  protected readonly logger: Logger;
1493
- protected readonly runnerStore: Map<string | symbol, (input: any) => Promise<any>>;
2055
+ protected readonly runnerStore: Map<string | symbol, (input: any, journal?: ExecutionJournal) => Promise<any>>;
1494
2056
  constructor(store: Store, eventManager: EventManager, logger: Logger);
1495
2057
  private readonly middlewareManager;
1496
2058
  /**
@@ -1498,8 +2060,9 @@ declare class TaskRunner {
1498
2060
  * This function can throw only if any of the event listeners or run function throws
1499
2061
  * @param task the task to be run
1500
2062
  * @param input the input to be passed to the task
2063
+ * @param options optional call options including journal for forwarding
1501
2064
  */
1502
- run<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>, input?: TInput): Promise<TOutput | undefined>;
2065
+ run<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>, input?: TInput, options?: TaskCallOptions): Promise<TOutput | undefined>;
1503
2066
  /**
1504
2067
  * Creates the function with the chain of middleware.
1505
2068
  * @param task
@@ -1507,7 +2070,7 @@ declare class TaskRunner {
1507
2070
  * @param taskDependencies
1508
2071
  * @returns
1509
2072
  */
1510
- protected createRunnerWithMiddleware<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>): (input: TInput) => Promise<Awaited<TOutput>>;
2073
+ protected createRunnerWithMiddleware<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>): (input: TInput, parentJournal?: ExecutionJournal) => Promise<Awaited<TOutput>>;
1511
2074
  }
1512
2075
 
1513
2076
  /**
@@ -1571,7 +2134,7 @@ declare class MiddlewareManager {
1571
2134
  * Compose a runner for a task with its local interceptors and applicable middlewares.
1572
2135
  * Returns a function that accepts the task input and resolves to the task output.
1573
2136
  */
1574
- composeTaskRunner<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>): (input: TInput) => Promise<Awaited<TOutput>>;
2137
+ composeTaskRunner<TInput, TOutput extends Promise<any>, TDeps extends DependencyMapType>(task: ITask<TInput, TOutput, TDeps>): (input: TInput, parentJournal?: ExecutionJournal) => Promise<Awaited<TOutput>>;
1575
2138
  /**
1576
2139
  * Run a resource init wrapped with its applicable middlewares.
1577
2140
  */
@@ -1602,6 +2165,7 @@ declare class Store {
1602
2165
  private validator;
1603
2166
  private taskRunner?;
1604
2167
  private middlewareManager;
2168
+ private readonly initializedResourceIds;
1605
2169
  mode: RunnerMode;
1606
2170
  constructor(eventManager: EventManager, logger: Logger, onUnhandledError: OnUnhandledError, mode?: RunnerMode);
1607
2171
  get tasks(): Map<string, TaskStoreElementType>;
@@ -1613,7 +2177,7 @@ declare class Store {
1613
2177
  get taskMiddlewares(): Map<string, TaskMiddlewareStoreElementType>;
1614
2178
  get resourceMiddlewares(): Map<string, ResourceMiddlewareStoreElementType>;
1615
2179
  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>[]>>;
2180
+ 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
2181
  get overrideRequests(): Set<{
1618
2182
  source: string;
1619
2183
  override: RegisterableItems;
@@ -1629,6 +2193,8 @@ declare class Store {
1629
2193
  validateEventEmissionGraph(): void;
1630
2194
  initializeStore(root: IResource<any, any, any, any, any>, config: any): void;
1631
2195
  dispose(): Promise<void>;
2196
+ recordResourceInitialized(resourceId: string): void;
2197
+ private getResourcesInDisposeOrder;
1632
2198
  /**
1633
2199
  * Internal, avoid using this method directly.
1634
2200
  */
@@ -1664,16 +2230,14 @@ declare class ResourceInitializer {
1664
2230
  * This function can throw only if any of the event listeners or run function throws
1665
2231
  */
1666
2232
  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;
2233
+ value: TValue | undefined;
1668
2234
  context: TContext;
1669
2235
  }>;
1670
2236
  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
2237
  }
1672
2238
 
1673
2239
  /**
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.
2240
+ * Resolves and caches computed dependencies for store items (resources, tasks, middleware, hooks).
1677
2241
  */
1678
2242
  declare class DependencyProcessor {
1679
2243
  protected readonly store: Store;
@@ -1683,21 +2247,21 @@ declare class DependencyProcessor {
1683
2247
  protected readonly logger: Logger;
1684
2248
  constructor(store: Store, eventManager: EventManager, taskRunner: TaskRunner, logger: Logger);
1685
2249
  /**
1686
- * This function is going to go through all the resources, tasks and middleware to compute their required dependencies.
2250
+ * Computes and caches dependencies for all registered store items.
1687
2251
  */
1688
2252
  computeAllDependencies(): Promise<void>;
1689
2253
  private computeTaskDependencies;
1690
2254
  initializeUninitializedResources(): Promise<void>;
2255
+ private rethrowResourceInitError;
1691
2256
  /**
1692
- * Processes dependencies and hooks
1693
- * @param resource
2257
+ * Computes and caches dependencies for a resource (if not already computed).
1694
2258
  */
1695
2259
  protected processResourceDependencies<TD extends DependencyMapType>(resource: ResourceStoreElementType<any, any, TD>): Promise<void>;
1696
2260
  private wrapResourceDependencies;
1697
2261
  private makeTaskWithIntercept;
1698
2262
  initializeRoot(): Promise<void>;
1699
2263
  /**
1700
- * Processes all hooks, should run before emission of any event.
2264
+ * Attaches listeners for all hooks. Must run before emitting events.
1701
2265
  */
1702
2266
  attachListeners(): void;
1703
2267
  extractDependencies<T extends DependencyMapType>(map: T, source: string): Promise<DependencyValuesType<T>>;
@@ -1708,72 +2272,25 @@ declare class DependencyProcessor {
1708
2272
  * @returns
1709
2273
  */
1710
2274
  extractEventDependency(object: IEvent<any>, source: string): (input: any) => Promise<void>;
1711
- extractTaskDependency(object: ITask<any, any, {}>): Promise<(input: unknown) => Promise<any>>;
2275
+ extractTaskDependency(object: ITask<any, any, {}>): Promise<(input: unknown, options?: TaskCallOptions) => Promise<any>>;
1712
2276
  extractResourceDependency(object: IResource<any, any, any>): Promise<any>;
1713
2277
  }
1714
2278
 
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
-
2279
+ declare const QueueEvents: {
2280
+ readonly enqueue: IEvent<QueueEvent>;
2281
+ readonly start: IEvent<QueueEvent>;
2282
+ readonly finish: IEvent<QueueEvent>;
2283
+ readonly error: IEvent<QueueEvent>;
2284
+ readonly cancel: IEvent<QueueEvent>;
2285
+ readonly disposed: IEvent<QueueEvent>;
2286
+ };
2287
+ type QueueEventType = keyof typeof QueueEvents;
2288
+ type QueueEvent = {
2289
+ type: QueueEventType;
2290
+ taskId: number;
2291
+ disposed: boolean;
2292
+ error?: Error;
2293
+ };
1777
2294
  /**
1778
2295
  * Cooperative task queue.
1779
2296
  * • Tasks run one‑after‑another (FIFO ordering).
@@ -1784,6 +2301,10 @@ declare class Queue {
1784
2301
  private tail;
1785
2302
  private disposed;
1786
2303
  private abortController;
2304
+ private readonly eventManager;
2305
+ private nextTaskId;
2306
+ private listenerId;
2307
+ private activeListeners;
1787
2308
  private readonly executionContext;
1788
2309
  private readonly hasAsyncLocalStorage;
1789
2310
  /**
@@ -1799,6 +2320,9 @@ declare class Queue {
1799
2320
  dispose(options?: {
1800
2321
  cancel?: boolean;
1801
2322
  }): Promise<void>;
2323
+ on(type: QueueEventType, handler: (event: QueueEvent) => any): () => void;
2324
+ once(type: QueueEventType, handler: (event: QueueEvent) => any): () => void;
2325
+ private emit;
1802
2326
  }
1803
2327
 
1804
2328
  declare class RunResult<V> {
@@ -1876,8 +2400,9 @@ type AnyResource = IResource<any, any, any, any, any, any, any>;
1876
2400
  type AnyTaskMiddleware = ITaskMiddleware<any, any, any, any>;
1877
2401
  type AnyResourceMiddleware = IResourceMiddleware<any, any, any, any>;
1878
2402
  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;
2403
+ type AnyOverrideable = AnyTask | AnyResource | AnyTaskMiddleware | AnyResourceMiddleware | AnyHook;
2404
+ type OverridePatch<TBase extends AnyOverrideable> = Readonly<TBase extends AnyHook ? Omit<Partial<TBase>, "id" | "on"> : Omit<Partial<TBase>, "id">>;
2405
+ declare function defineOverride<TBase extends AnyOverrideable>(base: TBase, patch: OverridePatch<TBase>): TBase;
1881
2406
 
1882
2407
  /**
1883
2408
  * Create a tag definition.
@@ -1932,68 +2457,83 @@ declare class PlatformAdapter implements IPlatformAdapter {
1932
2457
  clearTimeout: typeof clearTimeout;
1933
2458
  }
1934
2459
 
1935
- declare const duplicateRegistrationError: ErrorHelper<{
2460
+ declare const duplicateRegistrationError: IErrorHelper<{
1936
2461
  type: string;
1937
2462
  id: string;
1938
2463
  } & DefaultErrorType>;
1939
- declare const dependencyNotFoundError: ErrorHelper<{
2464
+ declare const dependencyNotFoundError: IErrorHelper<{
1940
2465
  key: string;
1941
2466
  } & DefaultErrorType>;
1942
- declare const unknownItemTypeError: ErrorHelper<{
2467
+ declare const unknownItemTypeError: IErrorHelper<{
1943
2468
  item: unknown;
1944
2469
  } & DefaultErrorType>;
1945
- declare const contextError: ErrorHelper<{
2470
+ declare const contextError: IErrorHelper<{
1946
2471
  details?: string;
1947
2472
  } & DefaultErrorType>;
1948
- declare const circularDependenciesError: ErrorHelper<{
2473
+ declare const circularDependenciesError: IErrorHelper<{
1949
2474
  cycles: string[];
1950
2475
  } & DefaultErrorType>;
1951
- declare const eventNotFoundError: ErrorHelper<{
2476
+ declare const eventNotFoundError: IErrorHelper<{
1952
2477
  id: string;
1953
2478
  } & DefaultErrorType>;
1954
- declare const resourceNotFoundError: ErrorHelper<{
2479
+ declare const resourceNotFoundError: IErrorHelper<{
1955
2480
  id: string;
1956
2481
  } & DefaultErrorType>;
1957
- declare const middlewareNotRegisteredError: ErrorHelper<{
2482
+ declare const middlewareNotRegisteredError: IErrorHelper<{
1958
2483
  type: "task" | "resource";
1959
2484
  source: string;
1960
2485
  middlewareId: string;
1961
2486
  } & DefaultErrorType>;
1962
- declare const tagNotFoundError: ErrorHelper<{
2487
+ declare const tagNotFoundError: IErrorHelper<{
1963
2488
  id: string;
1964
2489
  } & DefaultErrorType>;
1965
- declare const lockedError: ErrorHelper<{
2490
+ declare const lockedError: IErrorHelper<{
1966
2491
  what: string;
1967
2492
  } & DefaultErrorType>;
1968
- declare const storeAlreadyInitializedError: ErrorHelper<DefaultErrorType>;
1969
- declare const validationError: ErrorHelper<{
2493
+ declare const storeAlreadyInitializedError: IErrorHelper<DefaultErrorType>;
2494
+ declare const validationError: IErrorHelper<{
1970
2495
  subject: string;
1971
2496
  id: string;
1972
2497
  originalError: string | Error;
1973
2498
  } & DefaultErrorType>;
1974
- declare const eventCycleError: ErrorHelper<{
2499
+ declare const eventCycleError: IErrorHelper<{
1975
2500
  path: Array<{
1976
2501
  id: string;
1977
2502
  source: string;
1978
2503
  }>;
1979
2504
  } & DefaultErrorType>;
1980
- declare const eventEmissionCycleError: ErrorHelper<{
2505
+ declare const eventEmissionCycleError: IErrorHelper<{
1981
2506
  cycles: string[];
1982
2507
  } & DefaultErrorType>;
1983
- declare const platformUnsupportedFunctionError: ErrorHelper<{
2508
+ declare const platformUnsupportedFunctionError: IErrorHelper<{
1984
2509
  functionName: string;
1985
2510
  } & DefaultErrorType>;
1986
- declare const cancellationError: ErrorHelper<{
2511
+ declare const cancellationError: IErrorHelper<{
1987
2512
  reason?: string;
1988
2513
  } & DefaultErrorType>;
1989
- declare const tunnelOwnershipConflictError: ErrorHelper<{
2514
+ declare const tunnelOwnershipConflictError: IErrorHelper<{
1990
2515
  taskId: string;
1991
2516
  currentOwnerId: string;
1992
2517
  attemptedOwnerId: string;
1993
2518
  } & DefaultErrorType>;
2519
+ declare const phantomTaskNotRoutedError: IErrorHelper<{
2520
+ taskId: string;
2521
+ } & DefaultErrorType>;
2522
+ declare const taskNotRegisteredError: IErrorHelper<{
2523
+ taskId: string;
2524
+ } & DefaultErrorType>;
2525
+ /** Builder types that require validation before build() */
2526
+ type BuilderType = "hook" | "task-middleware" | "resource-middleware";
2527
+ declare const builderIncompleteError: IErrorHelper<{
2528
+ type: BuilderType;
2529
+ builderId: string;
2530
+ missingFields: string[];
2531
+ } & DefaultErrorType>;
1994
2532
  declare function isCancellationError(err: unknown): boolean;
1995
2533
 
2534
+ type errors_BuilderType = BuilderType;
1996
2535
  type errors_IErrorHelper<TData extends DefaultErrorType = DefaultErrorType> = IErrorHelper<TData>;
2536
+ declare const errors_builderIncompleteError: typeof builderIncompleteError;
1997
2537
  declare const errors_cancellationError: typeof cancellationError;
1998
2538
  declare const errors_circularDependenciesError: typeof circularDependenciesError;
1999
2539
  declare const errors_contextError: typeof contextError;
@@ -2005,15 +2545,17 @@ declare const errors_eventNotFoundError: typeof eventNotFoundError;
2005
2545
  declare const errors_isCancellationError: typeof isCancellationError;
2006
2546
  declare const errors_lockedError: typeof lockedError;
2007
2547
  declare const errors_middlewareNotRegisteredError: typeof middlewareNotRegisteredError;
2548
+ declare const errors_phantomTaskNotRoutedError: typeof phantomTaskNotRoutedError;
2008
2549
  declare const errors_platformUnsupportedFunctionError: typeof platformUnsupportedFunctionError;
2009
2550
  declare const errors_resourceNotFoundError: typeof resourceNotFoundError;
2010
2551
  declare const errors_storeAlreadyInitializedError: typeof storeAlreadyInitializedError;
2011
2552
  declare const errors_tagNotFoundError: typeof tagNotFoundError;
2553
+ declare const errors_taskNotRegisteredError: typeof taskNotRegisteredError;
2012
2554
  declare const errors_tunnelOwnershipConflictError: typeof tunnelOwnershipConflictError;
2013
2555
  declare const errors_unknownItemTypeError: typeof unknownItemTypeError;
2014
2556
  declare const errors_validationError: typeof validationError;
2015
2557
  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 };
2558
+ 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
2559
  }
2018
2560
 
2019
2561
  /**
@@ -2061,6 +2603,27 @@ declare function buildTestFacade(deps: {
2061
2603
  eventManager: EventManager;
2062
2604
  };
2063
2605
 
2606
+ type HookOn = "*" | IEventDefinition<any> | readonly IEventDefinition<any>[];
2607
+ interface HookOverrideBuilder<TDeps extends DependencyMapType, TOn extends HookOn, TMeta extends ITaskMeta> {
2608
+ id: string;
2609
+ order(order: number): HookOverrideBuilder<TDeps, TOn, TMeta>;
2610
+ dependencies<TNewDeps extends DependencyMapType, TIsOverride extends boolean = false>(deps: TNewDeps | (() => TNewDeps), options?: {
2611
+ override?: TIsOverride;
2612
+ }): HookOverrideBuilder<TIsOverride extends true ? TNewDeps : TDeps & TNewDeps, TOn, TMeta>;
2613
+ tags<TNewTags extends TagType[]>(t: TNewTags, options?: {
2614
+ override?: boolean;
2615
+ }): HookOverrideBuilder<TDeps, TOn, TMeta>;
2616
+ meta<TNewMeta extends ITaskMeta>(m: TNewMeta): HookOverrideBuilder<TDeps, TOn, TNewMeta>;
2617
+ run(fn: IHookDefinition<TDeps, TOn, TMeta>["run"]): HookOverrideBuilder<TDeps, TOn, TMeta>;
2618
+ build(): IHook<TDeps, TOn, TMeta>;
2619
+ }
2620
+
2621
+ 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>;
2622
+ 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>;
2623
+ declare function override<TDeps extends DependencyMapType, TOn extends HookOn, TMeta extends ITaskMeta>(base: IHook<TDeps, TOn, TMeta>): HookOverrideBuilder<TDeps, TOn, TMeta>;
2624
+ declare function override<C, In, Out, D extends DependencyMapType>(base: ITaskMiddleware<C, In, Out, D>): TaskMiddlewareFluentBuilder<C, In, Out, D>;
2625
+ declare function override<C, In, Out, D extends DependencyMapType>(base: IResourceMiddleware<C, In, Out, D>): ResourceMiddlewareFluentBuilder<C, In, Out, D>;
2626
+
2064
2627
  declare const debugLevels: {
2065
2628
  normal: DebugConfig;
2066
2629
  verbose: DebugConfig;
@@ -2081,23 +2644,24 @@ interface HttpClientConfig {
2081
2644
  auth?: HttpClientAuth;
2082
2645
  timeoutMs?: number;
2083
2646
  fetchImpl?: typeof fetch;
2084
- serializer: Serializer;
2647
+ serializer: SerializerLike;
2085
2648
  onRequest?: (ctx: {
2086
2649
  url: string;
2087
2650
  headers: Record<string, string>;
2088
2651
  }) => void | Promise<void>;
2089
- contexts?: Array<IAsyncContext<any>>;
2652
+ contexts?: Array<IAsyncContext<unknown>>;
2090
2653
  errorRegistry?: Map<string, IErrorHelper<any>>;
2091
2654
  }
2092
2655
  interface HttpClient {
2093
2656
  task<I = unknown, O = unknown>(id: string, input?: I): Promise<O>;
2094
2657
  event<P = unknown>(id: string, payload?: P): Promise<void>;
2658
+ eventWithResult?<P = unknown>(id: string, payload?: P): Promise<P>;
2095
2659
  }
2096
2660
  declare function createHttpClient(cfg: HttpClientConfig): HttpClient;
2097
2661
 
2098
2662
  /**
2099
2663
  * Factory for creating HTTP clients with automatic injection of:
2100
- * - serializer (EJSON-compatible)
2664
+ * - serializer
2101
2665
  * - error registry (from Store)
2102
2666
  * - async contexts (from Store)
2103
2667
  *
@@ -2114,6 +2678,40 @@ interface HttpClientFactoryConfig {
2114
2678
  }
2115
2679
  type HttpClientFactory = (config: HttpClientFactoryConfig) => HttpClient;
2116
2680
 
2681
+ /**
2682
+ * Implementation of ExecutionJournal.
2683
+ * Created per task execution and passed through the middleware chain.
2684
+ */
2685
+ declare class ExecutionJournalImpl implements ExecutionJournal {
2686
+ private readonly store;
2687
+ /**
2688
+ * Store a value in the journal.
2689
+ * Throws an error if the key already exists unless { override: true } is passed.
2690
+ */
2691
+ set<T>(key: JournalKey<T>, value: T, options?: JournalSetOptions): void;
2692
+ get<T>(key: JournalKey<T>): T | undefined;
2693
+ has<T>(key: JournalKey<T>): boolean;
2694
+ }
2695
+ /**
2696
+ * Creates a typed journal key for use with ExecutionJournal.
2697
+ *
2698
+ * @example
2699
+ * ```typescript
2700
+ * const abortController = journal.createKey<AbortController>("timeout.abortController");
2701
+ * journal.set(abortController, new AbortController());
2702
+ * const ctrl = journal.get(abortController); // AbortController | undefined
2703
+ * ```
2704
+ */
2705
+ declare function createKey<T>(id: string): JournalKey<T>;
2706
+ declare const journal: {
2707
+ createKey: typeof createKey;
2708
+ /**
2709
+ * Creates a new empty ExecutionJournal.
2710
+ * Useful when you need to pass a specific journal instance to `runTask` or nested calls.
2711
+ */
2712
+ create: () => ExecutionJournalImpl;
2713
+ };
2714
+
2117
2715
  declare const globals: {
2118
2716
  events: {
2119
2717
  readonly ready: IEvent<void>;
@@ -2124,15 +2722,15 @@ declare const globals: {
2124
2722
  readonly eventManager: IResource<void, Promise<EventManager>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2125
2723
  readonly taskRunner: IResource<void, Promise<TaskRunner>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2126
2724
  readonly logger: IResource<void, Promise<Logger>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2127
- readonly serializer: IResource<void, Promise<Serializer>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2725
+ readonly serializer: IResource<void, Promise<SerializerLike>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2128
2726
  readonly cache: IResource<{
2129
2727
  defaultOptions?: any;
2130
2728
  }, Promise<{
2131
2729
  map: Map<string, ICacheInstance>;
2132
- cacheFactoryTask: TaskDependencyWithIntercept<any, Promise<ICacheInstance>>;
2730
+ cacheFactoryTask: TaskDependencyWithIntercept<lru_cache.LRUCache.Options<any, any, any>, Promise<ICacheInstance>>;
2133
2731
  defaultOptions: any;
2134
2732
  }>, {
2135
- cacheFactoryTask: ITask<any, Promise<ICacheInstance>, any, any, TagType[], TaskMiddlewareAttachmentType[]>;
2733
+ cacheFactoryTask: ITask<lru_cache.LRUCache.Options<any, any, any>, Promise<ICacheInstance>, any, any, TagType[], TaskMiddlewareAttachmentType[]>;
2136
2734
  }, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2137
2735
  readonly queue: IResource<void, Promise<{
2138
2736
  map: Map<string, Queue>;
@@ -2144,12 +2742,37 @@ declare const globals: {
2144
2742
  description: string;
2145
2743
  }, TagType[], ResourceMiddlewareAttachmentType[]>;
2146
2744
  readonly httpClientFactory: IResource<void, Promise<HttpClientFactory>, {
2147
- serializer: IResource<void, Promise<Serializer>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2745
+ serializer: IResource<void, Promise<SerializerLike>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2148
2746
  store: IResource<void, Promise<Store>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2149
2747
  }, any, {
2150
2748
  title: string;
2151
2749
  description: string;
2152
2750
  }, TagType[], ResourceMiddlewareAttachmentType[]>;
2751
+ readonly rateLimit: IResource<void, Promise<{
2752
+ states: WeakMap<RateLimitMiddlewareConfig, RateLimitState>;
2753
+ }>, {}, any, any, ITag<{
2754
+ metadata?: Record<string, any>;
2755
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2756
+ readonly circuitBreaker: IResource<void, Promise<{
2757
+ statusMap: Map<string, CircuitBreakerStatus>;
2758
+ }>, {}, any, any, ITag<{
2759
+ metadata?: Record<string, any>;
2760
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2761
+ readonly temporal: IResource<void, Promise<{
2762
+ debounceStates: WeakMap<TemporalMiddlewareConfig, DebounceState>;
2763
+ throttleStates: WeakMap<TemporalMiddlewareConfig, ThrottleState>;
2764
+ }>, {}, any, any, ITag<{
2765
+ metadata?: Record<string, any>;
2766
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2767
+ readonly concurrency: IResource<void, Promise<{
2768
+ semaphoresByConfig: WeakMap<ConcurrencyMiddlewareConfig, Semaphore>;
2769
+ semaphoresByKey: Map<string, {
2770
+ semaphore: Semaphore;
2771
+ limit: number;
2772
+ }>;
2773
+ }>, {}, any, any, ITag<{
2774
+ metadata?: Record<string, any>;
2775
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2153
2776
  };
2154
2777
  middleware: {
2155
2778
  requireContext: ITaskMiddleware<{
@@ -2164,14 +2787,87 @@ declare const globals: {
2164
2787
  defaultOptions?: any;
2165
2788
  }, Promise<{
2166
2789
  map: Map<string, ICacheInstance>;
2167
- cacheFactoryTask: TaskDependencyWithIntercept<any, Promise<ICacheInstance>>;
2790
+ cacheFactoryTask: TaskDependencyWithIntercept<lru_cache.LRUCache.Options<any, any, any>, Promise<ICacheInstance>>;
2168
2791
  defaultOptions: any;
2169
2792
  }>, {
2170
- cacheFactoryTask: ITask<any, Promise<ICacheInstance>, any, any, TagType[], TaskMiddlewareAttachmentType[]>;
2793
+ cacheFactoryTask: ITask<lru_cache.LRUCache.Options<any, any, any>, Promise<ICacheInstance>, any, any, TagType[], TaskMiddlewareAttachmentType[]>;
2171
2794
  }, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2795
+ }> & {
2796
+ journalKeys: {
2797
+ readonly hit: JournalKey<boolean>;
2798
+ };
2799
+ };
2800
+ concurrency: ITaskMiddleware<ConcurrencyMiddlewareConfig, void, void, {
2801
+ state: IResource<void, Promise<{
2802
+ semaphoresByConfig: WeakMap<ConcurrencyMiddlewareConfig, Semaphore>;
2803
+ semaphoresByKey: Map<string, {
2804
+ semaphore: Semaphore;
2805
+ limit: number;
2806
+ }>;
2807
+ }>, {}, any, any, ITag<{
2808
+ metadata?: Record<string, any>;
2809
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2810
+ }>;
2811
+ debounce: ITaskMiddleware<TemporalMiddlewareConfig, void, void, {
2812
+ state: IResource<void, Promise<{
2813
+ debounceStates: WeakMap<TemporalMiddlewareConfig, DebounceState>;
2814
+ throttleStates: WeakMap<TemporalMiddlewareConfig, ThrottleState>;
2815
+ }>, {}, any, any, ITag<{
2816
+ metadata?: Record<string, any>;
2817
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2818
+ }>;
2819
+ throttle: ITaskMiddleware<TemporalMiddlewareConfig, void, void, {
2820
+ state: IResource<void, Promise<{
2821
+ debounceStates: WeakMap<TemporalMiddlewareConfig, DebounceState>;
2822
+ throttleStates: WeakMap<TemporalMiddlewareConfig, ThrottleState>;
2823
+ }>, {}, any, any, ITag<{
2824
+ metadata?: Record<string, any>;
2825
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2172
2826
  }>;
2173
- retry: ITaskMiddleware<RetryMiddlewareConfig, void, void, any>;
2174
- timeout: ITaskMiddleware<TimeoutMiddlewareConfig, void, void, any>;
2827
+ fallback: ITaskMiddleware<FallbackMiddlewareConfig, void, void, {
2828
+ taskRunner: IResource<void, Promise<TaskRunner>, {}, any, any, TagType[], ResourceMiddlewareAttachmentType[]>;
2829
+ }> & {
2830
+ journalKeys: {
2831
+ readonly active: JournalKey<boolean>;
2832
+ readonly error: JournalKey<Error>;
2833
+ };
2834
+ };
2835
+ rateLimit: ITaskMiddleware<RateLimitMiddlewareConfig, void, void, {
2836
+ state: IResource<void, Promise<{
2837
+ states: WeakMap<RateLimitMiddlewareConfig, RateLimitState>;
2838
+ }>, {}, any, any, ITag<{
2839
+ metadata?: Record<string, any>;
2840
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2841
+ }> & {
2842
+ journalKeys: {
2843
+ readonly remaining: JournalKey<number>;
2844
+ readonly resetTime: JournalKey<number>;
2845
+ readonly limit: JournalKey<number>;
2846
+ };
2847
+ };
2848
+ retry: ITaskMiddleware<RetryMiddlewareConfig, void, void, any> & {
2849
+ journalKeys: {
2850
+ readonly attempt: JournalKey<number>;
2851
+ readonly lastError: JournalKey<Error>;
2852
+ };
2853
+ };
2854
+ timeout: ITaskMiddleware<TimeoutMiddlewareConfig, void, void, any> & {
2855
+ journalKeys: {
2856
+ readonly abortController: JournalKey<AbortController>;
2857
+ };
2858
+ };
2859
+ circuitBreaker: ITaskMiddleware<CircuitBreakerMiddlewareConfig, void, void, {
2860
+ state: IResource<void, Promise<{
2861
+ statusMap: Map<string, CircuitBreakerStatus>;
2862
+ }>, {}, any, any, ITag<{
2863
+ metadata?: Record<string, any>;
2864
+ }, void, void>[], ResourceMiddlewareAttachmentType[]>;
2865
+ }> & {
2866
+ journalKeys: {
2867
+ readonly state: JournalKey<CircuitBreakerState>;
2868
+ readonly failures: JournalKey<number>;
2869
+ };
2870
+ };
2175
2871
  };
2176
2872
  resource: {
2177
2873
  retry: IResourceMiddleware<RetryMiddlewareConfig, void, void, any>;
@@ -2188,6 +2884,7 @@ declare const globals: {
2188
2884
  debug: ITag<DebugFriendlyConfig, void, void>;
2189
2885
  tunnel: ITag<void, void, TunnelRunner>;
2190
2886
  tunnelPolicy: ITag<TunnelTaskMiddlewarePolicyConfig, void, void>;
2887
+ authValidator: ITag<void, void, void>;
2191
2888
  };
2192
2889
  tunnels: Readonly<{
2193
2890
  http: Readonly<{
@@ -2210,6 +2907,7 @@ declare const r: Readonly<{
2210
2907
  event: typeof eventBuilder;
2211
2908
  hook: typeof hookBuilder;
2212
2909
  tag: typeof tagBuilder;
2910
+ override: typeof override;
2213
2911
  asyncContext: typeof asyncContextBuilder;
2214
2912
  error: typeof errorBuilder;
2215
2913
  middleware: Readonly<{
@@ -2218,4 +2916,4 @@ declare const r: Readonly<{
2218
2916
  }>;
2219
2917
  }>;
2220
2918
 
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 };
2919
+ 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 ResourceForkInfo, type ResourceForkOptions, type ResourceForkRegisterMode, 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, symbolResourceForkedFrom, symbolResourceMiddleware, symbolResourceWithConfig, symbolTag, symbolTagConfigured, symbolTask, symbolTaskMiddleware, symbolTunneledBy, defineTag as tag, defineTask as task, defineTaskMiddleware as taskMiddleware };