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
@@ -0,0 +1,171 @@
1
+ import { A as AsyncResult } from './core-BuTBsR0x.cjs';
2
+
3
+ /**
4
+ * awaitly/resource
5
+ *
6
+ * Resource scope management for cleanup guarantees.
7
+ * Provides RAII-style resource management for async operations.
8
+ *
9
+ * Tree-shakable - only import if needed.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * import { withScope, ok, type AsyncResult } from 'awaitly';
14
+ *
15
+ * interface DbClient {
16
+ * query: (sql: string) => Promise<unknown[]>;
17
+ * close: () => Promise<void>;
18
+ * }
19
+ *
20
+ * const result = await withScope(async (scope) => {
21
+ * // Register database connection for cleanup
22
+ * const db = scope.add({
23
+ * value: await createDbConnection(),
24
+ * close: async () => db.value.close(),
25
+ * });
26
+ *
27
+ * // Register another resource
28
+ * const cache = scope.add({
29
+ * value: await createCache(),
30
+ * close: async () => cache.value.disconnect(),
31
+ * });
32
+ *
33
+ * // Use resources...
34
+ * const users = await db.value.query('SELECT * FROM users');
35
+ *
36
+ * return ok(users);
37
+ * // Resources are automatically closed in LIFO order when scope exits
38
+ * });
39
+ * ```
40
+ */
41
+
42
+ /**
43
+ * A resource with a value and a cleanup function.
44
+ */
45
+ interface Resource<T> {
46
+ /** The resource value */
47
+ value: T;
48
+ /** Function to release/cleanup the resource */
49
+ close: () => Promise<void>;
50
+ }
51
+ /**
52
+ * A scope that tracks resources for cleanup.
53
+ */
54
+ interface ResourceScope {
55
+ /**
56
+ * Add a resource to the scope.
57
+ * Resources are closed in LIFO order when the scope exits.
58
+ * @param resource - The resource to track
59
+ * @returns The resource value for convenience
60
+ */
61
+ add: <T>(resource: Resource<T>) => T;
62
+ /**
63
+ * Manually close all resources in the scope.
64
+ * Called automatically by `withScope`, but can be called manually if needed.
65
+ * Resources are closed in LIFO order (last added = first closed).
66
+ */
67
+ close: () => Promise<void>;
68
+ /**
69
+ * Check if a resource is in this scope.
70
+ */
71
+ has: <T>(resource: Resource<T>) => boolean;
72
+ /**
73
+ * Get the number of resources in the scope.
74
+ */
75
+ size: () => number;
76
+ }
77
+ /**
78
+ * Error that occurred during resource cleanup.
79
+ */
80
+ interface ResourceCleanupError {
81
+ type: "RESOURCE_CLEANUP_ERROR";
82
+ /** Errors that occurred during cleanup (may have multiple if multiple resources failed) */
83
+ errors: unknown[];
84
+ /** The original result from the scope function (if any) */
85
+ originalResult?: unknown;
86
+ }
87
+ /**
88
+ * Type guard for ResourceCleanupError.
89
+ */
90
+ declare function isResourceCleanupError(error: unknown): error is ResourceCleanupError;
91
+ /**
92
+ * Create a resource scope for tracking resources.
93
+ *
94
+ * Resources are closed in LIFO order (last added = first closed).
95
+ * This matches the typical dependency pattern where later resources
96
+ * may depend on earlier ones.
97
+ *
98
+ * @returns A ResourceScope instance
99
+ *
100
+ * @example
101
+ * ```typescript
102
+ * const scope = createResourceScope();
103
+ *
104
+ * try {
105
+ * const db = scope.add({
106
+ * value: await createConnection(),
107
+ * close: async () => connection.close(),
108
+ * });
109
+ *
110
+ * const cache = scope.add({
111
+ * value: await createCache(db),
112
+ * close: async () => cache.disconnect(),
113
+ * });
114
+ *
115
+ * // Use resources...
116
+ * } finally {
117
+ * await scope.close();
118
+ * // cache closed first, then db
119
+ * }
120
+ * ```
121
+ */
122
+ declare function createResourceScope(): ResourceScope;
123
+ /**
124
+ * Run a function with automatic resource cleanup.
125
+ *
126
+ * Resources added to the scope are automatically closed when the function
127
+ * completes, regardless of whether it succeeds or fails.
128
+ *
129
+ * @param fn - Function that uses the resource scope
130
+ * @returns The result of the function, or an error if cleanup failed
131
+ *
132
+ * @example
133
+ * ```typescript
134
+ * const result = await withScope(async (scope) => {
135
+ * const db = scope.add({
136
+ * value: await createConnection(),
137
+ * close: async () => db.value.close(),
138
+ * });
139
+ *
140
+ * const users = await db.value.query('SELECT * FROM users');
141
+ * return ok(users);
142
+ * });
143
+ *
144
+ * if (result.ok) {
145
+ * console.log('Users:', result.value);
146
+ * }
147
+ * ```
148
+ */
149
+ declare function withScope<T, E>(fn: (scope: ResourceScope) => AsyncResult<T, E>): AsyncResult<T, E | ResourceCleanupError>;
150
+ /**
151
+ * Create a resource from a factory function with automatic cleanup.
152
+ *
153
+ * Convenience helper for creating resources that follow the acquire/release pattern.
154
+ *
155
+ * @param acquire - Function to acquire the resource
156
+ * @param release - Function to release the resource
157
+ * @returns A Resource instance
158
+ *
159
+ * @example
160
+ * ```typescript
161
+ * const dbResource = await createResource(
162
+ * () => createConnection({ host: 'localhost' }),
163
+ * (conn) => conn.close()
164
+ * );
165
+ *
166
+ * const db = scope.add(dbResource);
167
+ * ```
168
+ */
169
+ declare function createResource<T>(acquire: () => T | Promise<T>, release: (value: T) => void | Promise<void>): Promise<Resource<T>>;
170
+
171
+ export { type Resource, type ResourceCleanupError, type ResourceScope, createResource, createResourceScope, isResourceCleanupError, withScope };
@@ -0,0 +1,171 @@
1
+ import { A as AsyncResult } from './core-BuTBsR0x.js';
2
+
3
+ /**
4
+ * awaitly/resource
5
+ *
6
+ * Resource scope management for cleanup guarantees.
7
+ * Provides RAII-style resource management for async operations.
8
+ *
9
+ * Tree-shakable - only import if needed.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * import { withScope, ok, type AsyncResult } from 'awaitly';
14
+ *
15
+ * interface DbClient {
16
+ * query: (sql: string) => Promise<unknown[]>;
17
+ * close: () => Promise<void>;
18
+ * }
19
+ *
20
+ * const result = await withScope(async (scope) => {
21
+ * // Register database connection for cleanup
22
+ * const db = scope.add({
23
+ * value: await createDbConnection(),
24
+ * close: async () => db.value.close(),
25
+ * });
26
+ *
27
+ * // Register another resource
28
+ * const cache = scope.add({
29
+ * value: await createCache(),
30
+ * close: async () => cache.value.disconnect(),
31
+ * });
32
+ *
33
+ * // Use resources...
34
+ * const users = await db.value.query('SELECT * FROM users');
35
+ *
36
+ * return ok(users);
37
+ * // Resources are automatically closed in LIFO order when scope exits
38
+ * });
39
+ * ```
40
+ */
41
+
42
+ /**
43
+ * A resource with a value and a cleanup function.
44
+ */
45
+ interface Resource<T> {
46
+ /** The resource value */
47
+ value: T;
48
+ /** Function to release/cleanup the resource */
49
+ close: () => Promise<void>;
50
+ }
51
+ /**
52
+ * A scope that tracks resources for cleanup.
53
+ */
54
+ interface ResourceScope {
55
+ /**
56
+ * Add a resource to the scope.
57
+ * Resources are closed in LIFO order when the scope exits.
58
+ * @param resource - The resource to track
59
+ * @returns The resource value for convenience
60
+ */
61
+ add: <T>(resource: Resource<T>) => T;
62
+ /**
63
+ * Manually close all resources in the scope.
64
+ * Called automatically by `withScope`, but can be called manually if needed.
65
+ * Resources are closed in LIFO order (last added = first closed).
66
+ */
67
+ close: () => Promise<void>;
68
+ /**
69
+ * Check if a resource is in this scope.
70
+ */
71
+ has: <T>(resource: Resource<T>) => boolean;
72
+ /**
73
+ * Get the number of resources in the scope.
74
+ */
75
+ size: () => number;
76
+ }
77
+ /**
78
+ * Error that occurred during resource cleanup.
79
+ */
80
+ interface ResourceCleanupError {
81
+ type: "RESOURCE_CLEANUP_ERROR";
82
+ /** Errors that occurred during cleanup (may have multiple if multiple resources failed) */
83
+ errors: unknown[];
84
+ /** The original result from the scope function (if any) */
85
+ originalResult?: unknown;
86
+ }
87
+ /**
88
+ * Type guard for ResourceCleanupError.
89
+ */
90
+ declare function isResourceCleanupError(error: unknown): error is ResourceCleanupError;
91
+ /**
92
+ * Create a resource scope for tracking resources.
93
+ *
94
+ * Resources are closed in LIFO order (last added = first closed).
95
+ * This matches the typical dependency pattern where later resources
96
+ * may depend on earlier ones.
97
+ *
98
+ * @returns A ResourceScope instance
99
+ *
100
+ * @example
101
+ * ```typescript
102
+ * const scope = createResourceScope();
103
+ *
104
+ * try {
105
+ * const db = scope.add({
106
+ * value: await createConnection(),
107
+ * close: async () => connection.close(),
108
+ * });
109
+ *
110
+ * const cache = scope.add({
111
+ * value: await createCache(db),
112
+ * close: async () => cache.disconnect(),
113
+ * });
114
+ *
115
+ * // Use resources...
116
+ * } finally {
117
+ * await scope.close();
118
+ * // cache closed first, then db
119
+ * }
120
+ * ```
121
+ */
122
+ declare function createResourceScope(): ResourceScope;
123
+ /**
124
+ * Run a function with automatic resource cleanup.
125
+ *
126
+ * Resources added to the scope are automatically closed when the function
127
+ * completes, regardless of whether it succeeds or fails.
128
+ *
129
+ * @param fn - Function that uses the resource scope
130
+ * @returns The result of the function, or an error if cleanup failed
131
+ *
132
+ * @example
133
+ * ```typescript
134
+ * const result = await withScope(async (scope) => {
135
+ * const db = scope.add({
136
+ * value: await createConnection(),
137
+ * close: async () => db.value.close(),
138
+ * });
139
+ *
140
+ * const users = await db.value.query('SELECT * FROM users');
141
+ * return ok(users);
142
+ * });
143
+ *
144
+ * if (result.ok) {
145
+ * console.log('Users:', result.value);
146
+ * }
147
+ * ```
148
+ */
149
+ declare function withScope<T, E>(fn: (scope: ResourceScope) => AsyncResult<T, E>): AsyncResult<T, E | ResourceCleanupError>;
150
+ /**
151
+ * Create a resource from a factory function with automatic cleanup.
152
+ *
153
+ * Convenience helper for creating resources that follow the acquire/release pattern.
154
+ *
155
+ * @param acquire - Function to acquire the resource
156
+ * @param release - Function to release the resource
157
+ * @returns A Resource instance
158
+ *
159
+ * @example
160
+ * ```typescript
161
+ * const dbResource = await createResource(
162
+ * () => createConnection({ host: 'localhost' }),
163
+ * (conn) => conn.close()
164
+ * );
165
+ *
166
+ * const db = scope.add(dbResource);
167
+ * ```
168
+ */
169
+ declare function createResource<T>(acquire: () => T | Promise<T>, release: (value: T) => void | Promise<void>): Promise<Resource<T>>;
170
+
171
+ export { type Resource, type ResourceCleanupError, type ResourceScope, createResource, createResourceScope, isResourceCleanupError, withScope };
@@ -0,0 +1,2 @@
1
+ var B=e=>({ok:!0,value:e}),P=(e,u)=>({ok:!1,error:e,...u?.cause!==void 0?{cause:u.cause}:{}});var se=e=>typeof e=="object"&&e!==null&&e.type==="UNEXPECTED_ERROR",F=Symbol.for("step_timeout_marker");function H(e){return typeof e!="object"||e===null?!1:e.type==="STEP_TIMEOUT"?!0:F in e}function ue(e){if(!(typeof e!="object"||e===null)){if(e.type==="STEP_TIMEOUT"){let u=e;return{timeoutMs:u.timeoutMs,stepName:u.stepName,stepKey:u.stepKey,attempt:u.attempt}}if(F in e)return e[F]}}var ee=Symbol("early-exit");function ae(e,u){return{[ee]:!0,error:e,meta:u}}function ie(e){return typeof e=="object"&&e!==null&&e[ee]===!0}var ne=Symbol("mapper-exception");function pe(e){return{[ne]:!0,thrown:e}}function ce(e){return typeof e=="object"&&e!==null&&e[ne]===!0}function le(e){return typeof e=="string"?{name:e}:e??{}}function q(e,u){let{backoff:E,initialDelay:R,maxDelay:g,jitter:I}=u,k;switch(E){case"fixed":k=R;break;case"linear":k=R*e;break;case"exponential":k=R*Math.pow(2,e-1);break}if(k=Math.min(k,g),I){let o=k*.25*Math.random();k=k+o}return Math.floor(k)}function G(e){return new Promise(u=>setTimeout(u,e))}var Q=Symbol("timeout");async function Ee(e,u,E){let R=new AbortController,g=u.error??{type:"STEP_TIMEOUT",stepName:E.name,stepKey:E.key,timeoutMs:u.ms,attempt:E.attempt},I,k=new Promise((_,d)=>{I=setTimeout(()=>{R.abort(),d({[Q]:!0,error:g})},u.ms)}),o;u.signal?o=Promise.resolve(e(R.signal)):o=Promise.resolve(e());try{return await Promise.race([o,k])}catch(_){if(typeof _=="object"&&_!==null&&_[Q]===!0){let d=_.error;if(typeof d=="object"&&d!==null&&d.type!=="STEP_TIMEOUT"){let V={timeoutMs:u.ms,stepName:E.name,stepKey:E.key,attempt:E.attempt};F in d?d[F]=V:Object.defineProperty(d,F,{value:V,enumerable:!1,writable:!0,configurable:!1})}throw d}throw _}finally{clearTimeout(I)}}var K={backoff:"exponential",initialDelay:100,maxDelay:3e4,jitter:!0,retryOn:()=>!0,onRetry:()=>{}};async function Z(e,u){let{onError:E,onEvent:R,catchUnexpected:g,workflowId:I,context:k}=u&&typeof u=="object"?u:{},o=I??crypto.randomUUID(),_=!E&&!g,d=[],V=0,W=t=>t??`step_${++V}`,c=t=>{let x=t.context!==void 0||k===void 0?t:{...t,context:k};if(x.type==="step_success"){let v=x.stepId;for(let U=d.length-1;U>=0;U--){let j=d[U];if(j.type==="race"&&!j.winnerId){j.winnerId=v;break}}}R?.(x,k)},O=ae,z=t=>ie(t),X=(t,x)=>_?x?.origin==="result"?{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"result",error:t,...x.resultCause!==void 0?{cause:x.resultCause}:{}}}:x?.origin==="throw"?{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"throw",error:t,thrown:x.thrown}}:{type:"UNEXPECTED_ERROR",cause:{type:"STEP_FAILURE",origin:"result",error:t}}:t,re=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 x=function(y,a){let s=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let n=performance.now(),r=!1;d.push({scopeId:s,type:"parallel"});let f=()=>{if(r)return;r=!0;let p=d.findIndex(i=>i.scopeId===s);p!==-1&&d.splice(p,1),c({type:"scope_end",workflowId:o,scopeId:s,ts:Date.now(),durationMs:performance.now()-n})};c({type:"scope_start",workflowId:o,scopeId:s,scopeType:"parallel",name:y,ts:Date.now()});try{let p=await a();if(f(),!p.ok)throw E?.(p.error,y,k),O(p.error,{origin:"result",resultCause:p.cause});return p.value}catch(p){throw f(),p}})()},v=function(y,a){let s=Object.keys(y),n=a.name??`Parallel(${s.join(", ")})`,r=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let f=performance.now(),p=!1;d.push({scopeId:r,type:"parallel"});let i=()=>{if(p)return;p=!0;let w=d.findIndex(T=>T.scopeId===r);w!==-1&&d.splice(w,1),c({type:"scope_end",workflowId:o,scopeId:r,ts:Date.now(),durationMs:performance.now()-f})};c({type:"scope_start",workflowId:o,scopeId:r,scopeType:"parallel",name:n,ts:Date.now()});try{let w=await new Promise(A=>{if(s.length===0){A([]);return}let h=!1,C=s.length,N=new Array(s.length);for(let b=0;b<s.length;b++){let D=s[b],Y=b;Promise.resolve(y[D]()).catch(m=>P({type:"PROMISE_REJECTED",cause:m},{cause:{type:"PROMISE_REJECTION",reason:m}})).then(m=>{if(!h){if(!m.ok){h=!0,A([{key:D,result:m}]);return}N[Y]={key:D,result:m},C--,C===0&&A(N)}})}});i();let T={};for(let{key:A,result:h}of w){if(!h.ok)throw E?.(h.error,A,k),O(h.error,{origin:"result",resultCause:h.cause});T[A]=h.value}return T}catch(w){throw i(),w}})()};var we=x,me=v;let t=(y,a)=>(async()=>{let s=le(a),{name:n,key:r,retry:f,timeout:p}=s,i=W(r),w=R,T=w?performance.now():0;if(!(typeof y=="function")){if(f&&f.attempts>1)throw new Error("step: retry options require a function operation. Direct Promise/Result values cannot be re-executed on retry. Wrap your operation in a function: step(() => yourOperation, { retry: {...} })");if(p)throw new Error("step: timeout options require a function operation. Direct Promise/Result values cannot be wrapped with timeout after they've started. Wrap your operation in a function: step(() => yourOperation, { timeout: {...} })")}let C={attempts:Math.max(1,f?.attempts??1),backoff:f?.backoff??K.backoff,initialDelay:f?.initialDelay??K.initialDelay,maxDelay:f?.maxDelay??K.maxDelay,jitter:f?.jitter??K.jitter,retryOn:f?.retryOn??K.retryOn,onRetry:f?.onRetry??K.onRetry};R&&c({type:"step_start",workflowId:o,stepId:i,stepKey:r,name:n,ts:Date.now()});let N;for(let m=1;m<=C.attempts;m++){let oe=w?performance.now():0;try{let l;if(typeof y=="function"?p?l=await Ee(y,p,{name:n,key:r,attempt:m}):l=await y():l=await y,l.ok){let M=performance.now()-T;return c({type:"step_success",workflowId:o,stepId:i,stepKey:r,name:n,ts:Date.now(),durationMs:M}),r&&c({type:"step_complete",workflowId:o,stepKey:r,name:n,ts:Date.now(),durationMs:M,result:l}),l.value}if(N=l,m<C.attempts&&C.retryOn(l.error,m)){let M=q(m,C);c({type:"step_retry",workflowId:o,stepId:i,stepKey:r,name:n,ts:Date.now(),attempt:m+1,maxAttempts:C.attempts,delayMs:M,error:l.error}),C.onRetry(l.error,m,M),await G(M);continue}C.attempts>1&&c({type:"step_retries_exhausted",workflowId:o,stepId:i,stepKey:r,name:n,ts:Date.now(),durationMs:performance.now()-T,attempts:m,lastError:l.error});break}catch(l){let M=performance.now()-oe;if(z(l))throw c({type:"step_aborted",workflowId:o,stepId:i,stepKey:r,name:n,ts:Date.now(),durationMs:M}),l;if(H(l)){let S=ue(l),$=p?.ms??S?.timeoutMs??0;if(c({type:"step_timeout",workflowId:o,stepId:i,stepKey:r,name:n,ts:Date.now(),timeoutMs:$,attempt:m}),m<C.attempts&&C.retryOn(l,m)){let J=q(m,C);c({type:"step_retry",workflowId:o,stepId:i,stepKey:r,name:n,ts:Date.now(),attempt:m+1,maxAttempts:C.attempts,delayMs:J,error:l}),C.onRetry(l,m,J),await G(J);continue}C.attempts>1&&c({type:"step_retries_exhausted",workflowId:o,stepId:i,stepKey:r,name:n,ts:Date.now(),durationMs:performance.now()-T,attempts:m,lastError:l})}if(m<C.attempts&&C.retryOn(l,m)){let S=q(m,C);c({type:"step_retry",workflowId:o,stepId:i,stepKey:r,name:n,ts:Date.now(),attempt:m+1,maxAttempts:C.attempts,delayMs:S,error:l}),C.onRetry(l,m,S),await G(S);continue}C.attempts>1&&!H(l)&&c({type:"step_retries_exhausted",workflowId:o,stepId:i,stepKey:r,name:n,ts:Date.now(),durationMs:performance.now()-T,attempts:m,lastError:l});let L=performance.now()-T;if(g){let S;try{S=g(l)}catch($){throw pe($)}throw c({type:"step_error",workflowId:o,stepId:i,stepKey:r,name:n,ts:Date.now(),durationMs:L,error:S}),r&&c({type:"step_complete",workflowId:o,stepKey:r,name:n,ts:Date.now(),durationMs:L,result:P(S,{cause:l}),meta:{origin:"throw",thrown:l}}),E?.(S,n,k),O(S,{origin:"throw",thrown:l})}else{let S={type:"UNEXPECTED_ERROR",cause:{type:"UNCAUGHT_EXCEPTION",thrown:l}};throw c({type:"step_error",workflowId:o,stepId:i,stepKey:r,name:n,ts:Date.now(),durationMs:L,error:S}),r&&c({type:"step_complete",workflowId:o,stepKey:r,name:n,ts:Date.now(),durationMs:L,result:P(S,{cause:l}),meta:{origin:"throw",thrown:l}}),l}}}let b=N,D=performance.now()-T,Y=X(b.error,{origin:"result",resultCause:b.cause});throw c({type:"step_error",workflowId:o,stepId:i,stepKey:r,name:n,ts:Date.now(),durationMs:D,error:Y}),r&&c({type:"step_complete",workflowId:o,stepKey:r,name:n,ts:Date.now(),durationMs:D,result:b,meta:{origin:"result",resultCause:b.cause}}),E?.(b.error,n,k),O(b.error,{origin:"result",resultCause:b.cause})})();t.try=(y,a)=>{let s=a.name,n=a.key,r=W(n),f="error"in a?()=>a.error:a.onError,p=R;return(async()=>{let i=p?performance.now():0;R&&c({type:"step_start",workflowId:o,stepId:r,stepKey:n,name:s,ts:Date.now()});try{let w=await y(),T=performance.now()-i;return c({type:"step_success",workflowId:o,stepId:r,stepKey:n,name:s,ts:Date.now(),durationMs:T}),n&&c({type:"step_complete",workflowId:o,stepKey:n,name:s,ts:Date.now(),durationMs:T,result:B(w)}),w}catch(w){let T=f(w),A=performance.now()-i,h=X(T,{origin:"throw",thrown:w});throw c({type:"step_error",workflowId:o,stepId:r,stepKey:n,name:s,ts:Date.now(),durationMs:A,error:h}),n&&c({type:"step_complete",workflowId:o,stepKey:n,name:s,ts:Date.now(),durationMs:A,result:P(T,{cause:w}),meta:{origin:"throw",thrown:w}}),E?.(T,s,k),O(T,{origin:"throw",thrown:w})}})()},t.fromResult=(y,a)=>{let s=a.name,n=a.key,r=W(n),f="error"in a?()=>a.error:a.onError,p=R;return(async()=>{let i=p?performance.now():0;R&&c({type:"step_start",workflowId:o,stepId:r,stepKey:n,name:s,ts:Date.now()});let w=await y();if(w.ok){let T=performance.now()-i;return c({type:"step_success",workflowId:o,stepId:r,stepKey:n,name:s,ts:Date.now(),durationMs:T}),n&&c({type:"step_complete",workflowId:o,stepKey:n,name:s,ts:Date.now(),durationMs:T,result:B(w.value)}),w.value}else{let T=f(w.error),A=performance.now()-i,h=X(T,{origin:"result",resultCause:w.error});throw c({type:"step_error",workflowId:o,stepId:r,stepKey:n,name:s,ts:Date.now(),durationMs:A,error:h}),n&&c({type:"step_complete",workflowId:o,stepKey:n,name:s,ts:Date.now(),durationMs:A,result:P(T,{cause:w.error}),meta:{origin:"result",resultCause:w.error}}),E?.(T,s,k),O(T,{origin:"result",resultCause:w.error})}})()},t.retry=(y,a)=>t(y,{name:a.name,key:a.key,retry:{attempts:a.attempts,backoff:a.backoff,initialDelay:a.initialDelay,maxDelay:a.maxDelay,jitter:a.jitter,retryOn:a.retryOn,onRetry:a.onRetry},timeout:a.timeout}),t.withTimeout=(y,a)=>t(y,{name:a.name,key:a.key,timeout:a}),t.parallel=((...y)=>{if(typeof y[0]=="string"){let a=y[0],s=y[1];return x(a,s)}else{let a=y[0],s=y[1]??{};return v(a,s)}}),t.race=(y,a)=>{let s=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let n=performance.now(),r=!1,f={scopeId:s,type:"race",winnerId:void 0};d.push(f);let p=()=>{if(r)return;r=!0;let i=d.findIndex(w=>w.scopeId===s);i!==-1&&d.splice(i,1),c({type:"scope_end",workflowId:o,scopeId:s,ts:Date.now(),durationMs:performance.now()-n,winnerId:f.winnerId})};c({type:"scope_start",workflowId:o,scopeId:s,scopeType:"race",name:y,ts:Date.now()});try{let i=await a();if(p(),!i.ok)throw E?.(i.error,y,k),O(i.error,{origin:"result",resultCause:i.cause});return i.value}catch(i){throw p(),i}})()},t.allSettled=(y,a)=>{let s=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let n=performance.now(),r=!1;d.push({scopeId:s,type:"allSettled"});let f=()=>{if(r)return;r=!0;let p=d.findIndex(i=>i.scopeId===s);p!==-1&&d.splice(p,1),c({type:"scope_end",workflowId:o,scopeId:s,ts:Date.now(),durationMs:performance.now()-n})};c({type:"scope_start",workflowId:o,scopeId:s,scopeType:"allSettled",name:y,ts:Date.now()});try{let p=await a();if(f(),!p.ok)throw E?.(p.error,y,k),O(p.error,{origin:"result",resultCause:p.cause});return p.value}catch(p){throw f(),p}})()};let j=await e(t);return B(j)}catch(t){if(ce(t))throw t.thrown;if(z(t)){let v=t.meta.origin==="throw"?t.meta.thrown:t.meta.resultCause;if(g||E)return P(t.error,{cause:v});if(se(t.error))return P(t.error,{cause:v});let U=re(t);return P(U,{cause:v})}if(g){let v=g(t);return E?.(v,"unexpected",k),P(v,{cause:t})}let x={type:"UNEXPECTED_ERROR",cause:{type:"UNCAUGHT_EXCEPTION",thrown:t}};return E?.(x,"unexpected",k),P(x,{cause:t})}}Z.strict=(e,u)=>Z(e,u);function te(e){return typeof e=="object"&&e!==null&&e.type==="RESOURCE_CLEANUP_ERROR"}function ye(){let e=[];return{add:u=>(e.push(u),u.value),close:async()=>{let u=[];for(let E=e.length-1;E>=0;E--)try{await e[E].close()}catch(R){u.push(R)}if(e.length=0,u.length>0)throw{type:"RESOURCE_CLEANUP_ERROR",errors:u}},has:u=>e.includes(u),size:()=>e.length}}async function de(e){let u=ye(),E;try{E=await e(u)}catch(R){try{await u.close()}catch(g){if(te(g))return P({...g,originalResult:{thrown:R}})}throw R}try{await u.close()}catch(R){if(te(R))return P({...R,originalResult:E});throw R}return E}async function fe(e,u){let E=await e();return{value:E,close:async()=>{await u(E)}}}export{fe as createResource,ye as createResourceScope,te as isResourceCleanupError,de as withScope};
2
+ //# sourceMappingURL=resource.js.map