awaitly 1.35.0 → 2.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.
- package/dist/{duration.d.ts → di-BDlT7InM.d.cts} +15 -1
- package/dist/{duration.d.cts → di-BbFFfO8y.d.ts} +15 -1
- package/dist/errors-DtXvrCiO.d.cts +708 -0
- package/dist/errors-DtXvrCiO.d.ts +708 -0
- package/dist/index.cjs +4594 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1970 -141
- package/dist/index.d.ts +1970 -141
- package/dist/index.js +4398 -1
- package/dist/index.js.map +1 -1
- package/dist/result.cjs +641 -1
- package/dist/result.cjs.map +1 -1
- package/dist/result.d.cts +29 -4
- package/dist/result.d.ts +29 -4
- package/dist/result.js +561 -1
- package/dist/result.js.map +1 -1
- package/dist/testing.cjs +4202 -8
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +2 -6
- package/dist/testing.d.ts +2 -6
- package/dist/testing.js +4154 -8
- package/dist/testing.js.map +1 -1
- package/dist/{run-entry-DGs0tySr.d.cts → types-B8NfNRGX.d.ts} +1078 -1502
- package/dist/{run-entry-BOuNyVoO.d.ts → types-BZ2f4MRR.d.cts} +1078 -1502
- package/dist/workflow.cjs +7096 -6
- package/dist/workflow.cjs.map +1 -1
- package/dist/workflow.d.cts +3346 -22
- package/dist/workflow.d.ts +3346 -22
- package/dist/workflow.js +6929 -6
- package/dist/workflow.js.map +1 -1
- package/package.json +3 -168
- package/dist/adapters.cjs +0 -7
- package/dist/adapters.cjs.map +0 -1
- package/dist/adapters.d.cts +0 -179
- package/dist/adapters.d.ts +0 -179
- package/dist/adapters.js +0 -7
- package/dist/adapters.js.map +0 -1
- package/dist/batch.cjs +0 -7
- package/dist/batch.cjs.map +0 -1
- package/dist/batch.d.cts +0 -200
- package/dist/batch.d.ts +0 -200
- package/dist/batch.js +0 -7
- package/dist/batch.js.map +0 -1
- package/dist/bind-deps.cjs +0 -2
- package/dist/bind-deps.cjs.map +0 -1
- package/dist/bind-deps.d.cts +0 -28
- package/dist/bind-deps.d.ts +0 -28
- package/dist/bind-deps.js +0 -2
- package/dist/bind-deps.js.map +0 -1
- package/dist/cache.cjs +0 -2
- package/dist/cache.cjs.map +0 -1
- package/dist/cache.d.cts +0 -269
- package/dist/cache.d.ts +0 -269
- package/dist/cache.js +0 -2
- package/dist/cache.js.map +0 -1
- package/dist/circuit-breaker.cjs +0 -7
- package/dist/circuit-breaker.cjs.map +0 -1
- package/dist/circuit-breaker.d.cts +0 -211
- package/dist/circuit-breaker.d.ts +0 -211
- package/dist/circuit-breaker.js +0 -7
- package/dist/circuit-breaker.js.map +0 -1
- package/dist/conditional.cjs +0 -2
- package/dist/conditional.cjs.map +0 -1
- package/dist/conditional.d.cts +0 -252
- package/dist/conditional.d.ts +0 -252
- package/dist/conditional.js +0 -2
- package/dist/conditional.js.map +0 -1
- package/dist/core.cjs +0 -7
- package/dist/core.cjs.map +0 -1
- package/dist/core.d.cts +0 -5
- package/dist/core.d.ts +0 -5
- package/dist/core.js +0 -7
- package/dist/core.js.map +0 -1
- package/dist/di-By77n4Fa.d.ts +0 -15
- package/dist/di-OJfsohf-.d.cts +0 -15
- package/dist/diagnostics.cjs +0 -8
- package/dist/diagnostics.cjs.map +0 -1
- package/dist/diagnostics.d.cts +0 -68
- package/dist/diagnostics.d.ts +0 -68
- package/dist/diagnostics.js +0 -8
- package/dist/diagnostics.js.map +0 -1
- package/dist/durable.cjs +0 -11
- package/dist/durable.cjs.map +0 -1
- package/dist/durable.d.cts +0 -9
- package/dist/durable.d.ts +0 -9
- package/dist/durable.js +0 -11
- package/dist/durable.js.map +0 -1
- package/dist/duration.cjs +0 -2
- package/dist/duration.cjs.map +0 -1
- package/dist/duration.js +0 -2
- package/dist/duration.js.map +0 -1
- package/dist/engine.cjs +0 -11
- package/dist/engine.cjs.map +0 -1
- package/dist/engine.d.cts +0 -115
- package/dist/engine.d.ts +0 -115
- package/dist/engine.js +0 -11
- package/dist/engine.js.map +0 -1
- package/dist/errors.cjs +0 -2
- package/dist/errors.cjs.map +0 -1
- package/dist/errors.d.cts +0 -361
- package/dist/errors.d.ts +0 -361
- package/dist/errors.js +0 -2
- package/dist/errors.js.map +0 -1
- package/dist/fetch.cjs +0 -7
- package/dist/fetch.cjs.map +0 -1
- package/dist/fetch.d.cts +0 -86
- package/dist/fetch.d.ts +0 -86
- package/dist/fetch.js +0 -7
- package/dist/fetch.js.map +0 -1
- package/dist/flow.cjs +0 -7
- package/dist/flow.cjs.map +0 -1
- package/dist/flow.d.cts +0 -163
- package/dist/flow.d.ts +0 -163
- package/dist/flow.js +0 -7
- package/dist/flow.js.map +0 -1
- package/dist/functional.cjs +0 -2
- package/dist/functional.cjs.map +0 -1
- package/dist/functional.d.cts +0 -444
- package/dist/functional.d.ts +0 -444
- package/dist/functional.js +0 -2
- package/dist/functional.js.map +0 -1
- package/dist/guards-4sV7mTqj.d.cts +0 -72
- package/dist/guards-BIX05ALH.d.ts +0 -72
- package/dist/hitl-DFn4Xa_l.d.cts +0 -468
- package/dist/hitl-DU5VpKq7.d.ts +0 -468
- package/dist/hitl.cjs +0 -7
- package/dist/hitl.cjs.map +0 -1
- package/dist/hitl.d.cts +0 -442
- package/dist/hitl.d.ts +0 -442
- package/dist/hitl.js +0 -7
- package/dist/hitl.js.map +0 -1
- package/dist/index-CnvBryQB.d.ts +0 -417
- package/dist/index-DEZEf8Fs.d.cts +0 -417
- package/dist/match-entry-DjI2bLpD.d.cts +0 -209
- package/dist/match-entry-DjI2bLpD.d.ts +0 -209
- package/dist/match.cjs +0 -2
- package/dist/match.cjs.map +0 -1
- package/dist/match.d.cts +0 -1
- package/dist/match.d.ts +0 -1
- package/dist/match.js +0 -2
- package/dist/match.js.map +0 -1
- package/dist/otel.cjs +0 -2
- package/dist/otel.cjs.map +0 -1
- package/dist/otel.d.cts +0 -188
- package/dist/otel.d.ts +0 -188
- package/dist/otel.js +0 -2
- package/dist/otel.js.map +0 -1
- package/dist/persistence-entry-B-8PjnSR.d.cts +0 -831
- package/dist/persistence-entry-D8zRkLiT.d.ts +0 -831
- package/dist/persistence.cjs +0 -2
- package/dist/persistence.cjs.map +0 -1
- package/dist/persistence.d.cts +0 -7
- package/dist/persistence.d.ts +0 -7
- package/dist/persistence.js +0 -2
- package/dist/persistence.js.map +0 -1
- package/dist/policies.cjs +0 -2
- package/dist/policies.cjs.map +0 -1
- package/dist/policies.d.cts +0 -379
- package/dist/policies.d.ts +0 -379
- package/dist/policies.js +0 -2
- package/dist/policies.js.map +0 -1
- package/dist/ratelimit.cjs +0 -7
- package/dist/ratelimit.cjs.map +0 -1
- package/dist/ratelimit.d.cts +0 -458
- package/dist/ratelimit.d.ts +0 -458
- package/dist/ratelimit.js +0 -7
- package/dist/ratelimit.js.map +0 -1
- package/dist/reliability.cjs +0 -11
- package/dist/reliability.cjs.map +0 -1
- package/dist/reliability.d.cts +0 -11
- package/dist/reliability.d.ts +0 -11
- package/dist/reliability.js +0 -11
- package/dist/reliability.js.map +0 -1
- package/dist/resolver.cjs +0 -7
- package/dist/resolver.cjs.map +0 -1
- package/dist/resolver.d.cts +0 -68
- package/dist/resolver.d.ts +0 -68
- package/dist/resolver.js +0 -7
- package/dist/resolver.js.map +0 -1
- package/dist/resource.cjs +0 -7
- package/dist/resource.cjs.map +0 -1
- package/dist/resource.d.cts +0 -174
- package/dist/resource.d.ts +0 -174
- package/dist/resource.js +0 -7
- package/dist/resource.js.map +0 -1
- package/dist/result/retry.cjs +0 -2
- package/dist/result/retry.cjs.map +0 -1
- package/dist/result/retry.d.cts +0 -70
- package/dist/result/retry.d.ts +0 -70
- package/dist/result/retry.js +0 -2
- package/dist/result/retry.js.map +0 -1
- package/dist/retry.cjs +0 -2
- package/dist/retry.cjs.map +0 -1
- package/dist/retry.d.cts +0 -388
- package/dist/retry.d.ts +0 -388
- package/dist/retry.js +0 -2
- package/dist/retry.js.map +0 -1
- package/dist/run.cjs +0 -7
- package/dist/run.cjs.map +0 -1
- package/dist/run.d.cts +0 -4
- package/dist/run.d.ts +0 -4
- package/dist/run.js +0 -7
- package/dist/run.js.map +0 -1
- package/dist/saga.cjs +0 -11
- package/dist/saga.cjs.map +0 -1
- package/dist/saga.d.cts +0 -164
- package/dist/saga.d.ts +0 -164
- package/dist/saga.js +0 -11
- package/dist/saga.js.map +0 -1
- package/dist/singleflight.cjs +0 -2
- package/dist/singleflight.cjs.map +0 -1
- package/dist/singleflight.d.cts +0 -145
- package/dist/singleflight.d.ts +0 -145
- package/dist/singleflight.js +0 -2
- package/dist/singleflight.js.map +0 -1
- package/dist/slugs.cjs +0 -2
- package/dist/slugs.cjs.map +0 -1
- package/dist/slugs.d.cts +0 -67
- package/dist/slugs.d.ts +0 -67
- package/dist/slugs.js +0 -2
- package/dist/slugs.js.map +0 -1
- package/dist/streaming.cjs +0 -9
- package/dist/streaming.cjs.map +0 -1
- package/dist/streaming.d.cts +0 -596
- package/dist/streaming.d.ts +0 -596
- package/dist/streaming.js +0 -9
- package/dist/streaming.js.map +0 -1
- package/dist/tagged-error.cjs +0 -2
- package/dist/tagged-error.cjs.map +0 -1
- package/dist/tagged-error.d.cts +0 -275
- package/dist/tagged-error.d.ts +0 -275
- package/dist/tagged-error.js +0 -2
- package/dist/tagged-error.js.map +0 -1
- package/dist/types-BziYHFkD.d.ts +0 -323
- package/dist/types-C5jLEUqY.d.cts +0 -323
- package/dist/webhook.cjs +0 -7
- package/dist/webhook.cjs.map +0 -1
- package/dist/webhook.d.cts +0 -499
- package/dist/webhook.d.ts +0 -499
- package/dist/webhook.js +0 -7
- package/dist/webhook.js.map +0 -1
package/dist/resource.d.cts
DELETED
|
@@ -1,174 +0,0 @@
|
|
|
1
|
-
import { c as AsyncResult } from './run-entry-DGs0tySr.cjs';
|
|
2
|
-
import './errors.cjs';
|
|
3
|
-
import './tagged-error.cjs';
|
|
4
|
-
import './slugs.cjs';
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* awaitly/resource
|
|
8
|
-
*
|
|
9
|
-
* Resource scope management for cleanup guarantees.
|
|
10
|
-
* Provides RAII-style resource management for async operations.
|
|
11
|
-
*
|
|
12
|
-
* Tree-shakable - only import if needed.
|
|
13
|
-
*
|
|
14
|
-
* @example
|
|
15
|
-
* ```typescript
|
|
16
|
-
* import { withScope, ok, type AsyncResult } from 'awaitly';
|
|
17
|
-
*
|
|
18
|
-
* interface DbClient {
|
|
19
|
-
* query: (sql: string) => Promise<unknown[]>;
|
|
20
|
-
* close: () => Promise<void>;
|
|
21
|
-
* }
|
|
22
|
-
*
|
|
23
|
-
* const result = await withScope(async (scope) => {
|
|
24
|
-
* // Register database connection for cleanup
|
|
25
|
-
* const db = scope.add({
|
|
26
|
-
* value: await createDbConnection(),
|
|
27
|
-
* close: async () => db.value.close(),
|
|
28
|
-
* });
|
|
29
|
-
*
|
|
30
|
-
* // Register another resource
|
|
31
|
-
* const cache = scope.add({
|
|
32
|
-
* value: await createCache(),
|
|
33
|
-
* close: async () => cache.value.disconnect(),
|
|
34
|
-
* });
|
|
35
|
-
*
|
|
36
|
-
* // Use resources...
|
|
37
|
-
* const users = await db.value.query('SELECT * FROM users');
|
|
38
|
-
*
|
|
39
|
-
* return ok(users);
|
|
40
|
-
* // Resources are automatically closed in LIFO order when scope exits
|
|
41
|
-
* });
|
|
42
|
-
* ```
|
|
43
|
-
*/
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* A resource with a value and a cleanup function.
|
|
47
|
-
*/
|
|
48
|
-
interface Resource<T> {
|
|
49
|
-
/** The resource value */
|
|
50
|
-
value: T;
|
|
51
|
-
/** Function to release/cleanup the resource */
|
|
52
|
-
close: () => Promise<void>;
|
|
53
|
-
}
|
|
54
|
-
/**
|
|
55
|
-
* A scope that tracks resources for cleanup.
|
|
56
|
-
*/
|
|
57
|
-
interface ResourceScope {
|
|
58
|
-
/**
|
|
59
|
-
* Add a resource to the scope.
|
|
60
|
-
* Resources are closed in LIFO order when the scope exits.
|
|
61
|
-
* @param resource - The resource to track
|
|
62
|
-
* @returns The resource value for convenience
|
|
63
|
-
*/
|
|
64
|
-
add: <T>(resource: Resource<T>) => T;
|
|
65
|
-
/**
|
|
66
|
-
* Manually close all resources in the scope.
|
|
67
|
-
* Called automatically by `withScope`, but can be called manually if needed.
|
|
68
|
-
* Resources are closed in LIFO order (last added = first closed).
|
|
69
|
-
*/
|
|
70
|
-
close: () => Promise<void>;
|
|
71
|
-
/**
|
|
72
|
-
* Check if a resource is in this scope.
|
|
73
|
-
*/
|
|
74
|
-
has: <T>(resource: Resource<T>) => boolean;
|
|
75
|
-
/**
|
|
76
|
-
* Get the number of resources in the scope.
|
|
77
|
-
*/
|
|
78
|
-
size: () => number;
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* Error that occurred during resource cleanup.
|
|
82
|
-
*/
|
|
83
|
-
interface ResourceCleanupError {
|
|
84
|
-
type: "RESOURCE_CLEANUP_ERROR";
|
|
85
|
-
/** Errors that occurred during cleanup (may have multiple if multiple resources failed) */
|
|
86
|
-
errors: unknown[];
|
|
87
|
-
/** The original result from the scope function (if any) */
|
|
88
|
-
originalResult?: unknown;
|
|
89
|
-
}
|
|
90
|
-
/**
|
|
91
|
-
* Type guard for ResourceCleanupError.
|
|
92
|
-
*/
|
|
93
|
-
declare function isResourceCleanupError(error: unknown): error is ResourceCleanupError;
|
|
94
|
-
/**
|
|
95
|
-
* Create a resource scope for tracking resources.
|
|
96
|
-
*
|
|
97
|
-
* Resources are closed in LIFO order (last added = first closed).
|
|
98
|
-
* This matches the typical dependency pattern where later resources
|
|
99
|
-
* may depend on earlier ones.
|
|
100
|
-
*
|
|
101
|
-
* @returns A ResourceScope instance
|
|
102
|
-
*
|
|
103
|
-
* @example
|
|
104
|
-
* ```typescript
|
|
105
|
-
* const scope = createResourceScope();
|
|
106
|
-
*
|
|
107
|
-
* try {
|
|
108
|
-
* const db = scope.add({
|
|
109
|
-
* value: await createConnection(),
|
|
110
|
-
* close: async () => connection.close(),
|
|
111
|
-
* });
|
|
112
|
-
*
|
|
113
|
-
* const cache = scope.add({
|
|
114
|
-
* value: await createCache(db),
|
|
115
|
-
* close: async () => cache.disconnect(),
|
|
116
|
-
* });
|
|
117
|
-
*
|
|
118
|
-
* // Use resources...
|
|
119
|
-
* } finally {
|
|
120
|
-
* await scope.close();
|
|
121
|
-
* // cache closed first, then db
|
|
122
|
-
* }
|
|
123
|
-
* ```
|
|
124
|
-
*/
|
|
125
|
-
declare function createResourceScope(): ResourceScope;
|
|
126
|
-
/**
|
|
127
|
-
* Run a function with automatic resource cleanup.
|
|
128
|
-
*
|
|
129
|
-
* Resources added to the scope are automatically closed when the function
|
|
130
|
-
* completes, regardless of whether it succeeds or fails.
|
|
131
|
-
*
|
|
132
|
-
* @param fn - Function that uses the resource scope
|
|
133
|
-
* @returns The result of the function, or an error if cleanup failed
|
|
134
|
-
*
|
|
135
|
-
* @example
|
|
136
|
-
* ```typescript
|
|
137
|
-
* const result = await withScope(async (scope) => {
|
|
138
|
-
* const db = scope.add({
|
|
139
|
-
* value: await createConnection(),
|
|
140
|
-
* close: async () => db.value.close(),
|
|
141
|
-
* });
|
|
142
|
-
*
|
|
143
|
-
* const users = await db.value.query('SELECT * FROM users');
|
|
144
|
-
* return ok(users);
|
|
145
|
-
* });
|
|
146
|
-
*
|
|
147
|
-
* if (result.ok) {
|
|
148
|
-
* console.log('Users:', result.value);
|
|
149
|
-
* }
|
|
150
|
-
* ```
|
|
151
|
-
*/
|
|
152
|
-
declare function withScope<T, E>(fn: (scope: ResourceScope) => AsyncResult<T, E>): AsyncResult<T, E | ResourceCleanupError>;
|
|
153
|
-
/**
|
|
154
|
-
* Create a resource from a factory function with automatic cleanup.
|
|
155
|
-
*
|
|
156
|
-
* Convenience helper for creating resources that follow the acquire/release pattern.
|
|
157
|
-
*
|
|
158
|
-
* @param acquire - Function to acquire the resource
|
|
159
|
-
* @param release - Function to release the resource
|
|
160
|
-
* @returns A Resource instance
|
|
161
|
-
*
|
|
162
|
-
* @example
|
|
163
|
-
* ```typescript
|
|
164
|
-
* const dbResource = await createResource(
|
|
165
|
-
* () => createConnection({ host: 'localhost' }),
|
|
166
|
-
* (conn) => conn.close()
|
|
167
|
-
* );
|
|
168
|
-
*
|
|
169
|
-
* const db = scope.add(dbResource);
|
|
170
|
-
* ```
|
|
171
|
-
*/
|
|
172
|
-
declare function createResource<T>(acquire: () => T | Promise<T>, release: (value: T) => void | Promise<void>): Promise<Resource<T>>;
|
|
173
|
-
|
|
174
|
-
export { type Resource, type ResourceCleanupError, type ResourceScope, createResource, createResourceScope, isResourceCleanupError, withScope };
|
package/dist/resource.d.ts
DELETED
|
@@ -1,174 +0,0 @@
|
|
|
1
|
-
import { c as AsyncResult } from './run-entry-BOuNyVoO.js';
|
|
2
|
-
import './errors.js';
|
|
3
|
-
import './tagged-error.js';
|
|
4
|
-
import './slugs.js';
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* awaitly/resource
|
|
8
|
-
*
|
|
9
|
-
* Resource scope management for cleanup guarantees.
|
|
10
|
-
* Provides RAII-style resource management for async operations.
|
|
11
|
-
*
|
|
12
|
-
* Tree-shakable - only import if needed.
|
|
13
|
-
*
|
|
14
|
-
* @example
|
|
15
|
-
* ```typescript
|
|
16
|
-
* import { withScope, ok, type AsyncResult } from 'awaitly';
|
|
17
|
-
*
|
|
18
|
-
* interface DbClient {
|
|
19
|
-
* query: (sql: string) => Promise<unknown[]>;
|
|
20
|
-
* close: () => Promise<void>;
|
|
21
|
-
* }
|
|
22
|
-
*
|
|
23
|
-
* const result = await withScope(async (scope) => {
|
|
24
|
-
* // Register database connection for cleanup
|
|
25
|
-
* const db = scope.add({
|
|
26
|
-
* value: await createDbConnection(),
|
|
27
|
-
* close: async () => db.value.close(),
|
|
28
|
-
* });
|
|
29
|
-
*
|
|
30
|
-
* // Register another resource
|
|
31
|
-
* const cache = scope.add({
|
|
32
|
-
* value: await createCache(),
|
|
33
|
-
* close: async () => cache.value.disconnect(),
|
|
34
|
-
* });
|
|
35
|
-
*
|
|
36
|
-
* // Use resources...
|
|
37
|
-
* const users = await db.value.query('SELECT * FROM users');
|
|
38
|
-
*
|
|
39
|
-
* return ok(users);
|
|
40
|
-
* // Resources are automatically closed in LIFO order when scope exits
|
|
41
|
-
* });
|
|
42
|
-
* ```
|
|
43
|
-
*/
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* A resource with a value and a cleanup function.
|
|
47
|
-
*/
|
|
48
|
-
interface Resource<T> {
|
|
49
|
-
/** The resource value */
|
|
50
|
-
value: T;
|
|
51
|
-
/** Function to release/cleanup the resource */
|
|
52
|
-
close: () => Promise<void>;
|
|
53
|
-
}
|
|
54
|
-
/**
|
|
55
|
-
* A scope that tracks resources for cleanup.
|
|
56
|
-
*/
|
|
57
|
-
interface ResourceScope {
|
|
58
|
-
/**
|
|
59
|
-
* Add a resource to the scope.
|
|
60
|
-
* Resources are closed in LIFO order when the scope exits.
|
|
61
|
-
* @param resource - The resource to track
|
|
62
|
-
* @returns The resource value for convenience
|
|
63
|
-
*/
|
|
64
|
-
add: <T>(resource: Resource<T>) => T;
|
|
65
|
-
/**
|
|
66
|
-
* Manually close all resources in the scope.
|
|
67
|
-
* Called automatically by `withScope`, but can be called manually if needed.
|
|
68
|
-
* Resources are closed in LIFO order (last added = first closed).
|
|
69
|
-
*/
|
|
70
|
-
close: () => Promise<void>;
|
|
71
|
-
/**
|
|
72
|
-
* Check if a resource is in this scope.
|
|
73
|
-
*/
|
|
74
|
-
has: <T>(resource: Resource<T>) => boolean;
|
|
75
|
-
/**
|
|
76
|
-
* Get the number of resources in the scope.
|
|
77
|
-
*/
|
|
78
|
-
size: () => number;
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* Error that occurred during resource cleanup.
|
|
82
|
-
*/
|
|
83
|
-
interface ResourceCleanupError {
|
|
84
|
-
type: "RESOURCE_CLEANUP_ERROR";
|
|
85
|
-
/** Errors that occurred during cleanup (may have multiple if multiple resources failed) */
|
|
86
|
-
errors: unknown[];
|
|
87
|
-
/** The original result from the scope function (if any) */
|
|
88
|
-
originalResult?: unknown;
|
|
89
|
-
}
|
|
90
|
-
/**
|
|
91
|
-
* Type guard for ResourceCleanupError.
|
|
92
|
-
*/
|
|
93
|
-
declare function isResourceCleanupError(error: unknown): error is ResourceCleanupError;
|
|
94
|
-
/**
|
|
95
|
-
* Create a resource scope for tracking resources.
|
|
96
|
-
*
|
|
97
|
-
* Resources are closed in LIFO order (last added = first closed).
|
|
98
|
-
* This matches the typical dependency pattern where later resources
|
|
99
|
-
* may depend on earlier ones.
|
|
100
|
-
*
|
|
101
|
-
* @returns A ResourceScope instance
|
|
102
|
-
*
|
|
103
|
-
* @example
|
|
104
|
-
* ```typescript
|
|
105
|
-
* const scope = createResourceScope();
|
|
106
|
-
*
|
|
107
|
-
* try {
|
|
108
|
-
* const db = scope.add({
|
|
109
|
-
* value: await createConnection(),
|
|
110
|
-
* close: async () => connection.close(),
|
|
111
|
-
* });
|
|
112
|
-
*
|
|
113
|
-
* const cache = scope.add({
|
|
114
|
-
* value: await createCache(db),
|
|
115
|
-
* close: async () => cache.disconnect(),
|
|
116
|
-
* });
|
|
117
|
-
*
|
|
118
|
-
* // Use resources...
|
|
119
|
-
* } finally {
|
|
120
|
-
* await scope.close();
|
|
121
|
-
* // cache closed first, then db
|
|
122
|
-
* }
|
|
123
|
-
* ```
|
|
124
|
-
*/
|
|
125
|
-
declare function createResourceScope(): ResourceScope;
|
|
126
|
-
/**
|
|
127
|
-
* Run a function with automatic resource cleanup.
|
|
128
|
-
*
|
|
129
|
-
* Resources added to the scope are automatically closed when the function
|
|
130
|
-
* completes, regardless of whether it succeeds or fails.
|
|
131
|
-
*
|
|
132
|
-
* @param fn - Function that uses the resource scope
|
|
133
|
-
* @returns The result of the function, or an error if cleanup failed
|
|
134
|
-
*
|
|
135
|
-
* @example
|
|
136
|
-
* ```typescript
|
|
137
|
-
* const result = await withScope(async (scope) => {
|
|
138
|
-
* const db = scope.add({
|
|
139
|
-
* value: await createConnection(),
|
|
140
|
-
* close: async () => db.value.close(),
|
|
141
|
-
* });
|
|
142
|
-
*
|
|
143
|
-
* const users = await db.value.query('SELECT * FROM users');
|
|
144
|
-
* return ok(users);
|
|
145
|
-
* });
|
|
146
|
-
*
|
|
147
|
-
* if (result.ok) {
|
|
148
|
-
* console.log('Users:', result.value);
|
|
149
|
-
* }
|
|
150
|
-
* ```
|
|
151
|
-
*/
|
|
152
|
-
declare function withScope<T, E>(fn: (scope: ResourceScope) => AsyncResult<T, E>): AsyncResult<T, E | ResourceCleanupError>;
|
|
153
|
-
/**
|
|
154
|
-
* Create a resource from a factory function with automatic cleanup.
|
|
155
|
-
*
|
|
156
|
-
* Convenience helper for creating resources that follow the acquire/release pattern.
|
|
157
|
-
*
|
|
158
|
-
* @param acquire - Function to acquire the resource
|
|
159
|
-
* @param release - Function to release the resource
|
|
160
|
-
* @returns A Resource instance
|
|
161
|
-
*
|
|
162
|
-
* @example
|
|
163
|
-
* ```typescript
|
|
164
|
-
* const dbResource = await createResource(
|
|
165
|
-
* () => createConnection({ host: 'localhost' }),
|
|
166
|
-
* (conn) => conn.close()
|
|
167
|
-
* );
|
|
168
|
-
*
|
|
169
|
-
* const db = scope.add(dbResource);
|
|
170
|
-
* ```
|
|
171
|
-
*/
|
|
172
|
-
declare function createResource<T>(acquire: () => T | Promise<T>, release: (value: T) => void | Promise<void>): Promise<Resource<T>>;
|
|
173
|
-
|
|
174
|
-
export { type Resource, type ResourceCleanupError, type ResourceScope, createResource, createResourceScope, isResourceCleanupError, withScope };
|
package/dist/resource.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
var Ne={"step-require-id":"step-require-id","step-no-immediate-execution":"step-no-immediate-execution","step-require-thunk-for-key":"step-require-thunk-for-key","step-no-bare-await":"step-no-bare-await","step-no-try-catch-wrap":"step-no-try-catch-wrap","step-stable-cache-keys":"step-stable-cache-keys","workflow-no-floating":"workflow-no-floating","workflow-options-position":"workflow-options-position","workflow-callback-shape":"workflow-callback-shape","workflow-no-callable-form":"workflow-no-callable-form","workflow-no-dynamic-import":"workflow-no-dynamic-import","result-no-floating":"result-no-floating","result-require-handling":"result-require-handling","result-no-double-wrap":"result-no-double-wrap","result-no-manual-propagation":"result-no-manual-propagation","result-no-direct-ok-err":"result-no-direct-ok-err","error-check-unexpected-first":"error-check-unexpected-first","error-access-cause":"error-access-cause","error-normalize":"error-normalize","error-no-throw-in-deps":"error-no-throw-in-deps","concurrency-no-promise-all":"concurrency-no-promise-all","concurrency-no-promise-race":"concurrency-no-promise-race","concurrency-no-promise-allsettled":"concurrency-no-promise-allsettled","runtime-step-timeout":"runtime-step-timeout","runtime-step-aborted":"runtime-step-aborted","runtime-retry-exhausted":"runtime-retry-exhausted","runtime-rate-limit":"runtime-rate-limit","runtime-circuit-open":"runtime-circuit-open","runtime-unexpected":"runtime-unexpected","runtime-resolver-not-found":"runtime-resolver-not-found","runtime-saga-compensation":"runtime-saga-compensation"};function ye(n){return`https://jagreehal.github.io/awaitly/rules/#${n}`}var er=Object.keys(Ne);var te=class extends Error{_tag};function K(n,e){return class extends te{_tag=n;constructor(p,k){let A=e?.message?e.message(p??{}):n;if(super(A),this.name=n,e?.slug!==void 0){if(!e.hint)throw new TypeError(`TaggedError: 'hint' is required when 'slug' is set (slug: "${e.slug}")`);Object.defineProperty(this,"code",{value:e.slug,enumerable:!0,writable:!1,configurable:!1}),Object.defineProperty(this,"hint",{value:e.hint,enumerable:!0,writable:!1,configurable:!1}),Object.defineProperty(this,"docsUrl",{value:ye(e.slug),enumerable:!0,writable:!1,configurable:!1})}if(Object.setPrototypeOf(this,new.target.prototype),p&&typeof p=="object"){let E;if(e?.slug!==void 0){let{_tag:N,name:v,message:D,stack:s,code:j,hint:B,docsUrl:we,...re}=p;E=re}else{let{_tag:N,name:v,message:D,stack:s,...j}=p;E=j}let R=Object.prototype.hasOwnProperty.call(E,"cause"),P=R?E.cause:void 0;R&&delete E.cause;let M=k?.cause!==void 0;if(R&&M)throw new TypeError("TaggedError: cannot provide 'cause' in props when also setting ErrorOptions.cause");Object.assign(this,E),R&&(this.cause=P),M&&(this.cause=k?.cause)}else k?.cause!==void 0&&(this.cause=k.cause)}}}Object.defineProperty(K,Symbol.hasInstance,{value:n=>n instanceof te});(A=>{function n(E){return E instanceof Error}A.isError=n;function e(E){return E instanceof te}A.isTaggedError=e;function p(E,R){let P=E._tag,M=R[P];return M(E)}A.match=p;function k(E,R,P){let M=E._tag,N=R[M];return N?N(E):P(E)}A.matchPartial=k})(K||={});var fe=class extends K("TimeoutError",{slug:"runtime-step-timeout",hint:"Increase the step's timeout option, or check why the upstream operation is slow.",message:e=>e.operation?`TimeoutError: ${e.operation} timed out after ${e.ms}ms`:`TimeoutError: Operation timed out after ${e.ms}ms`}){},Te=class extends K("RetryExhaustedError",{slug:"runtime-retry-exhausted",hint:"All retry attempts failed. Inspect lastError and decide whether to surface it or compensate.",message:e=>e.operation?`RetryExhaustedError: ${e.operation} failed after ${e.attempts} attempts`:`RetryExhaustedError: Operation failed after ${e.attempts} attempts`}){},ke=class extends K("RateLimitError",{slug:"runtime-rate-limit",hint:"Wait retryAfterMs before retrying, or apply step.cache to deduplicate calls.",message:e=>e.limiterName?`RateLimitError: Rate limit exceeded for ${e.limiterName}${e.retryAfterMs?`, retry after ${e.retryAfterMs}ms`:""}`:`RateLimitError: Rate limit exceeded${e.retryAfterMs?`, retry after ${e.retryAfterMs}ms`:""}`}){},Re=class extends K("CircuitBreakerOpenError",{slug:"runtime-circuit-open",hint:"The circuit is open. Wait for it to half-open or fall back to a degraded path.",message:e=>`CircuitBreakerOpenError: Circuit ${e.circuitName} is ${e.state??"OPEN"}${e.retryAfterMs?`, retry after ${Math.ceil(e.retryAfterMs/1e3)}s`:""}`}){},ge=class extends K("ValidationError",{message:e=>`ValidationError: Invalid ${e.field} - ${e.reason}`}){},xe=class extends K("NotFoundError",{message:e=>e.id?`NotFoundError: ${e.resource} with id ${e.id} not found`:`NotFoundError: ${e.resource} not found`}){},Ce=class extends K("UnauthorizedError",{message:e=>e.reason?`UnauthorizedError: ${e.reason}`:e.action&&e.resource?`UnauthorizedError: Not authorized to ${e.action} ${e.resource}`:"UnauthorizedError: Access denied"}){},he=class extends K("NetworkError",{message:e=>e.url?`NetworkError: ${e.reason} (${e.url})`:`NetworkError: ${e.reason}`}){},be=class extends K("CompensationError",{slug:"runtime-saga-compensation",hint:"A saga compensation step failed. Inspect compensationError and ensure compensation is idempotent.",message:e=>`CompensationError: Failed to compensate step ${e.step}`}){},se=class extends K("UnexpectedError",{slug:"runtime-unexpected",hint:"An unexpected exception escaped a step. Inspect cause; consider returning a typed Result instead of throwing.",message:e=>`UnexpectedError: ${e.cause instanceof Error?e.cause.message:String(e.cause??"unknown")}`}){};function Ae(n){return{ok:!0,value:n}}var je=n=>typeof n=="object"&&n!==null&&"ok"in n&&typeof n.ok=="boolean"&&(n.ok?"value"in n:"error"in n),Se=(n,e)=>{let p={},k=new Map;for(let A of Object.keys(n)){let E=n[A];typeof E=="function"&&(p[A]=(...R)=>{let P=(k.get(A)??0)+1;k.set(A,P);let M=P===1?A:`${A}#${P}`;return e(M,async()=>{let N=await E(...R);return je(N)?N:Ae(N)})})}return p};function Fe(n){let e=n.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);if(!e)return;let p=parseFloat(e[1]),k=e[2].toLowerCase();return{_tag:"Duration",millis:p*({ms:1,s:1e3,m:6e4,h:36e5,d:864e5}[k]??1)}}function Be(n){return new se({cause:n})}function $(n){return{ok:!0,value:n}}function U(n,e){let p=e?.cause;return{ok:!1,error:n,...p!==void 0?{cause:p}:{}}}function Le(n){if(n==null)return"unknown";if(typeof n=="string")return n.trim()||"unknown";if(typeof n=="object"){let e=n;if(typeof e._tag=="string"){let p=e._tag.trim();if(p)return p}if(typeof e.tag=="string"){let p=e.tag.trim();if(p)return p}if(typeof e.code=="string"){let p=e.code.trim();if(p)return p}else if(typeof e.code=="number")return String(e.code);if(n instanceof Error&&n.name){let p=n.name.trim();if(p)return p}}return"unknown"}function Ve(n,e){if(!(!e||!n))return e[n]}function $e(n){let{intent:e,domain:p,owner:k,tags:A,stateChanges:E,emits:R,calls:P}=n;if(!e&&!p&&!k&&!A?.length&&!E?.length&&!R?.length&&!P?.length)return;let M={};return e&&(M.intent=e),p&&(M.domain=p),k&&(M.owner=k),A?.length&&(M.tags=A),E?.length&&(M.stateChanges=E),R?.length&&(M.emits=R),P?.length&&(M.calls=P),M}function L(n,e,p,k,A){let E=Le(n),R=Ve(E,e),P={tag:E,origin:p};return R!==void 0&&(P.classification=R),k!==void 0&&(P.attempt=k),A!==void 0&&(P.cumulativeDurationMs=A),P}var ee=Symbol.for("step_timeout_marker");function Pe(n){return typeof n!="object"||n===null?!1:n.type==="STEP_TIMEOUT"?!0:ee in n}function We(n){if(!(typeof n!="object"||n===null)){if(n.type==="STEP_TIMEOUT"){let e=n;return{timeoutMs:e.timeoutMs,stepName:e.stepName,stepKey:e.stepKey,attempt:e.attempt}}if(ee in n)return n[ee]}}var _e=Symbol("early-exit");function He(n,e){return{[_e]:!0,error:n,meta:e}}function qe(n){return typeof n=="object"&&n!==null&&n[_e]===!0}var Me=Symbol("mapper-exception");function Z(n){return{[Me]:!0,thrown:n}}function Ye(n){return typeof n=="object"&&n!==null&&n[Me]===!0}function Ee(n,e){let{backoff:p,initialDelay:k,maxDelay:A,jitter:E}=e,R;switch(p){case"fixed":R=k;break;case"linear":R=k*n;break;case"exponential":R=k*Math.pow(2,n-1);break}if(R=Math.min(R,A),E){let P=R*.25*Math.random();R=R+P}return Math.floor(R)}function de(n){return new Promise(e=>setTimeout(e,n))}var ve=Symbol("timeout"),ae=Symbol("timeout-option");function ze(n){return typeof n=="object"&&n!==null&&n[ae]===!0}async function Je(n,e,p,k){let A=new AbortController,E=e.onTimeout??"error",R=()=>typeof E=="function"?E({name:p.name,key:p.key,ms:e.ms}):e.error??{type:"STEP_TIMEOUT",stepName:p.name,stepKey:p.key,timeoutMs:e.ms,attempt:p.attempt},P;k?.aborted&&A.abort(k.reason);let M;k&&!k.aborted&&(M=()=>A.abort(k.reason),k.addEventListener("abort",M,{once:!0}));let N=new Promise((D,s)=>{P=setTimeout(()=>{if(E!=="disconnect"&&A.abort(),E==="option"){s({[ae]:!0,ms:e.ms});return}s({[ve]:!0,error:R()})},e.ms)}),v;e.signal?v=Promise.resolve(n(A.signal)):v=Promise.resolve(n());try{return await Promise.race([v,N])}catch(D){if(typeof D=="object"&&D!==null&&D[ae]===!0)throw{[ae]:!0,ms:e.ms};if(typeof D=="object"&&D!==null&&D[ve]===!0){E==="disconnect"&&v.catch(()=>{});let s=D.error;if(typeof s=="object"&&s!==null&&s.type!=="STEP_TIMEOUT"){let j={timeoutMs:e.ms,stepName:p.name,stepKey:p.key,attempt:p.attempt};ee in s?s[ee]=j:Object.defineProperty(s,ee,{value:j,enumerable:!1,writable:!0,configurable:!1})}throw s}throw D}finally{clearTimeout(P),M&&k&&k.removeEventListener("abort",M)}}var Q={backoff:"exponential",initialDelay:100,maxDelay:3e4,jitter:!0,shouldRetry:()=>!0,onRetry:()=>{}};async function me(n,e,p){if(typeof n!="function"){let l=n,F=e;if(typeof F!="function")throw new TypeError("[awaitly] run(deps, fn) requires a callback as the second argument. Example: run({ getUser }, async (s) => s.getUser(id))");return me(({step:G})=>F(Se(l,G),{step:G}),p)}let k=n,A=e,{onError:E,onEvent:R,catchUnexpected:P,workflowId:M,workflowName:N,context:v,_workflowSignal:D}=A&&typeof A=="object"?A:{},s=M??crypto.randomUUID(),j=P??Be,B=[],we=0,re=l=>l??`step_${++we}`,i=l=>{let F=l.context!==void 0||v===void 0?l:{...l,context:v},W=N!==void 0&&F.workflowName===void 0?{...F,workflowName:N}:F;if(W.type==="step_success"){let G=W.stepId;for(let oe=B.length-1;oe>=0;oe--){let V=B[oe];if(V.type==="race"&&!V.winnerId){V.winnerId=G;break}}}R?.(W,v)},I=He,J=l=>qe(l),q=(l,F)=>l,Ue=l=>typeof l=="function"?!1:!!(l&&typeof l=="object"&&"ok"in l||l&&typeof l=="object"&&"then"in l&&typeof l.then=="function");try{let F=function(a){let d={};for(let[t,o]of Object.entries(a))if(typeof o=="function")d[t]=o;else if(o&&typeof o=="object"&&"fn"in o)d[t]=o.fn;else throw new TypeError(`step.all: operation "${t}" must be a function or { fn, errors? } object`);return d},W=function(a,d){let t=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let o=performance.now(),r=!1;B.push({scopeId:t,type:"parallel"});let u=()=>{if(r)return;r=!0;let c=B.findIndex(m=>m.scopeId===t);c!==-1&&B.splice(c,1),i({type:"scope_end",workflowId:s,scopeId:t,ts:Date.now(),durationMs:performance.now()-o})};i({type:"scope_start",workflowId:s,scopeId:t,scopeType:"parallel",name:a,ts:Date.now()});try{let c=await d();if(u(),!c.ok)throw E?.(c.error,a,v),I(c.error,{origin:"result",resultCause:c.cause});return c.value}catch(c){throw u(),c}})()},G=function(a,d){let t=Object.keys(a),o=d.name??`Parallel(${t.join(", ")})`,r=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let u=performance.now(),c=!1;B.push({scopeId:r,type:"parallel"});let m=()=>{if(c)return;c=!0;let w=B.findIndex(y=>y.scopeId===r);w!==-1&&B.splice(w,1),i({type:"scope_end",workflowId:s,scopeId:r,ts:Date.now(),durationMs:performance.now()-u})};i({type:"scope_start",workflowId:s,scopeId:r,scopeType:"parallel",name:o,ts:Date.now()});try{let w=await new Promise(T=>{if(t.length===0){T([]);return}let b=!1,_=t.length,g=new Array(t.length);for(let O=0;O<t.length;O++){let x=t[O],h=O;Promise.resolve(a[x]()).catch(C=>U({type:"PROMISE_REJECTED",cause:C},{cause:{type:"PROMISE_REJECTION",reason:C}})).then(C=>{if(!b){if(!C.ok){b=!0,T([{key:x,result:C}]);return}g[h]={key:x,result:C},_--,_===0&&T(g)}})}});m();let y={};for(let{key:T,result:b}of w){if(!b.ok)throw E?.(b.error,T,v),I(b.error,{origin:"result",resultCause:b.cause});y[T]=b.value}return y}catch(w){throw m(),w}})()};var Xe=F,Ze=W,Qe=G;let l=(a,d,t)=>(async()=>{if(typeof a!="string"||a.length===0)throw new Error('[awaitly] step() requires an explicit string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))');let o=t??{},r=$e(o),u=a,c=o.key??a,m=o.key??a,{description:w,retry:y,timeout:T}=o,b=re(c),_=R,g=_?performance.now():0,x=Ue(d)?()=>d:d,C={attempts:Math.max(1,y?.attempts??1),backoff:y?.backoff??Q.backoff,initialDelay:y?.initialDelay??Q.initialDelay,maxDelay:y?.maxDelay??Q.maxDelay,jitter:y?.jitter??Q.jitter,shouldRetry:y?.shouldRetry??Q.shouldRetry,onRetry:y?.onRetry??Q.onRetry};R&&i({type:"step_start",workflowId:s,stepId:b,stepKey:c,name:u,description:w,ts:Date.now(),...r&&{metadata:r}});let X;for(let S=1;S<=C.attempts;S++){let De=_?performance.now():0;try{let f;if(T?f=await Je(x,T,{name:u,key:c,attempt:S},D):f=await x(),f.ok){let z=performance.now()-g;return i({type:"step_success",workflowId:s,stepId:b,stepKey:c,name:u,description:w,ts:Date.now(),durationMs:z,...r&&{metadata:r}}),m&&i({type:"step_complete",workflowId:s,stepKey:m,name:u,description:w,ts:Date.now(),durationMs:z,result:f,...r&&{metadata:r}}),f.value}if(X=f,S<C.attempts&&C.shouldRetry(f.error,S)){let z=Ee(S,C);i({type:"step_retry",workflowId:s,stepId:b,stepKey:c,name:u,ts:Date.now(),attempt:S+1,maxAttempts:C.attempts,delayMs:z,error:f.error,...r&&{metadata:r},diagnostics:L(f.error,o.errorMeta,"result",S,performance.now()-g)}),C.onRetry(f.error,S,z),await de(z);continue}C.attempts>1&&i({type:"step_retries_exhausted",workflowId:s,stepId:b,stepKey:c,name:u,ts:Date.now(),durationMs:performance.now()-g,attempts:S,lastError:f.error,...r&&{metadata:r},diagnostics:L(f.error,o.errorMeta,"result",S,performance.now()-g)});break}catch(f){let z=performance.now()-De;if(ze(f)){let H=f.ms;i({type:"step_timeout",workflowId:s,stepId:b,stepKey:c,name:u,ts:Date.now(),timeoutMs:H,attempt:S,...r&&{metadata:r},diagnostics:L(f,o.errorMeta,"timeout",S)}),i({type:"step_success",workflowId:s,stepId:b,stepKey:c,name:u,description:w,ts:Date.now(),durationMs:performance.now()-g,...r&&{metadata:r}}),m&&i({type:"step_complete",workflowId:s,stepKey:m,name:u,description:w,ts:Date.now(),durationMs:performance.now()-g,result:$(void 0),...r&&{metadata:r}});return}if(J(f))throw i({type:"step_aborted",workflowId:s,stepId:b,stepKey:c,name:u,description:w,ts:Date.now(),durationMs:z,...r&&{metadata:r}}),f;if(Pe(f)){let H=We(f),Ke=T?.ms??H?.timeoutMs??0;if(i({type:"step_timeout",workflowId:s,stepId:b,stepKey:c,name:u,ts:Date.now(),timeoutMs:Ke,attempt:S,...r&&{metadata:r},diagnostics:L(f,o.errorMeta,"timeout",S)}),S<C.attempts&&C.shouldRetry(f,S)){let pe=Ee(S,C);i({type:"step_retry",workflowId:s,stepId:b,stepKey:c,name:u,ts:Date.now(),attempt:S+1,maxAttempts:C.attempts,delayMs:pe,error:f,...r&&{metadata:r},diagnostics:L(f,o.errorMeta,"timeout",S,performance.now()-g)}),C.onRetry(f,S,pe),await de(pe);continue}C.attempts>1&&i({type:"step_retries_exhausted",workflowId:s,stepId:b,stepKey:c,name:u,ts:Date.now(),durationMs:performance.now()-g,attempts:S,lastError:f,...r&&{metadata:r},diagnostics:L(f,o.errorMeta,"timeout",S,performance.now()-g)});let le=performance.now()-g;throw i({type:"step_error",workflowId:s,stepId:b,stepKey:c,name:u,description:w,ts:Date.now(),durationMs:le,error:f,...r&&{metadata:r},diagnostics:L(f,o.errorMeta,"timeout",S,le)}),m&&i({type:"step_complete",workflowId:s,stepKey:m,name:u,description:w,ts:Date.now(),durationMs:le,result:U(f,{cause:f}),meta:{origin:"throw",thrown:f},...r&&{metadata:r}}),E?.(f,u,v),I(f,{origin:"throw",thrown:f})}if(S<C.attempts&&C.shouldRetry(f,S)){let H=Ee(S,C);i({type:"step_retry",workflowId:s,stepId:b,stepKey:c,name:u,ts:Date.now(),attempt:S+1,maxAttempts:C.attempts,delayMs:H,error:f,...r&&{metadata:r},diagnostics:L(f,o.errorMeta,"throw",S,performance.now()-g)}),C.onRetry(f,S,H),await de(H);continue}C.attempts>1&&!Pe(f)&&i({type:"step_retries_exhausted",workflowId:s,stepId:b,stepKey:c,name:u,ts:Date.now(),durationMs:performance.now()-g,attempts:S,lastError:f,...r&&{metadata:r},diagnostics:L(f,o.errorMeta,"throw",S,performance.now()-g)});let ce=performance.now()-g,ne;try{ne=j(f)}catch(H){throw Z(H)}throw i({type:"step_error",workflowId:s,stepId:b,stepKey:c,name:u,description:w,ts:Date.now(),durationMs:ce,error:ne,...r&&{metadata:r},diagnostics:L(f,o.errorMeta,"throw",S,ce)}),m&&i({type:"step_complete",workflowId:s,stepKey:m,name:u,description:w,ts:Date.now(),durationMs:ce,result:U(ne,{cause:f}),meta:{origin:"throw",thrown:f},...r&&{metadata:r}}),E?.(ne,u,v),I(ne,{origin:"throw",thrown:f})}}let Y=X,ue=performance.now()-g,ie=q(Y.error,{origin:"result",resultCause:Y.cause});throw i({type:"step_error",workflowId:s,stepId:b,stepKey:c,name:u,description:w,ts:Date.now(),durationMs:ue,error:ie,...r&&{metadata:r},diagnostics:L(Y.error,o.errorMeta,"result",C.attempts,ue)}),m&&i({type:"step_complete",workflowId:s,stepKey:m,name:u,description:w,ts:Date.now(),durationMs:ue,result:Y,meta:{origin:"result",resultCause:Y.cause},...r&&{metadata:r}}),E?.(ie,u,v),I(ie,{origin:"result",resultCause:Y.cause})})();l.try=(a,d,t)=>{if(typeof a!="string"||a.length===0)throw new Error('[awaitly] step.try() requires an explicit string ID as the first argument. Example: step.try("parse", () => JSON.parse(str), { error: "PARSE_ERROR" })');let o="error"in t?()=>t.error:t.onError;if(t.retry||t.timeout)return l.retry(a,async()=>{try{return $(await d())}catch(w){return U(o(w),{cause:w})}},{attempts:t.retry?.attempts??1,...t.retry??{},key:t.key,timeout:t.timeout});let r=t.key??a,u=a,c=a,m=R;return(async()=>{let w=m?performance.now():0;R&&i({type:"step_start",workflowId:s,stepId:c,stepKey:r,name:u,ts:Date.now()});try{let y=await d(),T=performance.now()-w;return i({type:"step_success",workflowId:s,stepId:c,stepKey:r,name:u,ts:Date.now(),durationMs:T}),r&&i({type:"step_complete",workflowId:s,stepKey:r,name:u,ts:Date.now(),durationMs:T,result:$(y)}),y}catch(y){let T=o(y),b=performance.now()-w,_=q(T,{origin:"throw",thrown:y});throw i({type:"step_error",workflowId:s,stepId:c,stepKey:r,name:u,ts:Date.now(),durationMs:b,error:_}),r&&i({type:"step_complete",workflowId:s,stepKey:r,name:u,ts:Date.now(),durationMs:b,result:U(T,{cause:y}),meta:{origin:"throw",thrown:y}}),E?.(_,u,v),I(_,{origin:"throw",thrown:y})}})()},l.fromResult=(a,d,t)=>{if(typeof a!="string"||a.length===0)throw new Error('[awaitly] step.fromResult() requires an explicit string ID as the first argument. Example: step.fromResult("callProvider", () => callProvider(input), { onError: (e) => ({ type: "FAILED" }) })');let o=t.key??a,r=a,u=a,c="error"in t?()=>t.error:t.onError,m=R;return(async()=>{let w=m?performance.now():0;R&&i({type:"step_start",workflowId:s,stepId:u,stepKey:o,name:r,ts:Date.now()});let y=await d();if(y.ok){let T=performance.now()-w;return i({type:"step_success",workflowId:s,stepId:u,stepKey:o,name:r,ts:Date.now(),durationMs:T}),o&&i({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:T,result:$(y.value)}),y.value}else{let T=c(y.error),b=performance.now()-w,_=q(T,{origin:"result",resultCause:y.error});throw i({type:"step_error",workflowId:s,stepId:u,stepKey:o,name:r,ts:Date.now(),durationMs:b,error:_}),o&&i({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:b,result:U(T,{cause:y.error}),meta:{origin:"result",resultCause:y.error}}),E?.(_,r,v),I(_,{origin:"result",resultCause:y.error})}})()},l.fromNullable=(a,d,t,o)=>{if(typeof a!="string"||a.length===0)throw new Error('[awaitly] step.fromNullable() requires an explicit string ID as the first argument. Example: step.fromNullable("getUser", () => db.find(id), () => ({ type: "NOT_FOUND" }))');return l(a,async()=>{let r=await d();return r!=null?$(r):U(t())},o)},l.retry=(a,d,t)=>{if(typeof a!="string"||a.length===0)throw new Error('[awaitly] step.retry() requires an explicit string ID as the first argument. Example: step.retry("fetchData", () => fetchData(), { attempts: 3 })');return l(a,d,{key:t.key??a,retry:{attempts:t.attempts,backoff:t.backoff,initialDelay:t.initialDelay,maxDelay:t.maxDelay,jitter:t.jitter,shouldRetry:t.shouldRetry,onRetry:t.onRetry},timeout:t.timeout})},l.withTimeout=(a,d,t)=>{if(typeof a!="string"||a.length===0)throw new Error('[awaitly] step.withTimeout() requires an explicit string ID as the first argument. Example: step.withTimeout("slowOp", () => slowOp(), { ms: 5000 })');return l(a,d,{key:t.key??a,timeout:t})},l.sleep=(a,d,t)=>{if(typeof a!="string"||a.length===0)throw new Error('[awaitly] step.sleep() requires an explicit string ID as the first argument. Example: step.sleep("delay", "5s")');let o=typeof d=="string"?Fe(d):d;if(!o)throw new Error(`step.sleep: invalid duration '${d}'`);let r=o.millis,u=t?.signal;return l(a,async()=>{if(D?.aborted||u?.aborted){let c=new Error("Sleep aborted");throw c.name="AbortError",c}return new Promise((c,m)=>{let w={timeoutId:void 0},y=()=>{w.timeoutId&&clearTimeout(w.timeoutId);let T=new Error("Sleep aborted");T.name="AbortError",m(T)};D?.addEventListener("abort",y,{once:!0}),u?.addEventListener("abort",y,{once:!0}),w.timeoutId=setTimeout(()=>{D?.removeEventListener("abort",y),u?.removeEventListener("abort",y),c($(void 0))},r)})},{key:t?.key??a,description:t?.description})},l.all=((...a)=>{if(typeof a[0]!="string")throw new TypeError("step.all(name, ...): first argument must be a string (step name). Example: step.all('Fetch data', { user: () => fetchUser(), posts: () => fetchPosts() })");let d=a[0],t=a[1];if(typeof t=="function")return W(d,t);if(t&&typeof t=="object"&&!Array.isArray(t)){let r=F(t);return G(r,{name:d})}throw new TypeError("step.all(name, ...): second argument must be a function (array form) or an object of operations (object form).")}),l.race=(a,d)=>{let t=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let o=performance.now(),r=!1,u={scopeId:t,type:"race",winnerId:void 0};B.push(u);let c=()=>{if(r)return;r=!0;let m=B.findIndex(w=>w.scopeId===t);m!==-1&&B.splice(m,1),i({type:"scope_end",workflowId:s,scopeId:t,ts:Date.now(),durationMs:performance.now()-o,winnerId:u.winnerId})};i({type:"scope_start",workflowId:s,scopeId:t,scopeType:"race",name:a,ts:Date.now()});try{let m=await d();if(c(),!m.ok)throw E?.(m.error,a,v),I(m.error,{origin:"result",resultCause:m.cause});return m.value}catch(m){throw c(),m}})()},l.if=(a,d,t)=>t(),l.label=l.if,l.branch=async(a,d)=>{let{condition:t,then:o,else:r}=d;if(t())return await o();if(r)return await r()},l.arm=(a,d)=>({fn:a,errors:d}),l.forEach=async(a,d,t)=>{let o=[],r=t.maxIterations,u=0,c="run"in t,m=Symbol.asyncIterator in d?d:(async function*(){yield*d})();for await(let w of m){if(r!==void 0&&u>=r)break;let y;c?y=await t.run(w,u):y=await t.item.handler(w,u,l),o.push(y),u++}return o},l.item=a=>({__forEachItemHandler:!0,handler:a}),l.dep=(a,d)=>d,l.workflow=(a,d,t)=>l(a,d,t),l.map=async(a,d,t,o)=>{let r=o?.concurrency??d.length;return l(a,()=>r>=d.length?Oe(d.map((u,c)=>t(u,c))):(async()=>{let u=[];for(let c=0;c<d.length;c+=r){let m=d.slice(c,c+r),w=await Oe(m.map((y,T)=>t(y,c+T)));if(!w.ok)return w;u.push(...w.value)}return $(u)})(),{key:o?.key})},l.withFallback=(a,d,t)=>{if(typeof a!="string"||a.length===0)throw new Error('[awaitly] step.withFallback() requires an explicit string ID as the first argument. Example: step.withFallback("getUser", () => fetchUser(id), { fallback: () => fetchFromCache(id) })');let o=t.key??a,r=a,u=re(o),c=R;return(async()=>{let m=c?performance.now():0;R&&i({type:"step_start",workflowId:s,stepId:u,stepKey:o,name:r,ts:Date.now()});let w;try{w=await d()}catch(g){if(J(g))throw i({type:"step_aborted",workflowId:s,stepId:u,stepKey:o,name:r,ts:Date.now(),durationMs:performance.now()-m}),g;let O;try{O=j(g)}catch(h){throw Z(h)}if(t.on!==void 0&&t.on!==O){let h=performance.now()-m;throw i({type:"step_error",workflowId:s,stepId:u,stepKey:o,name:r,ts:Date.now(),durationMs:h,error:O}),o&&i({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:h,result:U(O,{cause:g}),meta:{origin:"throw",thrown:g}}),E?.(O,r,v),I(O,{origin:"throw",thrown:g})}let x;try{x=await t.fallback()}catch(h){if(J(h))throw i({type:"step_aborted",workflowId:s,stepId:u,stepKey:o,name:r,ts:Date.now(),durationMs:performance.now()-m}),h;let C;try{C=j(h)}catch(Y){throw Z(Y)}let X=performance.now()-m;throw i({type:"step_error",workflowId:s,stepId:u,stepKey:o,name:r,ts:Date.now(),durationMs:X,error:C}),o&&i({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:X,result:U(C,{cause:h}),meta:{origin:"throw",thrown:h}}),E?.(C,r,v),I(C,{origin:"throw",thrown:h})}if(x.ok){let h=performance.now()-m;return i({type:"step_success",workflowId:s,stepId:u,stepKey:o,name:r,ts:Date.now(),durationMs:h}),o&&i({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:h,result:x,meta:{origin:"fallback",fallbackUsed:!0,fallbackReason:String(O)}}),x.value}else{let h=performance.now()-m,C=q(x.error,{origin:"result",resultCause:x.cause});throw i({type:"step_error",workflowId:s,stepId:u,stepKey:o,name:r,ts:Date.now(),durationMs:h,error:C}),o&&i({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:h,result:x,meta:{origin:"result",resultCause:x.cause}}),E?.(C,r,v),I(C,{origin:"result",resultCause:x.cause})}}if(w.ok){let g=performance.now()-m;return i({type:"step_success",workflowId:s,stepId:u,stepKey:o,name:r,ts:Date.now(),durationMs:g}),o&&i({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:g,result:w}),w.value}let y=w.error;if(t.on!==void 0&&t.on!==y){let g=performance.now()-m,O=q(y,{origin:"result",resultCause:w.cause});throw i({type:"step_error",workflowId:s,stepId:u,stepKey:o,name:r,ts:Date.now(),durationMs:g,error:O}),o&&i({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:g,result:w,meta:{origin:"result",resultCause:w.cause}}),E?.(O,r,v),I(O,{origin:"result",resultCause:w.cause})}let T;try{T=await t.fallback()}catch(g){if(J(g))throw i({type:"step_aborted",workflowId:s,stepId:u,stepKey:o,name:r,ts:Date.now(),durationMs:performance.now()-m}),g;let O;try{O=j(g)}catch(h){throw Z(h)}let x=performance.now()-m;throw i({type:"step_error",workflowId:s,stepId:u,stepKey:o,name:r,ts:Date.now(),durationMs:x,error:O}),o&&i({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:x,result:U(O,{cause:g}),meta:{origin:"throw",thrown:g}}),E?.(O,r,v),I(O,{origin:"throw",thrown:g})}if(T.ok){let g=performance.now()-m;return i({type:"step_success",workflowId:s,stepId:u,stepKey:o,name:r,ts:Date.now(),durationMs:g}),o&&i({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:g,result:T,meta:{origin:"fallback",fallbackUsed:!0,fallbackReason:String(y)}}),T.value}let b=performance.now()-m,_=q(T.error,{origin:"result",resultCause:T.cause});throw i({type:"step_error",workflowId:s,stepId:u,stepKey:o,name:r,ts:Date.now(),durationMs:b,error:_}),o&&i({type:"step_complete",workflowId:s,stepKey:o,name:r,ts:Date.now(),durationMs:b,result:T,meta:{origin:"result",resultCause:T.cause}}),E?.(_,r,v),I(_,{origin:"result",resultCause:T.cause})})()},l.withResource=(a,d)=>{if(typeof a!="string"||a.length===0)throw new Error('[awaitly] step.withResource() requires an explicit string ID as the first argument. Example: step.withResource("useDb", { acquire: () => connect(), use: (db) => query(db), release: (db) => db.close() })');let t=a,o=a,r=re(t),u=R;return(async()=>{let c=u?performance.now():0;R&&i({type:"step_start",workflowId:s,stepId:r,stepKey:t,name:o,ts:Date.now()});let m;try{m=await d.acquire()}catch(x){if(J(x))throw i({type:"step_aborted",workflowId:s,stepId:r,stepKey:t,name:o,ts:Date.now(),durationMs:performance.now()-c}),x;let h;try{h=j(x)}catch(X){throw Z(X)}let C=performance.now()-c;throw i({type:"step_error",workflowId:s,stepId:r,stepKey:t,name:o,ts:Date.now(),durationMs:C,error:h}),t&&i({type:"step_complete",workflowId:s,stepKey:t,name:o,ts:Date.now(),durationMs:C,result:U(h,{cause:x}),meta:{origin:"throw",thrown:x}}),E?.(h,o,v),I(h,{origin:"throw",thrown:x})}if(!m.ok){let x=performance.now()-c,h=q(m.error,{origin:"result",resultCause:m.cause});throw i({type:"step_error",workflowId:s,stepId:r,stepKey:t,name:o,ts:Date.now(),durationMs:x,error:h}),t&&i({type:"step_complete",workflowId:s,stepKey:t,name:o,ts:Date.now(),durationMs:x,result:m,meta:{origin:"result",resultCause:m.cause}}),E?.(h,o,v),I(h,{origin:"result",resultCause:m.cause})}let w=m.value,y,T,b=!1;try{y=await d.use(w)}catch(x){if(J(x)){try{await d.release(w)}catch(h){console.warn(`[awaitly] step.withResource("${a}"): release threw after earlyExit:`,h)}throw x}T=x,b=!0}try{await d.release(w)}catch(x){console.warn(`[awaitly] step.withResource("${a}"): release threw:`,x)}if(b){let x;try{x=j(T)}catch(C){throw Z(C)}let h=performance.now()-c;throw i({type:"step_error",workflowId:s,stepId:r,stepKey:t,name:o,ts:Date.now(),durationMs:h,error:x}),t&&i({type:"step_complete",workflowId:s,stepKey:t,name:o,ts:Date.now(),durationMs:h,result:U(x,{cause:T}),meta:{origin:"throw",thrown:T}}),E?.(x,o,v),I(x,{origin:"throw",thrown:T})}let _=y;if(_.ok){let x=performance.now()-c;return i({type:"step_success",workflowId:s,stepId:r,stepKey:t,name:o,ts:Date.now(),durationMs:x}),t&&i({type:"step_complete",workflowId:s,stepKey:t,name:o,ts:Date.now(),durationMs:x,result:_}),_.value}let g=performance.now()-c,O=q(_.error,{origin:"result",resultCause:_.cause});throw i({type:"step_error",workflowId:s,stepId:r,stepKey:t,name:o,ts:Date.now(),durationMs:g,error:O}),t&&i({type:"step_complete",workflowId:s,stepKey:t,name:o,ts:Date.now(),durationMs:g,result:_,meta:{origin:"result",resultCause:_.cause}}),E?.(O,o,v),I(O,{origin:"result",resultCause:_.cause})})()};let V=await k({step:l});if(process.env.NODE_ENV!=="production"&&V!==null&&typeof V=="object"&&"ok"in V&&typeof V.ok=="boolean"){let a=V;(a.ok===!0&&"value"in a||a.ok===!1&&"error"in a)&&console.warn(`awaitly: Workflow executor returned a Result-like object. Return raw values, not ok() or err().
|
|
2
|
-
|
|
3
|
-
Incorrect: return ok({ data });
|
|
4
|
-
Correct: return { data };
|
|
5
|
-
|
|
6
|
-
See: https://jagreehal.github.io/awaitly/guides/troubleshooting/#returning-ok-from-workflow-executor-double-wrapping`)}return $(V)}catch(l){if(Ye(l))throw l.thrown;if(J(l)){let W=l.meta.origin==="throw"?l.meta.thrown:l.meta.origin==="result"?l.meta.resultCause:void 0;return U(l.error,{cause:W})}let F=j(l);return E?.(F,"unexpected",v),U(F,{cause:l})}}me.strict=(n,e)=>me(n,e);async function Oe(n){return n.length===0?$([]):new Promise(e=>{let p=!1,k=n.length,A=new Array(n.length);for(let E=0;E<n.length;E++){let R=E;Promise.resolve(n[R]).catch(P=>U({type:"PROMISE_REJECTED",cause:P},{cause:{type:"PROMISE_REJECTION",reason:P}})).then(P=>{if(!p){if(!P.ok){p=!0,e(P);return}A[R]=P.value,k--,k===0&&e($(A))}})}})}function Ie(n){return typeof n=="object"&&n!==null&&n.type==="RESOURCE_CLEANUP_ERROR"}function Ge(){let n=[];return{add:e=>(n.push(e),e.value),close:async()=>{let e=[];for(let p=n.length-1;p>=0;p--)try{await n[p].close()}catch(k){e.push(k)}if(n.length=0,e.length>0)throw{type:"RESOURCE_CLEANUP_ERROR",errors:e}},has:e=>n.includes(e),size:()=>n.length}}async function mr(n){let e=Ge(),p;try{p=await n(e)}catch(k){try{await e.close()}catch(A){if(Ie(A))return U({...A,originalResult:{thrown:k}})}throw k}try{await e.close()}catch(k){if(Ie(k))return U({...k,originalResult:p});throw k}return p}async function wr(n,e){let p=await n();return{value:p,close:async()=>{await e(p)}}}export{wr as createResource,Ge as createResourceScope,Ie as isResourceCleanupError,mr as withScope};
|
|
7
|
-
//# sourceMappingURL=resource.js.map
|