awaitly 1.34.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 +35 -5
- package/dist/result.d.ts +35 -5
- 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-D2MmJFj9.d.cts → types-B8NfNRGX.d.ts} +1152 -1499
- package/dist/{run-entry-Dduz-is2.d.ts → types-BZ2f4MRR.d.cts} +1152 -1499
- 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 +13 -178
- 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-COl5oFnR.d.cts +0 -15
- package/dist/di-CyDj_JyZ.d.ts +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-BodHXLzX.d.cts +0 -72
- package/dist/guards-CeWoQ8fn.d.ts +0 -72
- package/dist/hitl-BPE_1UiM.d.cts +0 -468
- package/dist/hitl-byp570uC.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-BYT3amEz.d.ts +0 -417
- package/dist/index-C_ak66jy.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-DOMx3woy.d.ts +0 -822
- package/dist/persistence-entry-ymCA4iDu.d.cts +0 -822
- 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-DQmzO9f4.d.ts +0 -323
- package/dist/types-qBUOYi-4.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-D2MmJFj9.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-Dduz-is2.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 Me={"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 me(n){return`https://jagreehal.github.io/awaitly/rules/#${n}`}var ze=Object.keys(Me);var ee=class extends Error{_tag};function K(n,e){return class extends ee{_tag=n;constructor(i,y){let v=e?.message?e.message(i??{}):n;if(super(v),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:me(e.slug),enumerable:!0,writable:!1,configurable:!1})}if(Object.setPrototypeOf(this,new.target.prototype),i&&typeof i=="object"){let h;if(e?.slug!==void 0){let{_tag:a,name:U,message:M,stack:N,code:$,hint:c,docsUrl:I,...V}=i;h=V}else{let{_tag:a,name:U,message:M,stack:N,...$}=i;h=$}let S=Object.prototype.hasOwnProperty.call(h,"cause"),w=S?h.cause:void 0;S&&delete h.cause;let O=y?.cause!==void 0;if(S&&O)throw new TypeError("TaggedError: cannot provide 'cause' in props when also setting ErrorOptions.cause");Object.assign(this,h),S&&(this.cause=w),O&&(this.cause=y?.cause)}else y?.cause!==void 0&&(this.cause=y.cause)}}}Object.defineProperty(K,Symbol.hasInstance,{value:n=>n instanceof ee});(v=>{function n(h){return h instanceof Error}v.isError=n;function e(h){return h instanceof ee}v.isTaggedError=e;function i(h,S){let w=h._tag,O=S[w];return O(h)}v.match=i;function y(h,S,w){let O=h._tag,a=S[O];return a?a(h):w(h)}v.matchPartial=y})(K||={});var de=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`}){},Ee=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`}){},ye=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`:""}`}){},we=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`:""}`}){},fe=class extends K("ValidationError",{message:e=>`ValidationError: Invalid ${e.field} - ${e.reason}`}){},Te=class extends K("NotFoundError",{message:e=>e.id?`NotFoundError: ${e.resource} with id ${e.id} not found`:`NotFoundError: ${e.resource} not found`}){},ge=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"}){},ke=class extends K("NetworkError",{message:e=>e.url?`NetworkError: ${e.reason} (${e.url})`:`NetworkError: ${e.reason}`}){},Re=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}`}){},ne=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 Ie(n){let e=n.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);if(!e)return;let i=parseFloat(e[1]),y=e[2].toLowerCase();return{_tag:"Duration",millis:i*({ms:1,s:1e3,m:6e4,h:36e5,d:864e5}[y]??1)}}function De(n){return new ne({cause:n})}function B(n){return{ok:!0,value:n}}function D(n,e){let i=e?.cause;return{ok:!1,error:n,...i!==void 0?{cause:i}:{}}}function Ue(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 i=e._tag.trim();if(i)return i}if(typeof e.tag=="string"){let i=e.tag.trim();if(i)return i}if(typeof e.code=="string"){let i=e.code.trim();if(i)return i}else if(typeof e.code=="number")return String(e.code);if(n instanceof Error&&n.name){let i=n.name.trim();if(i)return i}}return"unknown"}function Ne(n,e){if(!(!e||!n))return e[n]}function Ke(n){let{intent:e,domain:i,owner:y,tags:v,stateChanges:h,emits:S,calls:w}=n;if(!e&&!i&&!y&&!v?.length&&!h?.length&&!S?.length&&!w?.length)return;let O={};return e&&(O.intent=e),i&&(O.domain=i),y&&(O.owner=y),v?.length&&(O.tags=v),h?.length&&(O.stateChanges=h),S?.length&&(O.emits=S),w?.length&&(O.calls=w),O}function j(n,e,i,y,v){let h=Ue(n),S=Ne(h,e),w={tag:h,origin:i};return S!==void 0&&(w.classification=S),y!==void 0&&(w.attempt=y),v!==void 0&&(w.cumulativeDurationMs=v),w}var Q=Symbol.for("step_timeout_marker");function xe(n){return typeof n!="object"||n===null?!1:n.type==="STEP_TIMEOUT"?!0:Q in n}function je(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(Q in n)return n[Q]}}var Se=Symbol("early-exit");function Fe(n,e){return{[Se]:!0,error:n,meta:e}}function Le(n){return typeof n=="object"&&n!==null&&n[Se]===!0}var Ae=Symbol("mapper-exception");function G(n){return{[Ae]:!0,thrown:n}}function Be(n){return typeof n=="object"&&n!==null&&n[Ae]===!0}function le(n,e){let{backoff:i,initialDelay:y,maxDelay:v,jitter:h}=e,S;switch(i){case"fixed":S=y;break;case"linear":S=y*n;break;case"exponential":S=y*Math.pow(2,n-1);break}if(S=Math.min(S,v),h){let w=S*.25*Math.random();S=S+w}return Math.floor(S)}function pe(n){return new Promise(e=>setTimeout(e,n))}var he=Symbol("timeout"),oe=Symbol("timeout-option");function $e(n){return typeof n=="object"&&n!==null&&n[oe]===!0}async function Ve(n,e,i,y){let v=new AbortController,h=e.onTimeout??"error",S=()=>typeof h=="function"?h({name:i.name,key:i.key,ms:e.ms}):e.error??{type:"STEP_TIMEOUT",stepName:i.name,stepKey:i.key,timeoutMs:e.ms,attempt:i.attempt},w;y?.aborted&&v.abort(y.reason);let O;y&&!y.aborted&&(O=()=>v.abort(y.reason),y.addEventListener("abort",O,{once:!0}));let a=new Promise((M,N)=>{w=setTimeout(()=>{if(h!=="disconnect"&&v.abort(),h==="option"){N({[oe]:!0,ms:e.ms});return}N({[he]:!0,error:S()})},e.ms)}),U;e.signal?U=Promise.resolve(n(v.signal)):U=Promise.resolve(n());try{return await Promise.race([U,a])}catch(M){if(typeof M=="object"&&M!==null&&M[oe]===!0)throw{[oe]:!0,ms:e.ms};if(typeof M=="object"&&M!==null&&M[he]===!0){h==="disconnect"&&U.catch(()=>{});let N=M.error;if(typeof N=="object"&&N!==null&&N.type!=="STEP_TIMEOUT"){let $={timeoutMs:e.ms,stepName:i.name,stepKey:i.key,attempt:i.attempt};Q in N?N[Q]=$:Object.defineProperty(N,Q,{value:$,enumerable:!1,writable:!0,configurable:!1})}throw N}throw M}finally{clearTimeout(w),O&&y&&y.removeEventListener("abort",O)}}var X={backoff:"exponential",initialDelay:100,maxDelay:3e4,jitter:!0,shouldRetry:()=>!0,onRetry:()=>{}};async function Ce(n,e){let{onError:i,onEvent:y,catchUnexpected:v,workflowId:h,workflowName:S,context:w,_workflowSignal:O}=e&&typeof e=="object"?e:{},a=h??crypto.randomUUID(),U=v??De,M=[],N=0,$=p=>p??`step_${++N}`,c=p=>{let F=p.context!==void 0||w===void 0?p:{...p,context:w},q=S!==void 0&&F.workflowName===void 0?{...F,workflowName:S}:F;if(q.type==="step_success"){let te=q.stepId;for(let re=M.length-1;re>=0;re--){let L=M[re];if(L.type==="race"&&!L.winnerId){L.winnerId=te;break}}}y?.(q,w)},I=Fe,V=p=>Le(p),W=(p,F)=>p,Pe=p=>typeof p=="function"?!1:!!(p&&typeof p=="object"&&"ok"in p||p&&typeof p=="object"&&"then"in p&&typeof p.then=="function");try{let F=function(s){let m={};for(let[r,o]of Object.entries(s))if(typeof o=="function")m[r]=o;else if(o&&typeof o=="object"&&"fn"in o)m[r]=o.fn;else throw new TypeError(`step.all: operation "${r}" must be a function or { fn, errors? } object`);return m},q=function(s,m){let r=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let o=performance.now(),t=!1;M.push({scopeId:r,type:"parallel"});let u=()=>{if(t)return;t=!0;let l=M.findIndex(d=>d.scopeId===r);l!==-1&&M.splice(l,1),c({type:"scope_end",workflowId:a,scopeId:r,ts:Date.now(),durationMs:performance.now()-o})};c({type:"scope_start",workflowId:a,scopeId:r,scopeType:"parallel",name:s,ts:Date.now()});try{let l=await m();if(u(),!l.ok)throw i?.(l.error,s,w),I(l.error,{origin:"result",resultCause:l.cause});return l.value}catch(l){throw u(),l}})()},te=function(s,m){let r=Object.keys(s),o=m.name??`Parallel(${r.join(", ")})`,t=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let u=performance.now(),l=!1;M.push({scopeId:t,type:"parallel"});let d=()=>{if(l)return;l=!0;let E=M.findIndex(f=>f.scopeId===t);E!==-1&&M.splice(E,1),c({type:"scope_end",workflowId:a,scopeId:t,ts:Date.now(),durationMs:performance.now()-u})};c({type:"scope_start",workflowId:a,scopeId:t,scopeType:"parallel",name:o,ts:Date.now()});try{let E=await new Promise(g=>{if(r.length===0){g([]);return}let b=!1,P=r.length,k=new Array(r.length);for(let _=0;_<r.length;_++){let R=r[_],C=_;Promise.resolve(s[R]()).catch(x=>D({type:"PROMISE_REJECTED",cause:x},{cause:{type:"PROMISE_REJECTION",reason:x}})).then(x=>{if(!b){if(!x.ok){b=!0,g([{key:R,result:x}]);return}k[C]={key:R,result:x},P--,P===0&&g(k)}})}});d();let f={};for(let{key:g,result:b}of E){if(!b.ok)throw i?.(b.error,g,w),I(b.error,{origin:"result",resultCause:b.cause});f[g]=b.value}return f}catch(E){throw d(),E}})()};var We=F,qe=q,Ye=te;let p=(s,m,r)=>(async()=>{if(typeof s!="string"||s.length===0)throw new Error('[awaitly] step() requires an explicit string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))');let o=r??{},t=Ke(o),u=s,l=o.key??s,d=o.key??s,{description:E,retry:f,timeout:g}=o,b=$(l),P=y,k=P?performance.now():0,R=Pe(m)?()=>m:m,x={attempts:Math.max(1,f?.attempts??1),backoff:f?.backoff??X.backoff,initialDelay:f?.initialDelay??X.initialDelay,maxDelay:f?.maxDelay??X.maxDelay,jitter:f?.jitter??X.jitter,shouldRetry:f?.shouldRetry??X.shouldRetry,onRetry:f?.onRetry??X.onRetry};y&&c({type:"step_start",workflowId:a,stepId:b,stepKey:l,name:u,description:E,ts:Date.now(),...t&&{metadata:t}});let J;for(let A=1;A<=x.attempts;A++){let ve=P?performance.now():0;try{let T;if(g?T=await Ve(R,g,{name:u,key:l,attempt:A},O):T=await R(),T.ok){let z=performance.now()-k;return c({type:"step_success",workflowId:a,stepId:b,stepKey:l,name:u,description:E,ts:Date.now(),durationMs:z,...t&&{metadata:t}}),d&&c({type:"step_complete",workflowId:a,stepKey:d,name:u,description:E,ts:Date.now(),durationMs:z,result:T,...t&&{metadata:t}}),T.value}if(J=T,A<x.attempts&&x.shouldRetry(T.error,A)){let z=le(A,x);c({type:"step_retry",workflowId:a,stepId:b,stepKey:l,name:u,ts:Date.now(),attempt:A+1,maxAttempts:x.attempts,delayMs:z,error:T.error,...t&&{metadata:t},diagnostics:j(T.error,o.errorMeta,"result",A,performance.now()-k)}),x.onRetry(T.error,A,z),await pe(z);continue}x.attempts>1&&c({type:"step_retries_exhausted",workflowId:a,stepId:b,stepKey:l,name:u,ts:Date.now(),durationMs:performance.now()-k,attempts:A,lastError:T.error,...t&&{metadata:t},diagnostics:j(T.error,o.errorMeta,"result",A,performance.now()-k)});break}catch(T){let z=performance.now()-ve;if($e(T)){let H=T.ms;c({type:"step_timeout",workflowId:a,stepId:b,stepKey:l,name:u,ts:Date.now(),timeoutMs:H,attempt:A,...t&&{metadata:t},diagnostics:j(T,o.errorMeta,"timeout",A)}),c({type:"step_success",workflowId:a,stepId:b,stepKey:l,name:u,description:E,ts:Date.now(),durationMs:performance.now()-k,...t&&{metadata:t}}),d&&c({type:"step_complete",workflowId:a,stepKey:d,name:u,description:E,ts:Date.now(),durationMs:performance.now()-k,result:B(void 0),...t&&{metadata:t}});return}if(V(T))throw c({type:"step_aborted",workflowId:a,stepId:b,stepKey:l,name:u,description:E,ts:Date.now(),durationMs:z,...t&&{metadata:t}}),T;if(xe(T)){let H=je(T),Oe=g?.ms??H?.timeoutMs??0;if(c({type:"step_timeout",workflowId:a,stepId:b,stepKey:l,name:u,ts:Date.now(),timeoutMs:Oe,attempt:A,...t&&{metadata:t},diagnostics:j(T,o.errorMeta,"timeout",A)}),A<x.attempts&&x.shouldRetry(T,A)){let ce=le(A,x);c({type:"step_retry",workflowId:a,stepId:b,stepKey:l,name:u,ts:Date.now(),attempt:A+1,maxAttempts:x.attempts,delayMs:ce,error:T,...t&&{metadata:t},diagnostics:j(T,o.errorMeta,"timeout",A,performance.now()-k)}),x.onRetry(T,A,ce),await pe(ce);continue}x.attempts>1&&c({type:"step_retries_exhausted",workflowId:a,stepId:b,stepKey:l,name:u,ts:Date.now(),durationMs:performance.now()-k,attempts:A,lastError:T,...t&&{metadata:t},diagnostics:j(T,o.errorMeta,"timeout",A,performance.now()-k)});let ue=performance.now()-k;throw c({type:"step_error",workflowId:a,stepId:b,stepKey:l,name:u,description:E,ts:Date.now(),durationMs:ue,error:T,...t&&{metadata:t},diagnostics:j(T,o.errorMeta,"timeout",A,ue)}),d&&c({type:"step_complete",workflowId:a,stepKey:d,name:u,description:E,ts:Date.now(),durationMs:ue,result:D(T,{cause:T}),meta:{origin:"throw",thrown:T},...t&&{metadata:t}}),i?.(T,u,w),I(T,{origin:"throw",thrown:T})}if(A<x.attempts&&x.shouldRetry(T,A)){let H=le(A,x);c({type:"step_retry",workflowId:a,stepId:b,stepKey:l,name:u,ts:Date.now(),attempt:A+1,maxAttempts:x.attempts,delayMs:H,error:T,...t&&{metadata:t},diagnostics:j(T,o.errorMeta,"throw",A,performance.now()-k)}),x.onRetry(T,A,H),await pe(H);continue}x.attempts>1&&!xe(T)&&c({type:"step_retries_exhausted",workflowId:a,stepId:b,stepKey:l,name:u,ts:Date.now(),durationMs:performance.now()-k,attempts:A,lastError:T,...t&&{metadata:t},diagnostics:j(T,o.errorMeta,"throw",A,performance.now()-k)});let ie=performance.now()-k,Z;try{Z=U(T)}catch(H){throw G(H)}throw c({type:"step_error",workflowId:a,stepId:b,stepKey:l,name:u,description:E,ts:Date.now(),durationMs:ie,error:Z,...t&&{metadata:t},diagnostics:j(T,o.errorMeta,"throw",A,ie)}),d&&c({type:"step_complete",workflowId:a,stepKey:d,name:u,description:E,ts:Date.now(),durationMs:ie,result:D(Z,{cause:T}),meta:{origin:"throw",thrown:T},...t&&{metadata:t}}),i?.(Z,u,w),I(Z,{origin:"throw",thrown:T})}}let Y=J,se=performance.now()-k,ae=W(Y.error,{origin:"result",resultCause:Y.cause});throw c({type:"step_error",workflowId:a,stepId:b,stepKey:l,name:u,description:E,ts:Date.now(),durationMs:se,error:ae,...t&&{metadata:t},diagnostics:j(Y.error,o.errorMeta,"result",x.attempts,se)}),d&&c({type:"step_complete",workflowId:a,stepKey:d,name:u,description:E,ts:Date.now(),durationMs:se,result:Y,meta:{origin:"result",resultCause:Y.cause},...t&&{metadata:t}}),i?.(ae,u,w),I(ae,{origin:"result",resultCause:Y.cause})})();p.try=(s,m,r)=>{if(typeof s!="string"||s.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 r?()=>r.error:r.onError;if(r.retry||r.timeout)return p.retry(s,async()=>{try{return B(await m())}catch(E){return D(o(E),{cause:E})}},{attempts:r.retry?.attempts??1,...r.retry??{},key:r.key,timeout:r.timeout});let t=r.key??s,u=s,l=s,d=y;return(async()=>{let E=d?performance.now():0;y&&c({type:"step_start",workflowId:a,stepId:l,stepKey:t,name:u,ts:Date.now()});try{let f=await m(),g=performance.now()-E;return c({type:"step_success",workflowId:a,stepId:l,stepKey:t,name:u,ts:Date.now(),durationMs:g}),t&&c({type:"step_complete",workflowId:a,stepKey:t,name:u,ts:Date.now(),durationMs:g,result:B(f)}),f}catch(f){let g=o(f),b=performance.now()-E,P=W(g,{origin:"throw",thrown:f});throw c({type:"step_error",workflowId:a,stepId:l,stepKey:t,name:u,ts:Date.now(),durationMs:b,error:P}),t&&c({type:"step_complete",workflowId:a,stepKey:t,name:u,ts:Date.now(),durationMs:b,result:D(g,{cause:f}),meta:{origin:"throw",thrown:f}}),i?.(P,u,w),I(P,{origin:"throw",thrown:f})}})()},p.fromResult=(s,m,r)=>{if(typeof s!="string"||s.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=r.key??s,t=s,u=s,l="error"in r?()=>r.error:r.onError,d=y;return(async()=>{let E=d?performance.now():0;y&&c({type:"step_start",workflowId:a,stepId:u,stepKey:o,name:t,ts:Date.now()});let f=await m();if(f.ok){let g=performance.now()-E;return c({type:"step_success",workflowId:a,stepId:u,stepKey:o,name:t,ts:Date.now(),durationMs:g}),o&&c({type:"step_complete",workflowId:a,stepKey:o,name:t,ts:Date.now(),durationMs:g,result:B(f.value)}),f.value}else{let g=l(f.error),b=performance.now()-E,P=W(g,{origin:"result",resultCause:f.error});throw c({type:"step_error",workflowId:a,stepId:u,stepKey:o,name:t,ts:Date.now(),durationMs:b,error:P}),o&&c({type:"step_complete",workflowId:a,stepKey:o,name:t,ts:Date.now(),durationMs:b,result:D(g,{cause:f.error}),meta:{origin:"result",resultCause:f.error}}),i?.(P,t,w),I(P,{origin:"result",resultCause:f.error})}})()},p.fromNullable=(s,m,r,o)=>{if(typeof s!="string"||s.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 p(s,async()=>{let t=await m();return t!=null?B(t):D(r())},o)},p.retry=(s,m,r)=>{if(typeof s!="string"||s.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 p(s,m,{key:r.key??s,retry:{attempts:r.attempts,backoff:r.backoff,initialDelay:r.initialDelay,maxDelay:r.maxDelay,jitter:r.jitter,shouldRetry:r.shouldRetry,onRetry:r.onRetry},timeout:r.timeout})},p.withTimeout=(s,m,r)=>{if(typeof s!="string"||s.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 p(s,m,{key:r.key??s,timeout:r})},p.sleep=(s,m,r)=>{if(typeof s!="string"||s.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 m=="string"?Ie(m):m;if(!o)throw new Error(`step.sleep: invalid duration '${m}'`);let t=o.millis,u=r?.signal;return p(s,async()=>{if(O?.aborted||u?.aborted){let l=new Error("Sleep aborted");throw l.name="AbortError",l}return new Promise((l,d)=>{let E={timeoutId:void 0},f=()=>{E.timeoutId&&clearTimeout(E.timeoutId);let g=new Error("Sleep aborted");g.name="AbortError",d(g)};O?.addEventListener("abort",f,{once:!0}),u?.addEventListener("abort",f,{once:!0}),E.timeoutId=setTimeout(()=>{O?.removeEventListener("abort",f),u?.removeEventListener("abort",f),l(B(void 0))},t)})},{key:r?.key??s,description:r?.description})},p.all=((...s)=>{if(typeof s[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 m=s[0],r=s[1];if(typeof r=="function")return q(m,r);if(r&&typeof r=="object"&&!Array.isArray(r)){let t=F(r);return te(t,{name:m})}throw new TypeError("step.all(name, ...): second argument must be a function (array form) or an object of operations (object form).")}),p.race=(s,m)=>{let r=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let o=performance.now(),t=!1,u={scopeId:r,type:"race",winnerId:void 0};M.push(u);let l=()=>{if(t)return;t=!0;let d=M.findIndex(E=>E.scopeId===r);d!==-1&&M.splice(d,1),c({type:"scope_end",workflowId:a,scopeId:r,ts:Date.now(),durationMs:performance.now()-o,winnerId:u.winnerId})};c({type:"scope_start",workflowId:a,scopeId:r,scopeType:"race",name:s,ts:Date.now()});try{let d=await m();if(l(),!d.ok)throw i?.(d.error,s,w),I(d.error,{origin:"result",resultCause:d.cause});return d.value}catch(d){throw l(),d}})()},p.if=(s,m,r)=>r(),p.label=p.if,p.branch=async(s,m)=>{let{condition:r,then:o,else:t}=m;if(r())return await o();if(t)return await t()},p.arm=(s,m)=>({fn:s,errors:m}),p.forEach=async(s,m,r)=>{let o=[],t=r.maxIterations,u=0,l="run"in r,d=Symbol.asyncIterator in m?m:(async function*(){yield*m})();for await(let E of d){if(t!==void 0&&u>=t)break;let f;l?f=await r.run(E,u):f=await r.item.handler(E,u,p),o.push(f),u++}return o},p.item=s=>({__forEachItemHandler:!0,handler:s}),p.dep=(s,m)=>m,p.workflow=(s,m,r)=>p(s,m,r),p.map=async(s,m,r,o)=>{let t=o?.concurrency??m.length;return p(s,()=>t>=m.length?be(m.map((u,l)=>r(u,l))):(async()=>{let u=[];for(let l=0;l<m.length;l+=t){let d=m.slice(l,l+t),E=await be(d.map((f,g)=>r(f,l+g)));if(!E.ok)return E;u.push(...E.value)}return B(u)})(),{key:o?.key})},p.withFallback=(s,m,r)=>{if(typeof s!="string"||s.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=r.key??s,t=s,u=$(o),l=y;return(async()=>{let d=l?performance.now():0;y&&c({type:"step_start",workflowId:a,stepId:u,stepKey:o,name:t,ts:Date.now()});let E;try{E=await m()}catch(k){if(V(k))throw c({type:"step_aborted",workflowId:a,stepId:u,stepKey:o,name:t,ts:Date.now(),durationMs:performance.now()-d}),k;let _;try{_=U(k)}catch(C){throw G(C)}if(r.on!==void 0&&r.on!==_){let C=performance.now()-d;throw c({type:"step_error",workflowId:a,stepId:u,stepKey:o,name:t,ts:Date.now(),durationMs:C,error:_}),o&&c({type:"step_complete",workflowId:a,stepKey:o,name:t,ts:Date.now(),durationMs:C,result:D(_,{cause:k}),meta:{origin:"throw",thrown:k}}),i?.(_,t,w),I(_,{origin:"throw",thrown:k})}let R;try{R=await r.fallback()}catch(C){if(V(C))throw c({type:"step_aborted",workflowId:a,stepId:u,stepKey:o,name:t,ts:Date.now(),durationMs:performance.now()-d}),C;let x;try{x=U(C)}catch(Y){throw G(Y)}let J=performance.now()-d;throw c({type:"step_error",workflowId:a,stepId:u,stepKey:o,name:t,ts:Date.now(),durationMs:J,error:x}),o&&c({type:"step_complete",workflowId:a,stepKey:o,name:t,ts:Date.now(),durationMs:J,result:D(x,{cause:C}),meta:{origin:"throw",thrown:C}}),i?.(x,t,w),I(x,{origin:"throw",thrown:C})}if(R.ok){let C=performance.now()-d;return c({type:"step_success",workflowId:a,stepId:u,stepKey:o,name:t,ts:Date.now(),durationMs:C}),o&&c({type:"step_complete",workflowId:a,stepKey:o,name:t,ts:Date.now(),durationMs:C,result:R,meta:{origin:"fallback",fallbackUsed:!0,fallbackReason:String(_)}}),R.value}else{let C=performance.now()-d,x=W(R.error,{origin:"result",resultCause:R.cause});throw c({type:"step_error",workflowId:a,stepId:u,stepKey:o,name:t,ts:Date.now(),durationMs:C,error:x}),o&&c({type:"step_complete",workflowId:a,stepKey:o,name:t,ts:Date.now(),durationMs:C,result:R,meta:{origin:"result",resultCause:R.cause}}),i?.(x,t,w),I(x,{origin:"result",resultCause:R.cause})}}if(E.ok){let k=performance.now()-d;return c({type:"step_success",workflowId:a,stepId:u,stepKey:o,name:t,ts:Date.now(),durationMs:k}),o&&c({type:"step_complete",workflowId:a,stepKey:o,name:t,ts:Date.now(),durationMs:k,result:E}),E.value}let f=E.error;if(r.on!==void 0&&r.on!==f){let k=performance.now()-d,_=W(f,{origin:"result",resultCause:E.cause});throw c({type:"step_error",workflowId:a,stepId:u,stepKey:o,name:t,ts:Date.now(),durationMs:k,error:_}),o&&c({type:"step_complete",workflowId:a,stepKey:o,name:t,ts:Date.now(),durationMs:k,result:E,meta:{origin:"result",resultCause:E.cause}}),i?.(_,t,w),I(_,{origin:"result",resultCause:E.cause})}let g;try{g=await r.fallback()}catch(k){if(V(k))throw c({type:"step_aborted",workflowId:a,stepId:u,stepKey:o,name:t,ts:Date.now(),durationMs:performance.now()-d}),k;let _;try{_=U(k)}catch(C){throw G(C)}let R=performance.now()-d;throw c({type:"step_error",workflowId:a,stepId:u,stepKey:o,name:t,ts:Date.now(),durationMs:R,error:_}),o&&c({type:"step_complete",workflowId:a,stepKey:o,name:t,ts:Date.now(),durationMs:R,result:D(_,{cause:k}),meta:{origin:"throw",thrown:k}}),i?.(_,t,w),I(_,{origin:"throw",thrown:k})}if(g.ok){let k=performance.now()-d;return c({type:"step_success",workflowId:a,stepId:u,stepKey:o,name:t,ts:Date.now(),durationMs:k}),o&&c({type:"step_complete",workflowId:a,stepKey:o,name:t,ts:Date.now(),durationMs:k,result:g,meta:{origin:"fallback",fallbackUsed:!0,fallbackReason:String(f)}}),g.value}let b=performance.now()-d,P=W(g.error,{origin:"result",resultCause:g.cause});throw c({type:"step_error",workflowId:a,stepId:u,stepKey:o,name:t,ts:Date.now(),durationMs:b,error:P}),o&&c({type:"step_complete",workflowId:a,stepKey:o,name:t,ts:Date.now(),durationMs:b,result:g,meta:{origin:"result",resultCause:g.cause}}),i?.(P,t,w),I(P,{origin:"result",resultCause:g.cause})})()},p.withResource=(s,m)=>{if(typeof s!="string"||s.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 r=s,o=s,t=$(r),u=y;return(async()=>{let l=u?performance.now():0;y&&c({type:"step_start",workflowId:a,stepId:t,stepKey:r,name:o,ts:Date.now()});let d;try{d=await m.acquire()}catch(R){if(V(R))throw c({type:"step_aborted",workflowId:a,stepId:t,stepKey:r,name:o,ts:Date.now(),durationMs:performance.now()-l}),R;let C;try{C=U(R)}catch(J){throw G(J)}let x=performance.now()-l;throw c({type:"step_error",workflowId:a,stepId:t,stepKey:r,name:o,ts:Date.now(),durationMs:x,error:C}),r&&c({type:"step_complete",workflowId:a,stepKey:r,name:o,ts:Date.now(),durationMs:x,result:D(C,{cause:R}),meta:{origin:"throw",thrown:R}}),i?.(C,o,w),I(C,{origin:"throw",thrown:R})}if(!d.ok){let R=performance.now()-l,C=W(d.error,{origin:"result",resultCause:d.cause});throw c({type:"step_error",workflowId:a,stepId:t,stepKey:r,name:o,ts:Date.now(),durationMs:R,error:C}),r&&c({type:"step_complete",workflowId:a,stepKey:r,name:o,ts:Date.now(),durationMs:R,result:d,meta:{origin:"result",resultCause:d.cause}}),i?.(C,o,w),I(C,{origin:"result",resultCause:d.cause})}let E=d.value,f,g,b=!1;try{f=await m.use(E)}catch(R){if(V(R)){try{await m.release(E)}catch(C){console.warn(`[awaitly] step.withResource("${s}"): release threw after earlyExit:`,C)}throw R}g=R,b=!0}try{await m.release(E)}catch(R){console.warn(`[awaitly] step.withResource("${s}"): release threw:`,R)}if(b){let R;try{R=U(g)}catch(x){throw G(x)}let C=performance.now()-l;throw c({type:"step_error",workflowId:a,stepId:t,stepKey:r,name:o,ts:Date.now(),durationMs:C,error:R}),r&&c({type:"step_complete",workflowId:a,stepKey:r,name:o,ts:Date.now(),durationMs:C,result:D(R,{cause:g}),meta:{origin:"throw",thrown:g}}),i?.(R,o,w),I(R,{origin:"throw",thrown:g})}let P=f;if(P.ok){let R=performance.now()-l;return c({type:"step_success",workflowId:a,stepId:t,stepKey:r,name:o,ts:Date.now(),durationMs:R}),r&&c({type:"step_complete",workflowId:a,stepKey:r,name:o,ts:Date.now(),durationMs:R,result:P}),P.value}let k=performance.now()-l,_=W(P.error,{origin:"result",resultCause:P.cause});throw c({type:"step_error",workflowId:a,stepId:t,stepKey:r,name:o,ts:Date.now(),durationMs:k,error:_}),r&&c({type:"step_complete",workflowId:a,stepKey:r,name:o,ts:Date.now(),durationMs:k,result:P,meta:{origin:"result",resultCause:P.cause}}),i?.(_,o,w),I(_,{origin:"result",resultCause:P.cause})})()};let L=await n({step:p});if(process.env.NODE_ENV!=="production"&&L!==null&&typeof L=="object"&&"ok"in L&&typeof L.ok=="boolean"){let s=L;(s.ok===!0&&"value"in s||s.ok===!1&&"error"in s)&&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 B(L)}catch(p){if(Be(p))throw p.thrown;if(V(p)){let q=p.meta.origin==="throw"?p.meta.thrown:p.meta.origin==="result"?p.meta.resultCause:void 0;return D(p.error,{cause:q})}let F=U(p);return i?.(F,"unexpected",w),D(F,{cause:p})}}Ce.strict=(n,e)=>Ce(n,e);async function be(n){return n.length===0?B([]):new Promise(e=>{let i=!1,y=n.length,v=new Array(n.length);for(let h=0;h<n.length;h++){let S=h;Promise.resolve(n[S]).catch(w=>D({type:"PROMISE_REJECTED",cause:w},{cause:{type:"PROMISE_REJECTION",reason:w}})).then(w=>{if(!i){if(!w.ok){i=!0,e(w);return}v[S]=w.value,y--,y===0&&e(B(v))}})}})}function _e(n){return typeof n=="object"&&n!==null&&n.type==="RESOURCE_CLEANUP_ERROR"}function He(){let n=[];return{add:e=>(n.push(e),e.value),close:async()=>{let e=[];for(let i=n.length-1;i>=0;i--)try{await n[i].close()}catch(y){e.push(y)}if(n.length=0,e.length>0)throw{type:"RESOURCE_CLEANUP_ERROR",errors:e}},has:e=>n.includes(e),size:()=>n.length}}async function ot(n){let e=He(),i;try{i=await n(e)}catch(y){try{await e.close()}catch(v){if(_e(v))return D({...v,originalResult:{thrown:y}})}throw y}try{await e.close()}catch(y){if(_e(y))return D({...y,originalResult:i});throw y}return i}async function st(n,e){let i=await n();return{value:i,close:async()=>{await e(i)}}}export{st as createResource,He as createResourceScope,_e as isResourceCleanupError,ot as withScope};
|
|
7
|
-
//# sourceMappingURL=resource.js.map
|