awaitly 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1278 -0
  3. package/dist/batch.cjs +2 -0
  4. package/dist/batch.cjs.map +1 -0
  5. package/dist/batch.d.cts +197 -0
  6. package/dist/batch.d.ts +197 -0
  7. package/dist/batch.js +2 -0
  8. package/dist/batch.js.map +1 -0
  9. package/dist/circuit-breaker.cjs +2 -0
  10. package/dist/circuit-breaker.cjs.map +1 -0
  11. package/dist/circuit-breaker.d.cts +208 -0
  12. package/dist/circuit-breaker.d.ts +208 -0
  13. package/dist/circuit-breaker.js +2 -0
  14. package/dist/circuit-breaker.js.map +1 -0
  15. package/dist/conditional.cjs +2 -0
  16. package/dist/conditional.cjs.map +1 -0
  17. package/dist/conditional.d.cts +249 -0
  18. package/dist/conditional.d.ts +249 -0
  19. package/dist/conditional.js +2 -0
  20. package/dist/conditional.js.map +1 -0
  21. package/dist/core-BuTBsR0x.d.cts +2325 -0
  22. package/dist/core-BuTBsR0x.d.ts +2325 -0
  23. package/dist/core.cjs +2 -0
  24. package/dist/core.cjs.map +1 -0
  25. package/dist/core.d.cts +3 -0
  26. package/dist/core.d.ts +3 -0
  27. package/dist/core.js +2 -0
  28. package/dist/core.js.map +1 -0
  29. package/dist/devtools.cjs +11 -0
  30. package/dist/devtools.cjs.map +1 -0
  31. package/dist/devtools.d.cts +176 -0
  32. package/dist/devtools.d.ts +176 -0
  33. package/dist/devtools.js +11 -0
  34. package/dist/devtools.js.map +1 -0
  35. package/dist/duration.cjs +2 -0
  36. package/dist/duration.cjs.map +1 -0
  37. package/dist/duration.d.cts +246 -0
  38. package/dist/duration.d.ts +246 -0
  39. package/dist/duration.js +2 -0
  40. package/dist/duration.js.map +1 -0
  41. package/dist/hitl.cjs +2 -0
  42. package/dist/hitl.cjs.map +1 -0
  43. package/dist/hitl.d.cts +337 -0
  44. package/dist/hitl.d.ts +337 -0
  45. package/dist/hitl.js +2 -0
  46. package/dist/hitl.js.map +1 -0
  47. package/dist/index.cjs +2 -0
  48. package/dist/index.cjs.map +1 -0
  49. package/dist/index.d.cts +4 -0
  50. package/dist/index.d.ts +4 -0
  51. package/dist/index.js +2 -0
  52. package/dist/index.js.map +1 -0
  53. package/dist/match.cjs +2 -0
  54. package/dist/match.cjs.map +1 -0
  55. package/dist/match.d.cts +209 -0
  56. package/dist/match.d.ts +209 -0
  57. package/dist/match.js +2 -0
  58. package/dist/match.js.map +1 -0
  59. package/dist/otel.cjs +2 -0
  60. package/dist/otel.cjs.map +1 -0
  61. package/dist/otel.d.cts +185 -0
  62. package/dist/otel.d.ts +185 -0
  63. package/dist/otel.js +2 -0
  64. package/dist/otel.js.map +1 -0
  65. package/dist/persistence.cjs +2 -0
  66. package/dist/persistence.cjs.map +1 -0
  67. package/dist/persistence.d.cts +572 -0
  68. package/dist/persistence.d.ts +572 -0
  69. package/dist/persistence.js +2 -0
  70. package/dist/persistence.js.map +1 -0
  71. package/dist/policies.cjs +2 -0
  72. package/dist/policies.cjs.map +1 -0
  73. package/dist/policies.d.cts +378 -0
  74. package/dist/policies.d.ts +378 -0
  75. package/dist/policies.js +2 -0
  76. package/dist/policies.js.map +1 -0
  77. package/dist/ratelimit.cjs +2 -0
  78. package/dist/ratelimit.cjs.map +1 -0
  79. package/dist/ratelimit.d.cts +279 -0
  80. package/dist/ratelimit.d.ts +279 -0
  81. package/dist/ratelimit.js +2 -0
  82. package/dist/ratelimit.js.map +1 -0
  83. package/dist/reliability.cjs +2 -0
  84. package/dist/reliability.cjs.map +1 -0
  85. package/dist/reliability.d.cts +5 -0
  86. package/dist/reliability.d.ts +5 -0
  87. package/dist/reliability.js +2 -0
  88. package/dist/reliability.js.map +1 -0
  89. package/dist/resource.cjs +2 -0
  90. package/dist/resource.cjs.map +1 -0
  91. package/dist/resource.d.cts +171 -0
  92. package/dist/resource.d.ts +171 -0
  93. package/dist/resource.js +2 -0
  94. package/dist/resource.js.map +1 -0
  95. package/dist/retry.cjs +2 -0
  96. package/dist/retry.cjs.map +1 -0
  97. package/dist/retry.d.cts +2 -0
  98. package/dist/retry.d.ts +2 -0
  99. package/dist/retry.js +2 -0
  100. package/dist/retry.js.map +1 -0
  101. package/dist/saga.cjs +2 -0
  102. package/dist/saga.cjs.map +1 -0
  103. package/dist/saga.d.cts +231 -0
  104. package/dist/saga.d.ts +231 -0
  105. package/dist/saga.js +2 -0
  106. package/dist/saga.js.map +1 -0
  107. package/dist/schedule.cjs +2 -0
  108. package/dist/schedule.cjs.map +1 -0
  109. package/dist/schedule.d.cts +387 -0
  110. package/dist/schedule.d.ts +387 -0
  111. package/dist/schedule.js +2 -0
  112. package/dist/schedule.js.map +1 -0
  113. package/dist/tagged-error.cjs +2 -0
  114. package/dist/tagged-error.cjs.map +1 -0
  115. package/dist/tagged-error.d.cts +252 -0
  116. package/dist/tagged-error.d.ts +252 -0
  117. package/dist/tagged-error.js +2 -0
  118. package/dist/tagged-error.js.map +1 -0
  119. package/dist/testing.cjs +2 -0
  120. package/dist/testing.cjs.map +1 -0
  121. package/dist/testing.d.cts +228 -0
  122. package/dist/testing.d.ts +228 -0
  123. package/dist/testing.js +2 -0
  124. package/dist/testing.js.map +1 -0
  125. package/dist/visualize.cjs +1573 -0
  126. package/dist/visualize.cjs.map +1 -0
  127. package/dist/visualize.d.cts +1415 -0
  128. package/dist/visualize.d.ts +1415 -0
  129. package/dist/visualize.js +1573 -0
  130. package/dist/visualize.js.map +1 -0
  131. package/dist/webhook.cjs +2 -0
  132. package/dist/webhook.cjs.map +1 -0
  133. package/dist/webhook.d.cts +469 -0
  134. package/dist/webhook.d.ts +469 -0
  135. package/dist/webhook.js +2 -0
  136. package/dist/webhook.js.map +1 -0
  137. package/dist/workflow-entry-C6nH8ByN.d.ts +858 -0
  138. package/dist/workflow-entry-RRTlSg_4.d.cts +858 -0
  139. package/dist/workflow.cjs +2 -0
  140. package/dist/workflow.cjs.map +1 -0
  141. package/dist/workflow.d.cts +2 -0
  142. package/dist/workflow.d.ts +2 -0
  143. package/dist/workflow.js +2 -0
  144. package/dist/workflow.js.map +1 -0
  145. package/docs/advanced.md +1548 -0
  146. package/docs/api.md +513 -0
  147. package/docs/coming-from-neverthrow.md +1013 -0
  148. package/docs/match.md +417 -0
  149. package/docs/pino-logging-example.md +396 -0
  150. package/docs/policies.md +508 -0
  151. package/docs/resource-management.md +509 -0
  152. package/docs/schedule.md +467 -0
  153. package/docs/tagged-error.md +785 -0
  154. package/docs/visualization.md +430 -0
  155. package/docs/visualize-examples.md +330 -0
  156. package/package.json +227 -0
