@jagreehal/workflow 1.1.0 → 1.2.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.
package/dist/core.d.cts CHANGED
@@ -117,9 +117,11 @@ declare const err: <E, C = unknown>(error: E, options?: {
117
117
  * ```typescript
118
118
  * const r = someOperation();
119
119
  * if (isOk(r)) {
120
- * console.log(r.value); // Type is T
120
+ * // Use r.value (Type is T)
121
+ * processValue(r.value);
121
122
  * } else {
122
- * console.error(r.error); // Type is E
123
+ * // Handle r.error (Type is E)
124
+ * handleError(r.error);
123
125
  * }
124
126
  * ```
125
127
  */
@@ -324,6 +326,61 @@ interface RunStep<E = unknown> {
324
326
  name?: string;
325
327
  key?: string;
326
328
  }) => Promise<T>;
329
+ /**
330
+ * Execute a parallel operation (allAsync) with scope events for visualization.
331
+ *
332
+ * This wraps the operation with scope_start and scope_end events, enabling
333
+ * visualization of parallel execution branches.
334
+ *
335
+ * @param name - Name for this parallel block (used in visualization)
336
+ * @param operation - A function that returns a Result from allAsync or allSettledAsync
337
+ * @returns The success value (unwrapped array)
338
+ *
339
+ * @example
340
+ * ```typescript
341
+ * const [user, posts] = await step.parallel('Fetch all data', () =>
342
+ * allAsync([fetchUser(id), fetchPosts(id)])
343
+ * );
344
+ * ```
345
+ */
346
+ parallel: <T, StepE extends E, StepC = unknown>(name: string, operation: () => Result<T[], StepE, StepC> | AsyncResult<T[], StepE, StepC>) => Promise<T[]>;
347
+ /**
348
+ * Execute a race operation (anyAsync) with scope events for visualization.
349
+ *
350
+ * This wraps the operation with scope_start and scope_end events, enabling
351
+ * visualization of racing execution branches.
352
+ *
353
+ * @param name - Name for this race block (used in visualization)
354
+ * @param operation - A function that returns a Result from anyAsync
355
+ * @returns The success value (first to succeed)
356
+ *
357
+ * @example
358
+ * ```typescript
359
+ * const data = await step.race('Fastest API', () =>
360
+ * anyAsync([fetchFromPrimary(id), fetchFromFallback(id)])
361
+ * );
362
+ * ```
363
+ */
364
+ race: <T, StepE extends E, StepC = unknown>(name: string, operation: () => Result<T, StepE, StepC> | AsyncResult<T, StepE, StepC>) => Promise<T>;
365
+ /**
366
+ * Execute an allSettled operation with scope events for visualization.
367
+ *
368
+ * This wraps the operation with scope_start and scope_end events, enabling
369
+ * visualization of allSettled execution branches. Unlike step.parallel,
370
+ * allSettled collects all results even if some fail.
371
+ *
372
+ * @param name - Name for this allSettled block (used in visualization)
373
+ * @param operation - A function that returns a Result from allSettledAsync
374
+ * @returns The success value (unwrapped array)
375
+ *
376
+ * @example
377
+ * ```typescript
378
+ * const [user, posts] = await step.allSettled('Fetch all data', () =>
379
+ * allSettledAsync([fetchUser(id), fetchPosts(id)])
380
+ * );
381
+ * ```
382
+ */
383
+ allSettled: <T, StepE extends E, StepC = unknown>(name: string, operation: () => Result<T[], StepE, StepC> | AsyncResult<T[], StepE, StepC>) => Promise<T[]>;
327
384
  }
328
385
  /**
329
386
  * Unified event stream for workflow execution.
@@ -333,6 +390,10 @@ interface RunStep<E = unknown> {
333
390
  * preserves its original types, but the event type cannot statically represent them.
334
391
  * Use runtime checks or the meta field to interpret cause values.
335
392
  */