package/docs/api.md ADDED
@@ -0,0 +1,513 @@
1
+ # API Reference
2
+
3
+ ## Workflows
4
+
5
+ ### createWorkflow
6
+
7
+ ```typescript
8
+ createWorkflow(deps) // Auto-inferred error types
9
+ createWorkflow(deps, { strict: true, catchUnexpected }) // Closed error union
10
+ createWorkflow(deps, { onEvent, createContext }) // Event stream + context (context auto-included in events)
11
+ createWorkflow(deps, { cache }) // Step caching
12
+ createWorkflow(deps, { resumeState }) // Resume from saved state
13
+
14
+ // Callback signatures:
15
+ workflow(async (step, deps, ctx) => { ... }) // ctx is always provided (WorkflowContext)
16
+ workflow(args, async (step, deps, args, ctx) => { ... }) // With typed args, ctx is always provided
17
+ ```
18
+
19
+ ### step
20
+
21
+ ```typescript
22
+ step(result) // Unwrap Result or exit early
23
+ step(result, { name, key }) // With tracing/caching options
24
+ step(() => result) // Lazy form (for caching/resume)
25
+ step(() => result, { name, key }) // Lazy with options
26
+ ```
27
+
28
+ ### step.try
29
+
30
+ ```typescript
31
+ step.try(fn, { error }) // Static error type
32
+ step.try(fn, { onError }) // Dynamic error from caught value
33
+ step.try(fn, { error, name, key }) // With tracing options
34
+ ```
35
+
36
+ ### step.fromResult
37
+
38
+ ```typescript
39
+ step.fromResult(fn, { error }) // Map any Result error to static type
40
+ step.fromResult(fn, { onError }) // Map Result error dynamically
41
+ ```
42
+
43
+ ### step.retry
44
+
45
+ ```typescript
46
+ step.retry(fn, { attempts, backoff }) // Basic retry
47
+ step.retry(fn, { attempts, timeout }) // Retry with per-attempt timeout
48
+ ```
49
+
50
+ ### step.withTimeout
51
+
52
+ ```typescript
53
+ step.withTimeout(fn, { ms }) // Simple timeout
54
+ step.withTimeout(fn, { ms, signal }) // With AbortSignal propagation
55
+ ```
56
+
57
+ ### step.parallel / step.race / step.allSettled
58
+
59
+ ```typescript
60
+ step.parallel(name, () => ...) // Parallel group with scope events
61
+ step.parallel({ key: fn }, opts) // Named object form
62
+ step.race(name, () => ...) // Race group with scope events
63
+ step.allSettled(name, () => ...) // allSettled group with scope events
64
+ ```
65
+
66
+ ### Low-level run
67
+
68
+ ```typescript
69
+ run(fn) // One-off workflow
70
+ run(fn, { onError }) // With error callback (receives context as 3rd param)
71
+ run(fn, { onEvent, context }) // With event stream (context auto-included in events)
72
+ run.strict(fn, { catchUnexpected }) // Closed error union
73
+ ```
74
+
75
+ ### Event helpers
76
+
77
+ ```typescript
78
+ isStepComplete(event) // Type guard for step_complete events
79
+ ```
80
+
81
+ ## Results
82
+
83
+ ### Constructors
84
+
85
+ ```typescript
86
+ ok(value) // Create success
87
+ err(error) // Create error
88
+ err(error, { cause }) // Create error with cause
89
+ ```
90
+
91
+ ### Type guards
92
+
93
+ ```typescript
94
+ isOk(result) // result is { ok: true, value }
95
+ isErr(result) // result is { ok: false, error }
96
+ isUnexpectedError(error) // error is UnexpectedError
97
+ ```
98
+
99
+ ## Unwrap
100
+
101
+ ```typescript
102
+ unwrap(result) // Value or throw UnwrapError
103
+ unwrapOr(result, defaultValue) // Value or default
104
+ unwrapOrElse(result, fn) // Value or compute from error
105
+ ```
106
+
107
+ ## Wrap
108
+
109
+ ```typescript
110
+ from(fn) // Sync throwing → Result
111
+ from(fn, onError) // With error mapper
112
+ fromPromise(promise) // Promise → Result
113
+ fromPromise(promise, onError) // With error mapper
114
+ tryAsync(fn) // Async fn → Result
115
+ tryAsync(fn, onError) // With error mapper
116
+ fromNullable(value, onNull) // Nullable → Result
117
+ ```
118
+
119
+ ## Transform
120
+
121
+ ```typescript
122
+ map(result, fn) // Transform value
123
+ mapError(result, fn) // Transform error
124
+ mapTry(result, fn, onError) // Transform value, catch throws
125
+ mapErrorTry(result, fn, onError) // Transform error, catch throws
126
+ andThen(result, fn) // Chain (flatMap)
127
+ match(result, { ok, err }) // Pattern match
128
+ tap(result, fn) // Side effect on success
129
+ tapError(result, fn) // Side effect on error
130
+ ```
131
+
132
+ ## Batch
133
+
134
+ ```typescript
135
+ all(results) // All succeed (sync, short-circuits)
136
+ allAsync(results) // All succeed (async, short-circuits)
137
+ any(results) // First success (sync)
138
+ anyAsync(results) // First success (async)
139
+ allSettled(results) // Collect all; error array if any fail (sync)
140
+ allSettledAsync(results) // Collect all; error array if any fail (async)
141
+ partition(results) // Split into { values, errors }
142
+ ```
143
+
144
+ ## Human-in-the-Loop (HITL)
145
+
146
+ ### Creating approval steps
147
+
148
+ ```typescript
149
+ createApprovalStep<T>(options) // Create approval-gated step function
150
+ // options: { key, checkApproval, pendingReason?, rejectedReason? }
151
+ ```
152
+
153
+ ### Checking approval status
154
+
155
+ ```typescript
156
+ isPendingApproval(error) // error is PendingApproval
157
+ isApprovalRejected(error) // error is ApprovalRejected
158
+ pendingApproval(stepKey, options?) // Create PendingApproval error
159
+ ```
160
+
161
+ ### Managing approval state
162
+
163
+ ```typescript
164
+ createHITLCollector() // Collect step events for resume
165
+ injectApproval(state, { stepKey, value }) // Add approval to resume state
166
+ clearStep(state, stepKey) // Remove step from resume state
167
+ hasPendingApproval(state, stepKey) // Check if step is pending
168
+ getPendingApprovals(state) // Get all pending step keys
169
+ ```
170
+
171
+ ## Types
172
+
173
+ ### Core Result types
174
+
175
+ ```typescript
176
+ Result<T, E, C> // { ok: true, value: T } | { ok: false, error: E, cause?: C }
177
+ AsyncResult<T, E, C> // Promise<Result<T, E, C>>
178
+ UnexpectedError // { type: 'UNEXPECTED_ERROR', cause: unknown }
179
+ ```
180
+
181
+ ### Workflow types
182
+
183
+ ```typescript
184
+ Workflow<E, Deps, C> // Non-strict workflow return type (C is context type)
185
+ WorkflowStrict<E, U, Deps, C> // Strict workflow return type (C is context type)
186
+ WorkflowOptions<E, C> // Options for createWorkflow
187
+ WorkflowOptionsStrict<E, U, C> // Options for strict createWorkflow
188
+ WorkflowContext<C> // Context object passed to callbacks: { workflowId, onEvent?, context? }
189
+ AnyResultFn // Constraint for Result-returning functions
190
+ ```
191
+
192
+ **WorkflowContext**: The third parameter (`ctx`) in workflow callbacks is always provided and contains:
193
+ - `workflowId`: Unique ID for this workflow run (always present)
194
+ - `onEvent`: Event emitter function (present if `onEvent` option provided, for conditional helpers)
195
+ - `context`: Per-run context from `createContext` (present if `createContext` provided)
196
+
197
+ **Note**:
198
+ - You can ignore the `ctx` parameter if you don't need it (TypeScript allows unused parameters).
199
+ - `WorkflowContext` has the same shape as `ConditionalContext`, so you can pass `ctx` directly to `createConditionalHelpers(ctx)` without destructuring.
200
+
201
+ ### Event types
202
+
203
+ ```typescript
204
+ WorkflowEvent<E, C> // Union of all event types (C defaults to unknown)
205
+ StepOptions // { name?: string, key?: string }
206
+ ```
207
+
208
+ **Context in Events**: When you provide context via `createContext` or the `context` option, it's automatically included in every event's `context` field. This makes it easy to correlate events with request data, user IDs, or other contextual information.
209
+
210
+ ```typescript
211
+ // Context is automatically added to all events
212
+ const workflow = createWorkflow({ fetchUser }, {
213
+ createContext: () => ({ requestId: 'req-123', userId: 'user-456' }),
214
+ onEvent: (event) => {
215
+ // event.context is automatically available
216
+ console.log(event.context?.requestId); // 'req-123'
217
+ console.log(event.context?.userId); // 'user-456'
218
+ }
219
+ });
220
+ ```
221
+
222
+ ### Cache & Resume types
223
+
224
+ ```typescript
225
+ StepCache // Cache interface (get/set/has/delete/clear)
226
+ ResumeState // { steps: Map<string, ResumeStateEntry> }
227
+ ResumeStateEntry // { result: Result, meta?: StepFailureMeta }
228
+ ```
229
+
230
+ ### HITL types
231
+
232
+ ```typescript
233
+ PendingApproval // { type: 'PENDING_APPROVAL', stepKey, reason? }
234
+ ApprovalRejected // { type: 'APPROVAL_REJECTED', stepKey, reason? }
235
+ ```
236
+
237
+ ### Type extraction utilities
238
+
239
+ ```typescript
240
+ ErrorOf<Fn> // Extract error type from function
241
+ CauseOf<Fn> // Extract cause type from function
242
+ Errors<[Fn1, Fn2, ...]> // Union of error types from functions
243
+ ErrorsOfDeps<Deps> // Extract errors from deps object
244
+ CausesOfDeps<Deps> // Extract causes from deps object
245
+ ExtractValue<Result> // Extract value type from Result
246
+ ExtractError<Result> // Extract error type from Result
247
+ ExtractCause<Result> // Extract cause type from Result
248
+ ```
249
+
250
+ ### Error types
251
+
252
+ ```typescript
253
+ UnwrapError<E, C> // Error thrown by unwrap()
254
+ ```
255
+
256
+ ## Circuit Breaker
257
+
258
+ ```typescript
259
+ createCircuitBreaker(name, config) // Create circuit breaker instance
260
+ isCircuitOpenError(error) // Check if error is circuit open
261
+ circuitBreakerPresets.critical // Preset configurations
262
+ circuitBreakerPresets.lenient
263
+ ```
264
+
265
+ ### Types
266
+
267
+ ```typescript
268
+ CircuitState // 'CLOSED' | 'OPEN' | 'HALF_OPEN'
269
+ CircuitBreakerConfig // Configuration options
270
+ CircuitBreakerStats // Runtime statistics
271
+ CircuitBreaker // Circuit breaker interface
272
+ CircuitOpenError // Error when circuit is open
273
+ ```
274
+
275
+ ## Saga / Compensation
276
+
277
+ ```typescript
278
+ createSagaWorkflow(deps, options) // Create saga with auto-inferred errors
279
+ runSaga(fn, options) // Low-level saga execution
280
+ isSagaCompensationError(error) // Check for compensation failure
281
+ ```
282
+
283
+ ### Types
284
+
285
+ ```typescript
286
+ SagaContext<E> // Context with step() and tryStep()
287
+ SagaStepOptions<T> // Step options with compensate
288
+ SagaCompensationError // Error with compensation details
289
+ SagaEvent // Saga lifecycle events
290
+ SagaResult<T, E> // Result type for sagas
291
+ CompensationAction<T> // Compensation function type
292
+ ```
293
+
294
+ ## Rate Limiting
295
+
296
+ ```typescript
297
+ createRateLimiter(name, config) // Token bucket rate limiter
298
+ createConcurrencyLimiter(name, cfg) // Concurrent execution limiter
299
+ createCombinedLimiter(name, config) // Rate + concurrency combined
300
+ rateLimiterPresets.api // Preset configurations
301
+ isRateLimitExceededError(error) // Check if rate limited
302
+ isQueueFullError(error) // Check if queue full
303
+ ```
304
+
305
+ ### Types
306
+
307
+ ```typescript
308
+ RateLimiterConfig // Rate limiter configuration
309
+ ConcurrencyLimiterConfig // Concurrency limiter config
310
+ RateLimiter // Rate limiter interface
311
+ ConcurrencyLimiter // Concurrency limiter interface
312
+ RateLimitExceededError // Error when rate exceeded
313
+ QueueFullError // Error when queue full
314
+ ```
315
+
316
+ ## Versioning
317
+
318
+ ```typescript
319
+ migrateState(state, target, migrations) // Apply migrations
320
+ createVersionedStateLoader(config) // Create loader with migrations
321
+ createVersionedState(state, version) // Wrap state with version
322
+ parseVersionedState(json) // Parse from JSON
323
+ stringifyVersionedState(state) // Serialize to JSON
324
+ createKeyRenameMigration(renames) // Migration helper
325
+ createKeyRemoveMigration(keys) // Migration helper
326
+ createValueTransformMigration(transforms) // Migration helper
327
+ composeMigrations(migrations) // Combine migrations
328
+ ```
329
+
330
+ ### Types
331
+
332
+ ```typescript
333
+ Version // Version number type
334
+ VersionedState // State with version
335
+ MigrationFn // Migration function type
336
+ Migrations // Migration map type
337
+ MigrationError // Error during migration
338
+ VersionIncompatibleError // Version mismatch error
339
+ ```
340
+
341
+ ## Conditional Execution
342
+
343
+ ```typescript
344
+ when(condition, operation, opts, ctx) // Run if true
345
+ unless(condition, operation, opts, ctx) // Run if false
346
+ whenOr(cond, op, default, opts, ctx) // Run if true, else default
347
+ unlessOr(cond, op, default, opts, ctx) // Run if false, else default
348
+ createConditionalHelpers(ctx) // Factory for bound helpers
349
+ ```
350
+
351
+ ### Types
352
+
353
+ ```typescript
354
+ ConditionalOptions // { name?, key?, reason? }
355
+ ConditionalContext<C> // { workflowId, onEvent?, context?: C }
356
+ ```
357
+
358
+ **Context in Conditional Events**: When you provide `context` in `ConditionalContext`, it's automatically included in `step_skipped` events, maintaining correlation with other workflow events.
359
+
360
+ ## Webhook / Event Triggers
361
+
362
+ ```typescript
363
+ createWebhookHandler(workflow, fn, config) // Create HTTP handler
364
+ createSimpleHandler(config) // Simple endpoint handler
365
+ createEventHandler(workflow, fn, config) // Queue event handler
366
+ createResultMapper(mappings, options) // Map errors to HTTP codes
367
+ createExpressHandler(handler) // Express middleware
368
+ toWebhookRequest(req) // Convert Express request
369
+ sendWebhookResponse(res, response) // Send Express response
370
+ validationError(message, field, details) // Create validation error
371
+ requireFields(fields) // Field validator
372
+ composeValidators(...validators) // Combine validators
373
+ ```
374
+
375
+ ### Types
376
+
377
+ ```typescript
378
+ WebhookRequest<Body> // Generic HTTP request
379
+ WebhookResponse<T> // Generic HTTP response
380
+ WebhookHandler<TBody> // Handler function type
381
+ ValidationError // Validation error type
382
+ EventMessage<T> // Queue message type
383
+ EventProcessingResult // Processing result type
384
+ ```
385
+
386
+ ## Policy Middleware
387
+
388
+ ```typescript
389
+ mergePolicies(...policies) // Combine policies
390
+ createPolicyApplier(...policies) // Create policy applier
391
+ withPolicy(policy, options) // Apply single policy
392
+ withPolicies(policies, name) // Apply multiple policies
393
+ createPolicyRegistry() // Create policy registry
394
+ stepOptions() // Fluent builder
395
+ retryPolicies.standard // Retry presets
396
+ timeoutPolicies.api // Timeout presets
397
+ servicePolicies.httpApi // Combined presets
398
+ ```
399
+
400
+ ### Types
401
+
402
+ ```typescript
403
+ Policy // Policy type
404
+ PolicyFactory // Factory type
405
+ NamedPolicy // Named policy type
406
+ PolicyRegistry // Registry interface
407
+ StepOptionsBuilder // Fluent builder type
408
+ ```
409
+
410
+ ## Persistence
411
+
412
+ ```typescript
413
+ createMemoryCache(options) // In-memory cache
414
+ createFileCache(options) // File-based cache
415
+ createKVCache(options) // Key-value store cache
416
+ createStatePersistence(store, prefix) // State persistence
417
+ createHydratingCache(memory, persist, id) // Hydrating cache
418
+ serializeState(state) // Serialize resume state
419
+ deserializeState(data) // Deserialize resume state
420
+ stringifyState(state, meta) // JSON stringify
421
+ parseState(json) // JSON parse
422
+ ```
423
+
424
+ ### Types
425
+
426
+ ```typescript
427
+ SerializedState // JSON-safe state
428
+ MemoryCacheOptions // Memory cache config
429
+ FileCacheOptions // File cache config
430
+ KeyValueStore // KV store interface
431
+ StatePersistence // Persistence interface
432
+ ```
433
+
434
+ ## Devtools
435
+
436
+ ```typescript
437
+ createDevtools(options) // Create devtools instance
438
+ renderDiff(diff) // Render run diff
439
+ quickVisualize(events) // Quick visualization
440
+ createConsoleLogger(options) // Console event logger
441
+ ```
442
+
443
+ ### Types
444
+
445
+ ```typescript
446
+ WorkflowRun // Captured run data
447
+ RunDiff // Diff between runs
448
+ StepDiff // Step-level diff
449
+ TimelineEntry // Timeline data
450
+ Devtools // Devtools interface
451
+ ```
452
+
453
+ ## HITL Orchestration
454
+
455
+ ```typescript
456
+ createHITLOrchestrator(options) // Create orchestrator
457
+ createMemoryApprovalStore() // In-memory approval store
458
+ createMemoryWorkflowStateStore() // In-memory state store
459
+ createApprovalWebhookHandler(store) // Webhook for approvals
460
+ createApprovalChecker(store, key) // Approval status checker
461
+ ```
462
+
463
+ ### Types
464
+
465
+ ```typescript
466
+ HITLOrchestrator // Orchestrator interface
467
+ ApprovalStore // Approval storage interface
468
+ WorkflowStateStore // State storage interface
469
+ HITLExecutionResult // Execution result type
470
+ ApprovalStatus // Approval status type
471
+ ```
472
+
473
+ ## Testing
474
+
475
+ ```typescript
476
+ createWorkflowHarness(deps, options) // Create test harness
477
+ createMockFn<T, E>() // Create mock function
478
+ createTestClock(startTime) // Deterministic clock
479
+ createSnapshot(invocations, result) // Create snapshot
480
+ compareSnapshots(snapshot1, snapshot2) // Compare snapshots
481
+ okOutcome(value) // Helper for ok outcome
482
+ errOutcome(error) // Helper for err outcome
483
+ throwOutcome(error) // Helper for throw outcome
484
+ ```
485
+
486
+ ### Types
487
+
488
+ ```typescript
489
+ WorkflowHarness<E, Deps> // Test harness interface
490
+ MockStep<E> // Mock step function
491
+ MockFunction<T, E> // Mock function interface
492
+ ScriptedOutcome<T, E> // Scripted step outcome
493
+ StepInvocation // Invocation record
494
+ AssertionResult // Assertion result
495
+ WorkflowSnapshot // Snapshot for comparison
496
+ ```
497
+
498
+ ## OpenTelemetry (Autotel)
499
+
500
+ ```typescript
501
+ createAutotelAdapter(config) // Create metrics adapter
502
+ createAutotelEventHandler(options) // Event handler for debug
503
+ withAutotelTracing(trace, options) // Wrap with tracing
504
+ ```
505
+
506
+ ### Types
507
+
508
+ ```typescript
509
+ AutotelAdapterConfig // Adapter configuration
510
+ AutotelMetrics // Collected metrics
511
+ AutotelAdapter // Adapter interface
512
+ AutotelTraceFn // Trace function type
513
+ ```