393
+ /**
394
+ * Scope types for parallel and race operations.
395
+ */
396
+ type ScopeType = "parallel" | "race" | "allSettled";
336
397
  type WorkflowEvent<E> = {
337
398
  type: "workflow_start";
338
399
  workflowId: string;
@@ -351,12 +412,14 @@ type WorkflowEvent<E> = {
351
412
  } | {
352
413
  type: "step_start";
353
414
  workflowId: string;
415
+ stepId: string;
354
416
  stepKey?: string;
355
417
  name?: string;
356
418
  ts: number;
357
419
  } | {
358
420
  type: "step_success";
359
421
  workflowId: string;
422
+ stepId: string;
360
423
  stepKey?: string;
361
424
  name?: string;
362
425
  ts: number;
@@ -364,6 +427,7 @@ type WorkflowEvent<E> = {
364
427
  } | {
365
428
  type: "step_error";
366
429
  workflowId: string;
430
+ stepId: string;
367
431
  stepKey?: string;
368
432
  name?: string;
369
433
  ts: number;
@@ -372,6 +436,7 @@ type WorkflowEvent<E> = {
372
436
  } | {
373
437
  type: "step_aborted";
374
438
  workflowId: string;
439
+ stepId: string;
375
440
  stepKey?: string;
376
441
  name?: string;
377
442
  ts: number;
@@ -397,6 +462,28 @@ type WorkflowEvent<E> = {
397
462
  stepKey: string;
398
463
  name?: string;
399
464
  ts: number;
465
+ } | {
466
+ type: "step_skipped";
467
+ workflowId: string;
468
+ stepKey?: string;
469
+ name?: string;
470
+ reason?: string;
471
+ decisionId?: string;
472
+ ts: number;
473
+ } | {
474
+ type: "scope_start";
475
+ workflowId: string;
476
+ scopeId: string;
477
+ scopeType: ScopeType;
478
+ name?: string;
479
+ ts: number;
480
+ } | {
481
+ type: "scope_end";
482
+ workflowId: string;
483
+ scopeId: string;
484
+ ts: number;
485
+ durationMs: number;
486
+ winnerId?: string;
400
487
  };
401
488
  type RunOptionsWithCatch<E, C = void> = {
402
489
  /**
@@ -1041,9 +1128,9 @@ declare function mapError<T, E, F, C>(r: Result<T, E, C>, fn: (error: E) => F):
1041
1128
  * });
1042
1129
  *
1043
1130
  * // Handle with cause
1044
- * const log = match(result, {
1045
- * ok: (value) => console.log('Success:', value),
1046
- * err: (error, cause) => console.error('Error:', error, cause),
1131
+ * const response = match(result, {
1132
+ * ok: (value) => ({ status: 'success', data: value }),
1133
+ * err: (error, cause) => ({ status: 'error', error, cause }),
1047
1134
  * });
1048
1135
  * ```
1049
1136
  */
@@ -1673,4 +1760,4 @@ type AllAsyncCauses<T extends readonly MaybeAsyncResult<unknown, unknown, unknow
1673
1760
  */
1674
1761
  declare function allSettledAsync<const T extends readonly MaybeAsyncResult<unknown, unknown, unknown>[]>(results: T): Promise<Result<AllAsyncValues<T>, SettledError<AllAsyncErrors<T> | PromiseRejectedError, AllAsyncCauses<T> | PromiseRejectionCause>[]>>;
1675
1762
 
1676
- export { type AsyncResult, type CauseOf, EARLY_EXIT_SYMBOL, type EarlyExit, type EmptyInputError, type ErrorOf, type Errors, type ExtractCause, type ExtractError, type ExtractValue, type MaybeAsyncResult, type PromiseRejectedError, type PromiseRejectionCause, type Result, type RunOptions, type RunOptionsWithCatch, type RunOptionsWithoutCatch, type RunStep, type SettledError, type StepFailureMeta, type StepOptions, type UnexpectedCause, type UnexpectedError, type UnexpectedStepFailureCause, UnwrapError, type WorkflowEvent, all, allAsync, allSettled, allSettledAsync, andThen, any, anyAsync, createEarlyExit, err, from, fromNullable, fromPromise, isEarlyExit, isErr, isOk, isUnexpectedError, map, mapError, mapErrorTry, mapTry, match, ok, partition, run, tap, tapError, tryAsync, unwrap, unwrapOr, unwrapOrElse };
1763
+ export { type AsyncResult, type CauseOf, EARLY_EXIT_SYMBOL, type EarlyExit, type EmptyInputError, type ErrorOf, type Errors, type ExtractCause, type ExtractError, type ExtractValue, type MaybeAsyncResult, type PromiseRejectedError, type PromiseRejectionCause, type Result, type RunOptions, type RunOptionsWithCatch, type RunOptionsWithoutCatch, type RunStep, type ScopeType, type SettledError, type StepFailureMeta, type StepOptions, type UnexpectedCause, type UnexpectedError, type UnexpectedStepFailureCause, UnwrapError, type WorkflowEvent, all, allAsync, allSettled, allSettledAsync, andThen, any, anyAsync, createEarlyExit, err, from, fromNullable, fromPromise, isEarlyExit, isErr, isOk, isUnexpectedError, map, mapError, mapErrorTry, mapTry, match, ok, partition, run, tap, tapError, tryAsync, unwrap, unwrapOr, unwrapOrElse };
package/dist/core.d.ts CHANGED
@@ -117,9 +117,11 @@ declare const err: <E, C = unknown>(error: E, options?: {
117
117
  * ```typescript
118
118
  * const r = someOperation();
119
119
  * if (isOk(r)) {
120
- * console.log(r.value); // Type is T
120
+ * // Use r.value (Type is T)
121
+ * processValue(r.value);
121
122
  * } else {
122
- * console.error(r.error); // Type is E
123
+ * // Handle r.error (Type is E)
124
+ * handleError(r.error);
123
125
  * }
124
126
  * ```
125
127
  */
@@ -324,6 +326,61 @@ interface RunStep<E = unknown> {
324
326
  name?: string;
325
327
  key?: string;
326
328
  }) => Promise<T>;
329
+ /**
330
+ * Execute a parallel operation (allAsync) with scope events for visualization.
331
+ *
332
+ * This wraps the operation with scope_start and scope_end events, enabling
333
+ * visualization of parallel execution branches.
334
+ *
335
+ * @param name - Name for this parallel block (used in visualization)
336
+ * @param operation - A function that returns a Result from allAsync or allSettledAsync
337
+ * @returns The success value (unwrapped array)
338
+ *
339
+ * @example
340
+ * ```typescript
341
+ * const [user, posts] = await step.parallel('Fetch all data', () =>
342
+ * allAsync([fetchUser(id), fetchPosts(id)])
343
+ * );
344
+ * ```
345
+ */
346
+ parallel: <T, StepE extends E, StepC = unknown>(name: string, operation: () => Result<T[], StepE, StepC> | AsyncResult<T[], StepE, StepC>) => Promise<T[]>;
347
+ /**
348
+ * Execute a race operation (anyAsync) with scope events for visualization.
349
+ *
350
+ * This wraps the operation with scope_start and scope_end events, enabling
351
+ * visualization of racing execution branches.
352
+ *
353
+ * @param name - Name for this race block (used in visualization)
354
+ * @param operation - A function that returns a Result from anyAsync
355
+ * @returns The success value (first to succeed)
356
+ *
357
+ * @example
358
+ * ```typescript
359
+ * const data = await step.race('Fastest API', () =>
360
+ * anyAsync([fetchFromPrimary(id), fetchFromFallback(id)])
361
+ * );
362
+ * ```
363
+ */
364
+ race: <T, StepE extends E, StepC = unknown>(name: string, operation: () => Result<T, StepE, StepC> | AsyncResult<T, StepE, StepC>) => Promise<T>;
365
+ /**
366
+ * Execute an allSettled operation with scope events for visualization.
367
+ *
368
+ * This wraps the operation with scope_start and scope_end events, enabling
369
+ * visualization of allSettled execution branches. Unlike step.parallel,
370
+ * allSettled collects all results even if some fail.
371
+ *
372
+ * @param name - Name for this allSettled block (used in visualization)
373
+ * @param operation - A function that returns a Result from allSettledAsync
374
+ * @returns The success value (unwrapped array)
375
+ *
376
+ * @example
377
+ * ```typescript
378
+ * const [user, posts] = await step.allSettled('Fetch all data', () =>
379
+ * allSettledAsync([fetchUser(id), fetchPosts(id)])
380
+ * );
381
+ * ```
382
+ */
383
+ allSettled: <T, StepE extends E, StepC = unknown>(name: string, operation: () => Result<T[], StepE, StepC> | AsyncResult<T[], StepE, StepC>) => Promise<T[]>;
327
384
  }
328
385
  /**
329
386
  * Unified event stream for workflow execution.
@@ -333,6 +390,10 @@ interface RunStep<E = unknown> {
333
390
  * preserves its original types, but the event type cannot statically represent them.
334
391
  * Use runtime checks or the meta field to interpret cause values.
335
392
  */
393
+ /**
394
+ * Scope types for parallel and race operations.
395
+ */
396
+ type ScopeType = "parallel" | "race" | "allSettled";
336
397
  type WorkflowEvent<E> = {
337
398
  type: "workflow_start";
338
399
  workflowId: string;
@@ -351,12 +412,14 @@ type WorkflowEvent<E> = {
351
412
  } | {
352
413
  type: "step_start";
353
414
  workflowId: string;
415
+ stepId: string;
354
416
  stepKey?: string;
355
417
  name?: string;
356
418
  ts: number;
357
419
  } | {
358
420
  type: "step_success";
359
421
  workflowId: string;
422
+ stepId: string;
360
423
  stepKey?: string;
361
424
  name?: string;
362
425
  ts: number;
@@ -364,6 +427,7 @@ type WorkflowEvent<E> = {
364
427
  } | {
365
428
  type: "step_error";
366
429
  workflowId: string;
430
+ stepId: string;
367
431
  stepKey?: string;
368
432
  name?: string;
369
433
  ts: number;
@@ -372,6 +436,7 @@ type WorkflowEvent<E> = {
372
436
  } | {
373
437
  type: "step_aborted";
374
438
  workflowId: string;
439
+ stepId: string;
375
440
  stepKey?: string;
376
441
  name?: string;
377
442
  ts: number;
@@ -397,6 +462,28 @@ type WorkflowEvent<E> = {
397
462
  stepKey: string;
398
463
  name?: string;
399
464
  ts: number;
465
+ } | {
466
+ type: "step_skipped";
467
+ workflowId: string;
468
+ stepKey?: string;
469
+ name?: string;
470
+ reason?: string;
471
+ decisionId?: string;
472
+ ts: number;
473
+ } | {
474
+ type: "scope_start";
475
+ workflowId: string;
476
+ scopeId: string;
477
+ scopeType: ScopeType;
478
+ name?: string;
479
+ ts: number;
480
+ } | {
481
+ type: "scope_end";
482
+ workflowId: string;
483
+ scopeId: string;
484
+ ts: number;
485
+ durationMs: number;
486
+ winnerId?: string;
400
487
  };
401
488
  type RunOptionsWithCatch<E, C = void> = {
402
489
  /**
@@ -1041,9 +1128,9 @@ declare function mapError<T, E, F, C>(r: Result<T, E, C>, fn: (error: E) => F):
1041
1128
  * });
1042
1129
  *
1043
1130
  * // Handle with cause
1044
- * const log = match(result, {
1045
- * ok: (value) => console.log('Success:', value),
1046
- * err: (error, cause) => console.error('Error:', error, cause),
1131
+ * const response = match(result, {
1132
+ * ok: (value) => ({ status: 'success', data: value }),
1133
+ * err: (error, cause) => ({ status: 'error', error, cause }),
1047
1134
  * });
1048
1135
  * ```
1049
1136
  */
@@ -1673,4 +1760,4 @@ type AllAsyncCauses<T extends readonly MaybeAsyncResult<unknown, unknown, unknow
1673
1760
  */
1674
1761
  declare function allSettledAsync<const T extends readonly MaybeAsyncResult<unknown, unknown, unknown>[]>(results: T): Promise<Result<AllAsyncValues<T>, SettledError<AllAsyncErrors<T> | PromiseRejectedError, AllAsyncCauses<T> | PromiseRejectionCause>[]>>;
1675
1762
 
1676
- export { type AsyncResult, type CauseOf, EARLY_EXIT_SYMBOL, type EarlyExit, type EmptyInputError, type ErrorOf, type Errors, type ExtractCause, type ExtractError, type ExtractValue, type MaybeAsyncResult, type PromiseRejectedError, type PromiseRejectionCause, type Result, type RunOptions, type RunOptionsWithCatch, type RunOptionsWithoutCatch, type RunStep, type SettledError, type StepFailureMeta, type StepOptions, type UnexpectedCause, type UnexpectedError, type UnexpectedStepFailureCause, UnwrapError, type WorkflowEvent, all, allAsync, allSettled, allSettledAsync, andThen, any, anyAsync, createEarlyExit, err, from, fromNullable, fromPromise, isEarlyExit, isErr, isOk, isUnexpectedError, map, mapError, mapErrorTry, mapTry, match, ok, partition, run, tap, tapError, tryAsync, unwrap, unwrapOr, unwrapOrElse };
1763
+ export { type AsyncResult, type CauseOf, EARLY_EXIT_SYMBOL, type EarlyExit, type EmptyInputError, type ErrorOf, type Errors, type ExtractCause, type ExtractError, type ExtractValue, type MaybeAsyncResult, type PromiseRejectedError, type PromiseRejectionCause, type Result, type RunOptions, type RunOptionsWithCatch, type RunOptionsWithoutCatch, type RunStep, type ScopeType, type SettledError, type StepFailureMeta, type StepOptions, type UnexpectedCause, type UnexpectedError, type UnexpectedStepFailureCause, UnwrapError, type WorkflowEvent, all, allAsync, allSettled, allSettledAsync, andThen, any, anyAsync, createEarlyExit, err, from, fromNullable, fromPromise, isEarlyExit, isErr, isOk, isUnexpectedError, map, mapError, mapErrorTry, mapTry, match, ok, partition, run, tap, tapError, tryAsync, unwrap, unwrapOr, unwrapOrElse };
package/dist/core.js CHANGED
@@ -1,2 +1,2 @@
1
- var k=e=>({ok:!0,value:e}),i=(e,n)=>({ok:!1,error:e,...n?.cause!==void 0?{cause:n.cause}:{}}),W=e=>e.ok,Y=e=>!e.ok,D=e=>typeof e=="object"&&e!==null&&e.type==="UNEXPECTED_ERROR",b=Symbol("early-exit");function N(e,n){return{[b]:!0,error:e,meta:n}}function V(e){return typeof e=="object"&&e!==null&&e[b]===!0}var I=Symbol("mapper-exception");function j(e){return{[I]:!0,thrown:e}}function L(e){return typeof e=="object"&&e!==null&&e[I]===!0}function X(e){return typeof e=="string"?{name:e}:e??{}}async function _(e,n){let{onError:r,onEvent:o,catchUnexpected:l,workflowId:R,context:d}=n&&typeof n=="object"?n:{},u=R??crypto.randomUUID(),O=!r&&!l,c=t=>{o?.(t,d)},P=N,U=t=>V(t),h=(t,f)=>O?f?.origin==="result"?{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"result",error:t,...f.resultCause!==void 0?{cause:f.resultCause}:{}}}:f?.origin==="throw"?{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"throw",error:t,thrown:f.thrown}}:{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"result",error:t}}:t,M=t=>t.origin==="result"?t.resultCause:t.thrown,K=t=>({type:"UNEXPECTED_ERROR",cause:t.meta.origin==="result"?{type:"STEP_FAILURE",origin:"result",error:t.error,...t.meta.resultCause!==void 0?{cause:t.meta.resultCause}:{}}:{type:"STEP_FAILURE",origin:"throw",error:t.error,thrown:t.meta.thrown}});try{let t=(m,T)=>(async()=>{let{name:a,key:s}=X(T),v=o?performance.now():0;o&&c({type:"step_start",workflowId:u,stepKey:s,name:a,ts:Date.now()});let p;try{p=await(typeof m=="function"?m():m)}catch(y){let C=performance.now()-v;if(U(y))throw c({type:"step_aborted",workflowId:u,stepKey:s,name:a,ts:Date.now(),durationMs:C}),y;if(l){let A;try{A=l(y)}catch(F){throw j(F)}throw c({type:"step_error",workflowId:u,stepKey:s,name:a,ts:Date.now(),durationMs:C,error:A}),s&&c({type:"step_complete",workflowId:u,stepKey:s,name:a,ts:Date.now(),durationMs:C,result:i(A,{cause:y}),meta:{origin:"throw",thrown:y}}),r?.(A,a),P(A,{origin:"throw",thrown:y})}else{let A={type:"UNEXPECTED_ERROR",cause:{type:"UNCAUGHT_EXCEPTION",thrown:y}};throw c({type:"step_error",workflowId:u,stepKey:s,name:a,ts:Date.now(),durationMs:C,error:A}),s&&c({type:"step_complete",workflowId:u,stepKey:s,name:a,ts:Date.now(),durationMs:C,result:i(A,{cause:y}),meta:{origin:"throw",thrown:y}}),y}}let E=performance.now()-v;if(p.ok)return c({type:"step_success",workflowId:u,stepKey:s,name:a,ts:Date.now(),durationMs:E}),s&&c({type:"step_complete",workflowId:u,stepKey:s,name:a,ts:Date.now(),durationMs:E,result:p}),p.value;let w=h(p.error,{origin:"result",resultCause:p.cause});throw c({type:"step_error",workflowId:u,stepKey:s,name:a,ts:Date.now(),durationMs:E,error:w}),s&&c({type:"step_complete",workflowId:u,stepKey:s,name:a,ts:Date.now(),durationMs:E,result:p,meta:{origin:"result",resultCause:p.cause}}),r?.(p.error,a),P(p.error,{origin:"result",resultCause:p.cause})})();t.try=(m,T)=>{let a=T.name,s=T.key,g="error"in T?()=>T.error:T.onError,v=o;return(async()=>{let p=v?performance.now():0;o&&c({type:"step_start",workflowId:u,stepKey:s,name:a,ts:Date.now()});try{let E=await m(),w=performance.now()-p;return c({type:"step_success",workflowId:u,stepKey:s,name:a,ts:Date.now(),durationMs:w}),s&&c({type:"step_complete",workflowId:u,stepKey:s,name:a,ts:Date.now(),durationMs:w,result:k(E)}),E}catch(E){let w=g(E),y=performance.now()-p,C=h(w,{origin:"throw",thrown:E});throw c({type:"step_error",workflowId:u,stepKey:s,name:a,ts:Date.now(),durationMs:y,error:C}),s&&c({type:"step_complete",workflowId:u,stepKey:s,name:a,ts:Date.now(),durationMs:y,result:i(w,{cause:E}),meta:{origin:"throw",thrown:E}}),r?.(w,a),P(w,{origin:"throw",thrown:E})}})()},t.fromResult=(m,T)=>{let a=T.name,s=T.key,g="error"in T?()=>T.error:T.onError,v=o;return(async()=>{let p=v?performance.now():0;o&&c({type:"step_start",workflowId:u,stepKey:s,name:a,ts:Date.now()});let E=await m();if(E.ok){let w=performance.now()-p;return c({type:"step_success",workflowId:u,stepKey:s,name:a,ts:Date.now(),durationMs:w}),s&&c({type:"step_complete",workflowId:u,stepKey:s,name:a,ts:Date.now(),durationMs:w,result:k(E.value)}),E.value}else{let w=g(E.error),y=performance.now()-p,C=h(w,{origin:"result",resultCause:E.error});throw c({type:"step_error",workflowId:u,stepKey:s,name:a,ts:Date.now(),durationMs:y,error:C}),s&&c({type:"step_complete",workflowId:u,stepKey:s,name:a,ts:Date.now(),durationMs:y,result:i(w,{cause:E.error}),meta:{origin:"result",resultCause:E.error}}),r?.(w,a),P(w,{origin:"result",resultCause:E.error})}})()};let x=await e(t);return k(x)}catch(t){if(L(t))throw t.thrown;if(U(t)){let x=M(t.meta);if(l||r)return i(t.error,{cause:x});if(D(t.error))return i(t.error,{cause:x});let m=K(t);return i(m,{cause:x})}if(l){let x=l(t);return r?.(x,"unexpected"),i(x,{cause:t})}let f={type:"UNEXPECTED_ERROR",cause:{type:"UNCAUGHT_EXCEPTION",thrown:t}};return r?.(f,"unexpected"),i(f,{cause:t})}}_.strict=(e,n)=>_(e,n);var S=class extends Error{constructor(r,o){super(`Unwrap called on an error result: ${String(r)}`);this.error=r;this.cause=o;this.name="UnwrapError"}},J=e=>{if(e.ok)return e.value;throw new S(e.error,e.cause)},G=(e,n)=>e.ok?e.value:n,q=(e,n)=>e.ok?e.value:n(e.error,e.cause);function B(e,n){try{return k(e())}catch(r){return n?i(n(r),{cause:r}):i(r)}}async function H(e,n){try{return k(await e)}catch(r){return n?i(n(r),{cause:r}):i(r)}}async function $(e,n){try{return k(await e())}catch(r){return n?i(n(r),{cause:r}):i(r)}}function z(e,n){return e!=null?k(e):i(n())}function Q(e,n){return e.ok?k(n(e.value)):e}function Z(e,n){return e.ok?e:i(n(e.error),{cause:e.cause})}function ee(e,n){return e.ok?n.ok(e.value):n.err(e.error,e.cause)}function ne(e,n){return e.ok?n(e.value):e}function re(e,n){return e.ok&&n(e.value),e}function te(e,n){return e.ok||n(e.error,e.cause),e}function oe(e,n,r){if(!e.ok)return e;try{return k(n(e.value))}catch(o){return i(r(o),{cause:o})}}function se(e,n,r){if(e.ok)return e;try{return i(n(e.error),{cause:e.cause})}catch(o){return i(r(o),{cause:o})}}function ue(e){let n=[];for(let r of e){if(!r.ok)return r;n.push(r.value)}return k(n)}async function ae(e){return e.length===0?k([]):new Promise(n=>{let r=!1,o=e.length,l=new Array(e.length);for(let R=0;R<e.length;R++){let d=R;Promise.resolve(e[d]).catch(u=>i({type:"PROMISE_REJECTED",cause:u},{cause:{type:"PROMISE_REJECTION",reason:u}})).then(u=>{if(!r){if(!u.ok){r=!0,n(u);return}l[d]=u.value,o--,o===0&&n(k(l))}})}})}function ie(e){let n=[],r=[];for(let o of e)o.ok?n.push(o.value):r.push({error:o.error,cause:o.cause});return r.length>0?i(r):k(n)}function le(e){let n=[],r=[];for(let o of e)o.ok?n.push(o.value):r.push(o.error);return{values:n,errors:r}}function Ee(e){if(e.length===0)return i({type:"EMPTY_INPUT",message:"any() requires at least one Result"});let n=null;for(let r of e){if(r.ok)return r;n||(n=r)}return n}async function ce(e){return e.length===0?i({type:"EMPTY_INPUT",message:"anyAsync() requires at least one Result"}):new Promise(n=>{let r=!1,o=e.length,l=null;for(let R of e)Promise.resolve(R).catch(d=>i({type:"PROMISE_REJECTED",cause:d},{cause:{type:"PROMISE_REJECTION",reason:d}})).then(d=>{if(!r){if(d.ok){r=!0,n(d);return}l||(l=d),o--,o===0&&n(l)}})})}async function pe(e){let n=await Promise.all(e.map(l=>Promise.resolve(l).then(R=>({status:"result",result:R})).catch(R=>({status:"rejected",error:{type:"PROMISE_REJECTED",cause:R},cause:{type:"PROMISE_REJECTION",reason:R}})))),r=[],o=[];for(let l of n)l.status==="rejected"?o.push({error:l.error,cause:l.cause}):l.result.ok?r.push(l.result.value):o.push({error:l.result.error,cause:l.result.cause});return o.length>0?i(o):k(r)}export{b as EARLY_EXIT_SYMBOL,S as UnwrapError,ue as all,ae as allAsync,ie as allSettled,pe as allSettledAsync,ne as andThen,Ee as any,ce as anyAsync,N as createEarlyExit,i as err,B as from,z as fromNullable,H as fromPromise,V as isEarlyExit,Y as isErr,W as isOk,D as isUnexpectedError,Q as map,Z as mapError,se as mapErrorTry,oe as mapTry,ee as match,k as ok,le as partition,_ as run,re as tap,te as tapError,$ as tryAsync,J as unwrap,G as unwrapOr,q as unwrapOrElse};
1
+ var f=e=>({ok:!0,value:e}),l=(e,n)=>({ok:!1,error:e,...n?.cause!==void 0?{cause:n.cause}:{}}),G=e=>e.ok,q=e=>!e.ok,L=e=>typeof e=="object"&&e!==null&&e.type==="UNEXPECTED_ERROR",O=Symbol("early-exit");function X(e,n){return{[O]:!0,error:e,meta:n}}function W(e){return typeof e=="object"&&e!==null&&e[O]===!0}var K=Symbol("mapper-exception");function Y(e){return{[K]:!0,thrown:e}}function J(e){return typeof e=="object"&&e!==null&&e[K]===!0}function $(e){return typeof e=="string"?{name:e}:e??{}}async function M(e,n){let{onError:t,onEvent:u,catchUnexpected:w,workflowId:C,context:A}=n&&typeof n=="object"?n:{},a=C??crypto.randomUUID(),D=!t&&!w,g=[],F=0,I=r=>r??`step_${++F}`,c=r=>{if(r.type==="step_success"){let S=r.stepId;for(let x=g.length-1;x>=0;x--){let T=g[x];if(T.type==="race"&&!T.winnerId){T.winnerId=S;break}}}u?.(r,A)},h=X,b=r=>W(r),_=(r,S)=>D?S?.origin==="result"?{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"result",error:r,...S.resultCause!==void 0?{cause:S.resultCause}:{}}}:S?.origin==="throw"?{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"throw",error:r,thrown:S.thrown}}:{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"result",error:r}}:r,N=r=>r.origin==="result"?r.resultCause:r.thrown,V=r=>({type:"UNEXPECTED_ERROR",cause:r.meta.origin==="result"?{type:"STEP_FAILURE",origin:"result",error:r.error,...r.meta.resultCause!==void 0?{cause:r.meta.resultCause}:{}}:{type:"STEP_FAILURE",origin:"throw",error:r.error,thrown:r.meta.thrown}});try{let r=(T,k)=>(async()=>{let{name:o,key:s}=$(k),y=I(s),p=u?performance.now():0;u&&c({type:"step_start",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now()});let i;try{i=await(typeof T=="function"?T():T)}catch(R){let v=performance.now()-p;if(b(R))throw c({type:"step_aborted",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now(),durationMs:v}),R;if(w){let P;try{P=w(R)}catch(j){throw Y(j)}throw c({type:"step_error",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now(),durationMs:v,error:P}),s&&c({type:"step_complete",workflowId:a,stepKey:s,name:o,ts:Date.now(),durationMs:v,result:l(P,{cause:R}),meta:{origin:"throw",thrown:R}}),t?.(P,o),h(P,{origin:"throw",thrown:R})}else{let P={type:"UNEXPECTED_ERROR",cause:{type:"UNCAUGHT_EXCEPTION",thrown:R}};throw c({type:"step_error",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now(),durationMs:v,error:P}),s&&c({type:"step_complete",workflowId:a,stepKey:s,name:o,ts:Date.now(),durationMs:v,result:l(P,{cause:R}),meta:{origin:"throw",thrown:R}}),R}}let E=performance.now()-p;if(i.ok)return c({type:"step_success",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now(),durationMs:E}),s&&c({type:"step_complete",workflowId:a,stepKey:s,name:o,ts:Date.now(),durationMs:E,result:i}),i.value;let d=_(i.error,{origin:"result",resultCause:i.cause});throw c({type:"step_error",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now(),durationMs:E,error:d}),s&&c({type:"step_complete",workflowId:a,stepKey:s,name:o,ts:Date.now(),durationMs:E,result:i,meta:{origin:"result",resultCause:i.cause}}),t?.(i.error,o),h(i.error,{origin:"result",resultCause:i.cause})})();r.try=(T,k)=>{let o=k.name,s=k.key,y=I(s),m="error"in k?()=>k.error:k.onError,p=u;return(async()=>{let i=p?performance.now():0;u&&c({type:"step_start",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now()});try{let E=await T(),d=performance.now()-i;return c({type:"step_success",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now(),durationMs:d}),s&&c({type:"step_complete",workflowId:a,stepKey:s,name:o,ts:Date.now(),durationMs:d,result:f(E)}),E}catch(E){let d=m(E),R=performance.now()-i,v=_(d,{origin:"throw",thrown:E});throw c({type:"step_error",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now(),durationMs:R,error:v}),s&&c({type:"step_complete",workflowId:a,stepKey:s,name:o,ts:Date.now(),durationMs:R,result:l(d,{cause:E}),meta:{origin:"throw",thrown:E}}),t?.(d,o),h(d,{origin:"throw",thrown:E})}})()},r.fromResult=(T,k)=>{let o=k.name,s=k.key,y=I(s),m="error"in k?()=>k.error:k.onError,p=u;return(async()=>{let i=p?performance.now():0;u&&c({type:"step_start",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now()});let E=await T();if(E.ok){let d=performance.now()-i;return c({type:"step_success",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now(),durationMs:d}),s&&c({type:"step_complete",workflowId:a,stepKey:s,name:o,ts:Date.now(),durationMs:d,result:f(E.value)}),E.value}else{let d=m(E.error),R=performance.now()-i,v=_(d,{origin:"result",resultCause:E.error});throw c({type:"step_error",workflowId:a,stepId:y,stepKey:s,name:o,ts:Date.now(),durationMs:R,error:v}),s&&c({type:"step_complete",workflowId:a,stepKey:s,name:o,ts:Date.now(),durationMs:R,result:l(d,{cause:E.error}),meta:{origin:"result",resultCause:E.error}}),t?.(d,o),h(d,{origin:"result",resultCause:E.error})}})()},r.parallel=(T,k)=>{let o=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let s=performance.now(),y=!1;g.push({scopeId:o,type:"parallel"});let m=()=>{if(y)return;y=!0;let p=g.findIndex(i=>i.scopeId===o);p!==-1&&g.splice(p,1),c({type:"scope_end",workflowId:a,scopeId:o,ts:Date.now(),durationMs:performance.now()-s})};c({type:"scope_start",workflowId:a,scopeId:o,scopeType:"parallel",name:T,ts:Date.now()});try{let p=await k();if(m(),!p.ok)throw t?.(p.error,T),h(p.error,{origin:"result",resultCause:p.cause});return p.value}catch(p){throw m(),p}})()},r.race=(T,k)=>{let o=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let s=performance.now(),y=!1,m={scopeId:o,type:"race",winnerId:void 0};g.push(m);let p=()=>{if(y)return;y=!0;let i=g.findIndex(E=>E.scopeId===o);i!==-1&&g.splice(i,1),c({type:"scope_end",workflowId:a,scopeId:o,ts:Date.now(),durationMs:performance.now()-s,winnerId:m.winnerId})};c({type:"scope_start",workflowId:a,scopeId:o,scopeType:"race",name:T,ts:Date.now()});try{let i=await k();if(p(),!i.ok)throw t?.(i.error,T),h(i.error,{origin:"result",resultCause:i.cause});return i.value}catch(i){throw p(),i}})()},r.allSettled=(T,k)=>{let o=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let s=performance.now(),y=!1;g.push({scopeId:o,type:"allSettled"});let m=()=>{if(y)return;y=!0;let p=g.findIndex(i=>i.scopeId===o);p!==-1&&g.splice(p,1),c({type:"scope_end",workflowId:a,scopeId:o,ts:Date.now(),durationMs:performance.now()-s})};c({type:"scope_start",workflowId:a,scopeId:o,scopeType:"allSettled",name:T,ts:Date.now()});try{let p=await k();if(m(),!p.ok)throw t?.(p.error,T),h(p.error,{origin:"result",resultCause:p.cause});return p.value}catch(p){throw m(),p}})()};let x=await e(r);return f(x)}catch(r){if(J(r))throw r.thrown;if(b(r)){let x=N(r.meta);if(w||t)return l(r.error,{cause:x});if(L(r.error))return l(r.error,{cause:x});let T=V(r);return l(T,{cause:x})}if(w){let x=w(r);return t?.(x,"unexpected"),l(x,{cause:r})}let S={type:"UNEXPECTED_ERROR",cause:{type:"UNCAUGHT_EXCEPTION",thrown:r}};return t?.(S,"unexpected"),l(S,{cause:r})}}M.strict=(e,n)=>M(e,n);var U=class extends Error{constructor(t,u){super(`Unwrap called on an error result: ${String(t)}`);this.error=t;this.cause=u;this.name="UnwrapError"}},B=e=>{if(e.ok)return e.value;throw new U(e.error,e.cause)},H=(e,n)=>e.ok?e.value:n,z=(e,n)=>e.ok?e.value:n(e.error,e.cause);function Q(e,n){try{return f(e())}catch(t){return n?l(n(t),{cause:t}):l(t)}}async function Z(e,n){try{return f(await e)}catch(t){return n?l(n(t),{cause:t}):l(t)}}async function ee(e,n){try{return f(await e())}catch(t){return n?l(n(t),{cause:t}):l(t)}}function ne(e,n){return e!=null?f(e):l(n())}function te(e,n){return e.ok?f(n(e.value)):e}function re(e,n){return e.ok?e:l(n(e.error),{cause:e.cause})}function oe(e,n){return e.ok?n.ok(e.value):n.err(e.error,e.cause)}function se(e,n){return e.ok?n(e.value):e}function ue(e,n){return e.ok&&n(e.value),e}function ae(e,n){return e.ok||n(e.error,e.cause),e}function ie(e,n,t){if(!e.ok)return e;try{return f(n(e.value))}catch(u){return l(t(u),{cause:u})}}function pe(e,n,t){if(e.ok)return e;try{return l(n(e.error),{cause:e.cause})}catch(u){return l(t(u),{cause:u})}}function ce(e){let n=[];for(let t of e){if(!t.ok)return t;n.push(t.value)}return f(n)}async function le(e){return e.length===0?f([]):new Promise(n=>{let t=!1,u=e.length,w=new Array(e.length);for(let C=0;C<e.length;C++){let A=C;Promise.resolve(e[A]).catch(a=>l({type:"PROMISE_REJECTED",cause:a},{cause:{type:"PROMISE_REJECTION",reason:a}})).then(a=>{if(!t){if(!a.ok){t=!0,n(a);return}w[A]=a.value,u--,u===0&&n(f(w))}})}})}function Ee(e){let n=[],t=[];for(let u of e)u.ok?n.push(u.value):t.push({error:u.error,cause:u.cause});return t.length>0?l(t):f(n)}function we(e){let n=[],t=[];for(let u of e)u.ok?n.push(u.value):t.push(u.error);return{values:n,errors:t}}function ye(e){if(e.length===0)return l({type:"EMPTY_INPUT",message:"any() requires at least one Result"});let n=null;for(let t of e){if(t.ok)return t;n||(n=t)}return n}async function Te(e){return e.length===0?l({type:"EMPTY_INPUT",message:"anyAsync() requires at least one Result"}):new Promise(n=>{let t=!1,u=e.length,w=null;for(let C of e)Promise.resolve(C).catch(A=>l({type:"PROMISE_REJECTED",cause:A},{cause:{type:"PROMISE_REJECTION",reason:A}})).then(A=>{if(!t){if(A.ok){t=!0,n(A);return}w||(w=A),u--,u===0&&n(w)}})})}async function ke(e){let n=await Promise.all(e.map(w=>Promise.resolve(w).then(C=>({status:"result",result:C})).catch(C=>({status:"rejected",error:{type:"PROMISE_REJECTED",cause:C},cause:{type:"PROMISE_REJECTION",reason:C}})))),t=[],u=[];for(let w of n)w.status==="rejected"?u.push({error:w.error,cause:w.cause}):w.result.ok?t.push(w.result.value):u.push({error:w.result.error,cause:w.result.cause});return u.length>0?l(u):f(t)}export{O as EARLY_EXIT_SYMBOL,U as UnwrapError,ce as all,le as allAsync,Ee as allSettled,ke as allSettledAsync,se as andThen,ye as any,Te as anyAsync,X as createEarlyExit,l as err,Q as from,ne as fromNullable,Z as fromPromise,W as isEarlyExit,q as isErr,G as isOk,L as isUnexpectedError,te as map,re as mapError,pe as mapErrorTry,ie as mapTry,oe as match,f as ok,we as partition,M as run,ue as tap,ae as tapError,ee as tryAsync,B as unwrap,H as unwrapOr,z as unwrapOrElse};
2
2
  //# sourceMappingURL=core.js.map