promise-logic 2.8.5 → 2.9.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 xier123456
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,49 +1,153 @@
1
- ### **1. Core Philosophy**
1
+ ## Core Philosophy
2
+
3
+ **Replace API Memory with Logical Concepts**
4
+
5
+ The design philosophy of `promise-logic` is: **Developers should focus on business logic, not on details of Promise APIs**.
6
+
7
+ Traditional Promise combinations (such as `Promise.all`, `Promise.race`) have naming and semantics that are not intuitive enough, especially in complex asynchronous scenarios where code readability rapidly declines.
2
8
 
3
- **Replace API Memory with Logical Concepts**
4
- The design philosophy of `promise-logic` is: **Developers should focus on business logic, not on details of Promise APIs**.
5
- Traditional Promise combinations (such as `Promise.all`, `Promise.race`) have naming and semantics that are not intuitive enough, especially in complex asynchronous scenarios where code readability rapidly declines.
6
9
  `promise-logic` abstracts asynchronous combinations into logical operations like `and`, `or`, `xor` through the concept of **Logic Gates**, making code semantically clear and self-explanatory.
7
10
 
11
+ ### Example Scenario: E-commerce Order Processing
12
+
13
+ ```javascript
14
+ import { PromiseLogic } from 'promise-logic';
15
+
16
+
17
+
18
+
19
+
20
+ // Order processing flow
21
+ async function createOrder() {
22
+ // Unified error types
23
+ const PAYMENT_OR_INVENTORY_ERROR = 'PAYMENT_OR_INVENTORY_ERROR';
24
+ const ORDER_ERROR = 'ORDER_ERROR';
25
+ const LOGISTICS_ERROR = 'LOGISTICS_ERROR';
26
+ const COUPON_ERROR = 'COUPON_ERROR';
27
+
28
+ // Destructure and, or methods from PromiseLogic for simpler syntax and understand the logical relationship of the current scenario
29
+ const { and, or } = PromiseLogic;
30
+
31
+ try {
32
+ // Execute payment and inventory operations (both must succeed)
33
+
34
+ const [
35
+ [paymentResult, inventoryResult], // Payment and inventory operation results
36
+ logistics, // Logistics operation result
37
+ coupon // Coupon operation result
38
+ ] = await and([
39
+ and([paymentAPI(), inventoryAPI()],{
40
+ errorType: PAYMENT_OR_INVENTORY_ERROR,// Custom payment or inventory error type
41
+ }),
42
+ or([oneLogisticsAPI(), twoLogisticsAPI()], {
43
+ errorType: LOGISTICS_ERROR,// Custom logistics error type
44
+ }),
45
+ or([couponAPI1(), couponAPI2()], {
46
+ errorType: COUPON_ERROR,// Custom coupon error type
47
+ })
48
+ ], {
49
+ errorType: ORDER_ERROR,// Custom order error type
50
+ errorMessage: 'Order creation failed' // Custom order error message
51
+ });
52
+
53
+ // Order creation successful, return payment result, inventory result, logistics result and coupon result
54
+ return {
55
+ payment: paymentResult,
56
+ inventory: inventoryResult,
57
+ logistics: logistics,
58
+ coupon: coupon,
59
+ status: 'success'
60
+ };
61
+ } catch (error) {
62
+ // Analyze error type
63
+ switch (error.type) {
64
+ case ORDER_ERROR:
65
+ return {
66
+ status: 'error',
67
+ errorType: 'order_error',
68
+ message: 'Order creation failed',
69
+ details: error
70
+ };
71
+ case PAYMENT_OR_INVENTORY_ERROR:
72
+ return {
73
+ status: 'error',
74
+ errorType: 'payment_or_inventory_failed',
75
+ message: 'Payment or inventory operation failed',
76
+ details: error
77
+ };
78
+ case LOGISTICS_ERROR:
79
+ return {
80
+ status: 'error',
81
+ errorType: 'logistics_unavailable',
82
+ message: 'All logistics services are unavailable',
83
+ details: error
84
+ };
85
+ case COUPON_ERROR:
86
+ return {
87
+ status: 'error',
88
+ errorType: 'coupon_error',
89
+ message: 'All coupons are unavailable',
90
+ details: error
91
+ };
92
+ default:
93
+ return {
94
+ status: 'error',
95
+ errorType: 'default_error',
96
+ message: 'Unknown error occurred during order creation',
97
+ details: error
98
+ };
99
+ }
100
+ }
101
+ }
102
+ ```
103
+
104
+ As you can see, the code structure is completely consistent with business rules. Code is documentation, and logic is self-explanatory.
105
+
8
106
  ---
9
107
 
10
- ### **2. Features**
108
+ ## Features
109
+
110
+ ### 1. Logical Semantics
111
+
112
+ - `and`: All tasks must succeed (equivalent to `Promise.all`)
113
+ - `or`: At least one task succeeds (equivalent to `Promise.any`)
114
+ - `xor`: **Exactly one task succeeds**
115
+ - `nand`: Not all tasks succeed (at least one fails)
116
+ - `nor`: All tasks fail (no task succeeds)
117
+ - `xnor`: All tasks succeed or all fail (same state)
118
+ - `not`: Inverts the result of a single Promise
119
+ - `majority`: Most tasks succeed
120
+
121
+ ### 2. Zero Dependencies
122
+
123
+ Only depends on native Promise, no additional runtime dependencies.
124
+
125
+ ### 3. Full Test Coverage
11
126
 
12
- 1. **Logical Semantics**
13
- - `and`: All tasks must succeed (equivalent to native `Promise.all`)
14
- - `or`: At least one task succeeds (equivalent to native `Promise.any`)
15
- - `xor`: **Exactly one task succeeds**
16
- - `nand`: Not all tasks succeed (at least one fails)
17
- - `nor`: All tasks fail (no task succeeds)
18
- - `xnor`: All tasks succeed or all fail (same state)
19
- - `not`: Inverts the result of a single Promise
20
- - `majority`: Most tasks succeed
127
+ All logic gates have undergone rigorous unit testing to ensure behavior meets expectations.
21
128
 
22
- 2. **Zero Dependencies**
23
- Only depends on native Promise, no additional runtime dependencies.
129
+ ### 4. Clear Error Classification
24
130
 
25
- 3. **Full Test Coverage**
26
- All logic gates have undergone rigorous unit testing to ensure behavior meets expectations.
131
+ - `PromiseLogicError` unified error type
132
+ - `error.type` distinguishes specific logical errors (e.g., `'XOR_ERROR'`)
133
+ - Supports custom error types and messages
27
134
 
28
- 4. **Clear Error Classification**
29
- - `PromiseLogicError` unified error type
30
- - `error.type` distinguishes specific logical errors (e.g., `'XOR_ERROR'`)
135
+ ### 5. Timeout Control
31
136
 
32
- 5. **Timeout Control**
33
- - `maxTimer`: Adds timeout functionality to any Promise operation (unit: milliseconds).
137
+ - `maxTimer`: Adds timeout functionality to any Promise operation (unit: milliseconds)
138
+ - Supports custom timeout error messages
34
139
 
35
- **Note**:
36
- - After timeout, it immediately interrupts the execution of the current Promise chain and jumps to error handling
37
- - However, please note that this does not cancel underlying asynchronous operations that have already started (such as network requests, file read/write, etc.)
140
+ **Note**: After timeout, it immediately interrupts the execution of the current Promise chain and jumps to error handling, but does not cancel underlying asynchronous operations that have already started (such as network requests, file read/write, etc.).
38
141
 
39
- 6. **Extended Operations**
40
- - `allFulfilled`: Returns all successful results in order. Returns immediately when a result exists.
41
- - `allRejected`: Returns all failed results in order. Returns immediately when a result exists.
42
- - `allSettled`: Returns all results (both successful and failed)
142
+ ### 6. Extended Operations
143
+
144
+ - `allFulfilled`: Returns all successful results in order, immediately tries to return when there are successful results
145
+ - `allRejected`: Returns all failed results in order, immediately tries to return when there are failed results
146
+ - `allSettled`: Returns all results (both successful and failed)
43
147
 
44
148
  ---
45
149
 
46
- ### **3. Installation**
150
+ ## Installation
47
151
 
48
152
  ```bash
49
153
  npm install promise-logic
@@ -51,33 +155,58 @@ npm install promise-logic
51
155
 
52
156
  ---
53
157
 
54
- ### **4. Quick Start**
158
+ ## Quick Start
159
+
160
+ ### Basic Usage Examples
55
161
 
56
- #### Example: Primary/Backup Service Call (XOR Scenario)
162
+ #### Destructuring Assignment
57
163
 
58
164
  ```javascript
59
165
  import { PromiseLogic } from 'promise-logic';
60
166
 
61
- // Primary service call
62
- const primary = fetch('https://api.main.com/data');
63
- // Backup service call
64
- const backup = fetch('https://api.backup.com/data');
167
+ // Destructure methods from PromiseLogic for simpler syntax
168
+ const { and, or, xor, not, race } = PromiseLogic;
169
+
170
+ // Use destructured methods
171
+ and([
172
+ fetch('/api/user').then(r => r.json()),
173
+ fetch('/api/profile').then(r => r.json())
174
+ ]).then(results => console.log(results));
175
+
176
+ or([
177
+ fetch('/api/primary').then(r => r.json()).catch(() => { throw new Error('primary failed'); }),
178
+ fetch('/api/backup').then(r => r.json())
179
+ ]).then(result => console.log(result));
180
+
181
+ xor([
182
+ fetch('/api/method1').then(r => r.json()),
183
+ fetch('/api/method2').then(r => r.json())
184
+ ]).then(result => console.log(result));
185
+ ```
186
+
187
+ #### Security Audit (XOR Scenario)
188
+
189
+ ```javascript
190
+ import { PromiseLogic } from 'promise-logic';
65
191
 
66
192
  // Execute XOR logic: exactly one success
67
- PromiseLogic.xor([primary, backup])
193
+ PromiseLogic.xor([
194
+ biometricAuth(), // Biometric authentication
195
+ hardwareKeyAuth() // Hardware key authentication
196
+ ])
68
197
  .then((result) => {
69
- console.log('Successfully fetched data:', result);
198
+ console.log('Successfully authenticated:', result);
70
199
  })
71
200
  .catch((error) => {
72
201
  if (error.type === 'XOR_ERROR') {
73
- console.error('Both primary and backup services succeeded or failed, which does not meet XOR semantics');
202
+ console.error('Conflict between biometric and hardware key authentication');
74
203
  } else {
75
- console.error('Network error:', error);
204
+ console.error('Authentication error:', error);
76
205
  }
77
206
  });
78
207
  ```
79
208
 
80
- #### Example: Majority Decision (Majority Scenario)
209
+ #### Majority Decision (Majority Scenario)
81
210
 
82
211
  ```javascript
83
212
  import { PromiseLogic } from 'promise-logic';
@@ -88,35 +217,17 @@ const services = [
88
217
  fetch('https://api.node3.com/vote')
89
218
  ];
90
219
 
91
- PromiseLogic.majority(services)
92
- .then((results) => {
93
- console.log('Majority of services returned success:', results);
94
- })
95
- .catch((error) => {
96
- console.error('Majority of services failed:', error);
97
- });
98
- ```
99
-
100
- ```typescript
101
- import { PromiseLogic } from 'promise-logic/typescript';
102
-
103
- const services = [
104
- fetch('https://api.node1.com/vote'),
105
- fetch('https://api.node2.com/vote'),
106
- fetch('https://api.node3.com/vote')
107
- ];
108
-
109
- // Type assertion can be done, or let PromiseLogic infer types automatically
110
- PromiseLogic.majority<Response>(services)
220
+ // Custom threshold 0.6 (60%)
221
+ PromiseLogic.majority(services, { max: 0.6 })
111
222
  .then((results) => {
112
- console.log('Majority of services returned success:', results);
223
+ console.log('Custom threshold met, successful results:', results);
113
224
  })
114
225
  .catch((error) => {
115
- console.error('Majority of services failed:', error);
226
+ console.error('Custom threshold not met:', error);
116
227
  });
117
228
  ```
118
229
 
119
- #### Example: Timeout Control
230
+ #### Timeout Control
120
231
 
121
232
  ```javascript
122
233
  import { PromiseLogic } from 'promise-logic';
@@ -127,16 +238,16 @@ PromiseLogic.and([
127
238
  new Promise((resolve) => setTimeout(resolve, 3000)), // 3 second operation
128
239
  Promise.resolve(3)
129
240
  ])
130
- .maxTimer(2000, 'Custom timeout error: operation did not complete within 2000ms') // 2 second timeout, custom error message
241
+ .maxTimer(2000, 'Custom timeout error: operation did not complete within 2000ms') // 2 second timeout
131
242
  .then((result) => {
132
243
  console.log('Operation completed within timeout:', result);
133
244
  })
134
245
  .catch((error) => {
135
- console.error('Operation timed out:', error.message); // Output: Custom timeout error: operation did not complete within 2000ms
246
+ console.error('Operation timed out:', error.message);
136
247
  });
137
248
  ```
138
249
 
139
- #### Example: Extended Operations
250
+ #### Extended Operations
140
251
 
141
252
  ```javascript
142
253
  import { PromiseLogic } from 'promise-logic';
@@ -148,12 +259,12 @@ const operations = [
148
259
  Promise.reject('error2')
149
260
  ];
150
261
 
151
- // Get all successful results (returns immediately when a result exists)
262
+ // Get all successful results (returns immediately when there are successes)
152
263
  PromiseLogic.allFulfilled(operations).then((results) => {
153
264
  console.log('Successful results:', results); // ['success1', 'success2']
154
265
  });
155
266
 
156
- // Get all failed results (returns immediately when a result exists)
267
+ // Get all failed results (returns immediately when there are failures)
157
268
  PromiseLogic.allRejected(operations).then((errors) => {
158
269
  console.log('Failed results:', errors); // ['error1', 'error2']
159
270
  });
@@ -161,138 +272,44 @@ PromiseLogic.allRejected(operations).then((errors) => {
161
272
  // Get all results (both success and failure)
162
273
  PromiseLogic.allSettled(operations).then((results) => {
163
274
  console.log('All results:', results);
164
- // Output:
165
- // [
166
- // { status: 'fulfilled', value: 'success1' },
167
- // { status: 'rejected', reason: 'error1' },
168
- // { status: 'fulfilled', value: 'success2' },
169
- // { status: 'rejected', reason: 'error2' }
170
- // ]
171
275
  });
172
276
  ```
173
277
 
174
- #### Example: allFulfilled - Execution Timing and Results
175
-
176
- ```javascript
177
- import { PromiseLogic } from 'promise-logic';
178
278
 
179
- const startTime = Date.now();
180
- console.log('Start executing allFulfilled, time:', startTime);
181
-
182
- const allFulfilledResult = await PromiseLogic.allFulfilled([
183
- new Promise(resolve => {
184
- console.log('First Promise started (slow)');
185
- setTimeout(() => {
186
- console.log('First Promise completed:', 'success1');
187
- resolve('success1');
188
- }, 100);
189
- }),
190
- Promise.reject('error'),
191
- new Promise(resolve => {
192
- console.log('Third Promise started (fast)');
193
- setTimeout(() => {
194
- console.log('Third Promise completed:', 'success2');
195
- resolve('success2');
196
- }, 10);
197
- })
198
- ]);
199
-
200
- const endTime = Date.now();
201
- const elapsedTime = endTime - startTime;
202
- console.log('allFulfilled complete results:', allFulfilledResult); // ['success1', 'success2']
203
- ```
204
-
205
- **Explanation:**
206
- - **First return info**: Third Promise completes at 10ms, immediately returns `['success2']`
207
- - **Complete return info**: First Promise completes at 100ms, final complete result is `['success1', 'success2']`
208
- - **Execution timing**: Returns immediately when a result exists, does not wait for all Promises to complete
209
- - **Order preservation**: Complete results are returned in input order, not completion order
210
-
211
- #### Example: allRejected - Execution Timing and Results
279
+ ### Custom Error Types and Messages
212
280
 
213
281
  ```javascript
214
282
  import { PromiseLogic } from 'promise-logic';
215
283
 
216
- const startTime = Date.now();
217
- console.log('Start executing allRejected, time:', startTime);
218
-
219
- const allRejectedResult = await PromiseLogic.allRejected([
220
- Promise.resolve('success1'),
221
- new Promise((_, reject) => {
222
- console.log('Second Promise started (fast)');
223
- setTimeout(() => {
224
- console.log('Second Promise completed:', 'error1');
225
- reject('error1');
226
- }, 10);
227
- }),
228
- new Promise((_, reject) => {
229
- console.log('Third Promise started (slow)');
230
- setTimeout(() => {
231
- console.log('Third Promise completed:', 'error2');
232
- reject('error2');
233
- }, 100);
234
- })
235
- ]);
236
-
237
- const endTime = Date.now();
238
- const elapsedTime = endTime - startTime;
239
- console.log('allRejected complete results:', allRejectedResult); // ['error1', 'error2']
240
- ```
241
-
242
- **Explanation:**
243
- - **First return info**: Second Promise completes at 10ms, immediately returns `['error1']`
244
- - **Complete return info**: Third Promise completes at 100ms, final complete result is `['error1', 'error2']`
245
- - **Execution timing**: Returns immediately when a result exists, does not wait for all Promises to complete
246
- - **Order preservation**: Complete results are returned in input order, not completion order
247
-
248
- #### Example: Custom majority threshold
249
-
250
- ```javascript
251
- import { PromiseLogic } from 'promise-logic';
284
+ // Custom error type
285
+ const CUSTOM_ERROR_TYPE = 'CUSTOM_ERROR';
252
286
 
253
- const services = [
254
- Promise.resolve('service1'),
255
- Promise.resolve('service2'),
256
- Promise.reject('service3'),
257
- Promise.reject('service4')
258
- ];
287
+ // Custom error message
288
+ const CUSTOM_ERROR_MESSAGE = 'Custom error message';
259
289
 
260
- // Default threshold (0.5): requires at least 3 successes
261
- // Custom threshold (0.4): requires at least 2 successes
262
- PromiseLogic.majority(services, { max: 0.4 })
290
+ // Use custom error type and message
291
+ PromiseLogic.and([Promise.resolve('success1'), Promise.reject('error1')], {
292
+ errorType: CUSTOM_ERROR_TYPE,
293
+ errorMessage: CUSTOM_ERROR_MESSAGE
294
+ })
263
295
  .then((results) => {
264
- console.log('Custom threshold met, successful results:', results); // ['service1', 'service2']
296
+ console.log(results);
265
297
  })
266
298
  .catch((error) => {
267
- console.error('Custom threshold not met:', error);
299
+ if (error.type === CUSTOM_ERROR_TYPE) {
300
+ console.error(error); // Output: Custom error message
301
+ } else {
302
+ console.error(error);
303
+ }
268
304
  });
269
305
  ```
270
306
 
271
- ## Recent Updates
272
-
273
- ### v2.8.0
274
-
275
- - **Performance optimization**: Optimized `allFulfilled` and `allRejected` implementation logic from the bottom layer, existing results return immediately while maintaining consistent input and output order
276
- - **Added chain timeout control with custom error messages**: Can customize timeout error messages in the `maxTimer` method
277
- - **Type fixes**: Fixed TypeScript version type declaration issues
278
- - **Test completion**: Added complete test cases for `allFulfilled`, `allRejected`, and `maxTimer`
279
- - **Code refactoring**: Improved code structure for better maintainability
280
-
281
- ### v2.7.0
282
-
283
- - **Added modular architecture**: Separated logic gate implementations into independent modules for better code maintainability
284
- - **Fixed NOT Logic Gate**: Fixed potential risks in NOT logic gate in production environments
285
- - **Improved Error Messages**: Enhanced error message format for clearer error details
286
- - **Enhanced Test Coverage**: Added complete factory function tests for v1 and v2 versions
287
- - **Updated Documentation**: Added custom factory function usage guide
288
-
289
-
290
307
  ### Using Factory Function
291
308
 
292
309
  The factory function allows you to create PromiseLogic methods with custom names:
293
310
 
294
311
  ```javascript
295
- import { createPromiseLogic } from 'promise-logic/factory';
312
+ import { createPromiseLogic } from 'promise-logic';
296
313
 
297
314
  // Create instance with custom naming
298
315
  const logic = createPromiseLogic({
@@ -307,7 +324,6 @@ const logic = createPromiseLogic({
307
324
 
308
325
  // Use custom-named methods
309
326
  logic.api_all_call([fetch('/api/users'), fetch('/api/posts')]);
310
-
311
327
  logic.api_any_call([fetch('/api/cache'), fetch('/api/database')]);
312
328
  ```
313
329
 
@@ -327,9 +343,30 @@ PromiseLogic.and([Promise.resolve(1), Promise.resolve(2)]).then(
327
343
  PromiseLogic.and<number>([Promise.resolve(1), Promise.resolve(2)]);
328
344
  ```
329
345
 
346
+ ### Dynamic Logic Nested
347
+
348
+ ```javascript
349
+ import { PromiseLogic } from 'promise-logic';
350
+
351
+
352
+ // Dynamic nesting example: adjust logistics strategy based on user level
353
+ const orderFlow = async (userLevel) => {
354
+ // VIP users: dual high-availability logistics guarantee (at least one success)
355
+ // Normal users: priority standard logistics, failover to economy logistics (at least one success)
356
+ const logisticsStrategy = userLevel === 'VIP'
357
+ ? PromiseLogic.or([premiumLogistics(), backupLogistics()])
358
+ : PromiseLogic.or([standardLogistics(), economyLogistics()]);
359
+
360
+ return await PromiseLogic.and([
361
+ PromiseLogic.and([paymentAPI(), inventoryAPI()]), // Payment + inventory atomic operations
362
+ logisticsStrategy, // Logistics strategy
363
+ couponValidation() // Coupon validation
364
+ ]);
365
+ };
366
+ ```
330
367
  ---
331
368
 
332
- ### **5. API Reference**
369
+ ## API Reference
333
370
 
334
371
  | API | Description |
335
372
  | :------------- | :--------------------------------------------------------------------------------------------------------------------------- |
@@ -347,62 +384,54 @@ PromiseLogic.and<number>([Promise.resolve(1), Promise.resolve(2)]);
347
384
  | `race` | Returns the first completed Promise result (regardless of success or failure). Equivalent to native `Promise.race`. |
348
385
  | `maxTimer` | Adds timeout functionality to any Promise operation (unit: milliseconds). Supports custom timeout error messages. |
349
386
 
387
+ ---
388
+
389
+ ## Changelog
350
390
 
351
- ### **6. Real-world Application Scenarios**
391
+ ### v2.9.0
352
392
 
353
- 1. **Primary/Backup Service Calls**
354
- - Use `xor` to ensure **exactly one service responds**, avoiding duplicate processing.
393
+ **Error Mechanism Improvements**
394
+ - Added `errorType` and `errorMessage` parameters to logic gates, supporting custom error types and messages, further fitting business scenarios
395
+ - Optimized the existing error type system to ensure correct TypeScript type definitions
396
+ - Optimized TypeScript type compatibility issues
397
+ - Optimized allSettled gate return type error messages
398
+ - Improved test scripts, covering most promise combination logic boundaries and tricky scenario issues, ensuring more stable operation of logic gates
399
+ - Optimized logic gate execution efficiency, reducing unnecessary Promise wrapping
355
400
 
356
- 2. **Distributed Decision Making**
357
- - Use `majority` to implement majority consensus (e.g., distributed voting).
401
+ ### v2.8.0
358
402
 
359
- 3. **Resource Competition**
360
- - Use `or` to get the first available resource (e.g., CDN node selection).
361
- - Use `not` to check if a resource is available.
403
+ - **Performance optimization**: Optimized `allFulfilled` and `allRejected` implementation logic from the bottom layer, existing results return immediately while maintaining consistent input and output order
404
+ - **Added chain timeout control with custom error messages**: Can customize timeout error messages in the `maxTimer` method
405
+ - **Type fixes**: Fixed TypeScript version type declaration issues
406
+ - **Test completion**: Added complete test cases for `allFulfilled`, `allRejected`, and `maxTimer`
407
+ - **Code refactoring**: Improved code structure for better maintainability
362
408
 
363
- 4. **Full-link Validation**
364
- - Use `and` to ensure all dependent services succeed (e.g., order creation).
409
+ ---
365
410
 
366
- 5. **Timeout Control**
367
- - Use `maxTimer` to add timeout functionality to any Promise operation (unit: milliseconds).
368
- - Returns custom error message after timeout, default: `Promise timed out after ${ms} ms`.
411
+ ## Contribution Guide
369
412
 
370
- 6. **Partial Success Handling**
371
- - Use `allFulfilled` to execute all Promises concurrently and return successful result array (e.g., batch API calls, suitable for high concurrency and partial failure acceptance scenarios).
372
- - Use `allRejected` to execute all Promises concurrently and return failed result array (e.g., error log collection, suitable for batch failure processing scenarios).
413
+ ### 1. Development Environment
373
414
 
374
- 7. **Full Result Retrieval**
375
- - Use `allSettled` to get results from all Promises (regardless of success or failure).
415
+ ```bash
416
+ git clone https://github.com/xier123456/promise-logic.git
417
+ cd promise-logic
418
+ npm install
419
+ ```
376
420
 
377
- 8. **Fast Response**
378
- - Use `race` to return the first completed Promise result (regardless of success or failure).
421
+ ### 2. Testing
379
422
 
380
- 9. **State Validation**
381
- - Use `nand` to verify that not all Promises succeed (at least one fails).
382
- - Use `nor` to verify that all Promises fail (no task succeeds).
383
- - Use `xnor` to verify that all Promises succeed or all fail (same state).
423
+ ```bash
424
+ npm test
425
+ ```
384
426
 
385
- ---
427
+ ### 3. Commit Guidelines
386
428
 
387
- ### **7. Contribution Guide**
388
-
389
- 1. **Development Environment**
390
- ```bash
391
- git clone https://github.com/xier123456/promise-logic.git
392
- cd promise-logic
393
- npm install
394
- ```
395
- 2. **Testing**
396
- ```bash
397
- npm test
398
- ```
399
- 3. **Commit Guidelines**
400
- - Commit messages must include prefixes like `feat:` (new feature), `fix:` (bug fix), `docs:` (documentation).
401
- - Pull Requests must include test cases.
429
+ - Commit messages must include prefixes like `feat:` (new feature), `fix:` (bug fix), `docs:` (documentation).
430
+ - Pull Requests must include test cases.
402
431
 
403
432
  ---
404
433
 
405
- ### **8. Resource Links**
434
+ ## Resource Links
406
435
 
407
436
  - **GitHub Repository**: [https://github.com/xier123456/promise-logic](https://github.com/xier123456/promise-logic)
408
437
  - **npm Package**: [https://www.npmjs.com/package/promise-logic](https://www.npmjs.com/package/promise-logic)
@@ -1 +1 @@
1
- "use strict";class e extends Error{constructor(e,t,r){super(t),this.name="PromiseLogicError",this.type=e,this.results=r}}function t(t,r,l,n,s){const i={XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${r} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${l} promises fulfilled (expected at least one rejection).`,NOT_ERROR:"NOT condition failed: promise resolved (expected rejection).",NOR_ERROR:`NOR condition failed: ${r} promises fulfilled (expected all rejected).`,MAJORITY_ERROR:`Majority condition failed: ${r}/${l} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${r}/${l} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${l-r}/${l} promises rejected (expected all to fail).`}[t],a=s.length>0?`\n失败原因:${s.map((e,t)=>`[${t+1}] ${e}`).join("\n")}`:"";return new e(t,i+a,n)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}countRejected(e){return e.filter(e=>"rejected"===e.status).length}}class l extends r{async execute(e,r={}){try{return await Promise.all(e)}catch(r){throw t("AND_ERROR",0,e.length,[...e],r)}}}class n extends r{async execute(e,r={}){try{return await Promise.any(e)}catch(r){throw t("OR_ERROR",0,e.length,[],r)}}}class s extends r{async execute(e,r={}){const l=await Promise.allSettled(e),n=this.filterFulfilledResults(l),s=this.filterRejectedResults(l),i=n.length,a=l.length;if(1===i)return n[0];throw t("XOR_ERROR",i,a,l,s)}}class i extends r{async execute(e,r={}){const l=await Promise.allSettled(e),n=this.filterFulfilledResults(l),s=n.length,i=l.length;if(s===i)throw t("NAND_ERROR",s,i,l,n);return n}}class a extends r{async execute(e,r={}){const l=await Promise.allSettled(e),n=this.filterFulfilledResults(l),s=n.length,i=l.length;if(0===s)return[];throw t("NOR_ERROR",s,i,l,n)}}class o extends r{async execute(e,r={}){const l=await Promise.allSettled(e),n=this.filterFulfilledResults(l),s=n.length,i=l.length;if(0===s||s===i)return n;throw t("XNOR_ERROR",s,i,l,n)}}class c extends r{async execute(e,r={max:.5}){const l=await Promise.allSettled(e),n=this.filterFulfilledResults(l),s=n.length,i=l.length;if(s>Math.floor(i*r.max))return n;throw t("MAJORITY_ERROR",s,i,l)}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let l=0,n=0;const s=[...e],i=s?.length??0;0!==i?s.forEach((e,s)=>{Promise.resolve(e).then(e=>{n++,r[s]=e}).catch(()=>{r[s]=void 0}).finally(()=>{l++,n>0?t(r.filter(e=>void 0!==e)):l===i&&t([])})}):t(r)})}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let l=0,n=0;const s=[...e],i=s?.length??0;0!==i?s.forEach((e,s)=>{Promise.resolve(e).then(()=>{r[s]=void 0}).catch(e=>{n++,r[s]=e}).finally(()=>{l++,n>0?t(r.filter(e=>void 0!==e)):l===i&&t([])})}):t(r)})}}class f{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;return Promise.race([this.promise,new Promise((l,n)=>{r=setTimeout(()=>{n(new Error(t))},e)})]).finally(()=>clearTimeout(r))}then(e,t){return new f(this.promise.then(e,t))}catch(e){return new f(this.promise.catch(e))}finally(e){return new f(this.promise.finally(e))}toPromise(){return this.promise}}class h{static get gates(){return{and:new l,or:new n,xor:new s,nand:new i,nor:new a,xnor:new o,majority:new c,allFulfilled:new u,allRejected:new d}}static and(e){return new f(this.gates.and.execute(e))}static or(e){return new f(this.gates.or.execute(e))}static not(e){return new f(Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e)))}static race(e){return new f(Promise.race(e).then(e=>Promise.resolve(e)))}static allSettled(e){return new f(Promise.allSettled(e))}static xor(e){return new f(this.gates.xor.execute(e))}static nand(e){return new f(this.gates.nand.execute(e))}static nor(e){return new f(this.gates.nor.execute(e))}static xnor(e){return new f(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new f(this.gates.majority.execute(e,t))}static allFulfilled(e){return new f(this.gates.allFulfilled.execute(e))}static allRejected(e){return new f(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,l=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),l=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(l=new Promise(e=>{r=e})),l),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const l=()=>{t===e?r(t):this.waitForChange().then(l)};l()})}}}}exports.createPromiseLogic=function(e={}){const{prefix:t="",suffix:r="",rename:l={}}=e,n={and:h.and.bind(h),or:h.or.bind(h),race:h.race.bind(h),allSettled:h.allSettled.bind(h),xor:h.xor.bind(h),not:h.not.bind(h),nand:h.nand.bind(h),nor:h.nor.bind(h),xnor:h.xnor.bind(h),majority:h.majority.bind(h),allFulfilled:h.allFulfilled.bind(h),allRejected:h.allRejected.bind(h)},s={};return Object.entries(n).forEach(([e,n])=>{const i=l[e]||e;s[`${t}${i}${r}`]=n}),s};
1
+ "use strict";class e extends Error{constructor(e,t,r,s){super(t),this.name="PromiseLogicError",this.type=e,this.results=r,this.errors=s}}function t(t,r,s,n){return new e(t,r,s,n)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}countRejected(e){return e.filter(e=>"rejected"===e.status).length}}class s extends r{async execute(e,r){try{return await Promise.all(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"AND condition failed: at least one promise rejected";throw t(r.errorType,l,n,s)}}}class n extends r{async execute(e,r){try{return await Promise.any(e)}catch(e){const s=r.errorMessage||"OR condition failed: all promises rejected.";throw t(r.errorType,s,[],[e])}}}class l extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=this.filterRejectedResults(s),a=n.length,i=s.length;if(1===a)return n[0];{const e=r.errorMessage||(a>1?`XOR condition failed: ${a} promises fulfilled (expected exactly 1)`:`XOR condition failed: all ${i} promises rejected (expected exactly 1)`);throw t(r.errorType,e,s,l)}}}class a extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,a=s.length;if(0===a)return[];if(l===a){const e=r.errorMessage||`NAND condition failed: ${l}/${a} fulfilled (need not majority)`;throw t(r.errorType,e,s,n)}return n}}class i extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length;if(0===l)return[];{const e=r.errorMessage||`NOR condition failed: ${l} promises fulfilled (expected all rejected)`;throw t(r.errorType,e,s,n)}}}class o extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,a=s.length;if(0===l||l===a)return n;{const e=r.errorMessage||`XNOR condition failed: ${l}/${a} promises fulfilled (expected all or none)`;throw t(r.errorType,e,s,n)}}}class c extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,a=s.length;if(0===a)return[];if(l>Math.floor(a*r.max))return n;{const e=r.errorMessage||`MAJORITY condition failed: ${l}/${a} fulfilled (need majority)`;throw t(r.errorType,e,s,n)}}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0;const n=[...e],l=n?.length??0;let a=!1;0!==l?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r[n]=e,a=!0,t(r.filter(Boolean))}).catch(()=>{}).finally(()=>{s++,s!==l||a||t([])})}):t([])})}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0;const n=[...e],l=n?.length??0;let a=!1;0!==l?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{}).catch(e=>{r[n]=e,a=!0,t(r.filter(Boolean))}).finally(()=>{s++,s!==l||a||t([])})}):t([])})}}class h extends r{async execute(e,r){try{return await Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e))}catch(e){throw t(r.errorType,r.errorMessage||"NOT condition failed",[],e)}}}class f extends r{async execute(e,r){try{return await Promise.allSettled(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"ALL_SETTLED condition failed: at least one promise rejected";throw t(r.errorType,l,n,s)}}}class m extends r{async execute(e,r){if(0!==e.length)try{return await Promise.race(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"RACE condition failed: all promises rejected";throw t(r.errorType,l,n,s)}}}class w{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;return Promise.race([this.promise,new Promise((s,n)=>{r=setTimeout(()=>{n(new Error(t))},e)})]).finally(()=>clearTimeout(r))}then(e,t){return new w(this.promise.then(e,t))}catch(e){return new w(this.promise.catch(e))}finally(e){return new w(this.promise.finally(e))}toPromise(){return this.promise}}class x{static get gates(){return{and:new s,or:new n,xor:new l,nand:new a,nor:new i,xnor:new o,not:new h,race:new m,allSettled:new f,majority:new c,allFulfilled:new d,allRejected:new u}}static and(e,t={errorType:"AND_ERROR",errorMessage:""}){return new w(this.gates.and.execute(e,t))}static or(e,t={errorType:"OR_ERROR",errorMessage:""}){return new w(this.gates.or.execute(e,t))}static not(e,t={errorType:"NOT_ERROR",errorMessage:""}){return new w(this.gates.not.execute(e,t))}static race(e,t={errorType:"RACE_ERROR",errorMessage:""}){return new w(this.gates.race.execute(e,t))}static allSettled(e,t={errorType:"ALL_SETTLED_ERROR",errorMessage:""}){return new w(this.gates.allSettled.execute(e,t))}static xor(e,t={errorType:"XOR_ERROR",errorMessage:""}){return new w(this.gates.xor.execute(e,t))}static nand(e,t={errorType:"NAND_ERROR",errorMessage:""}){return new w(this.gates.nand.execute(e,t))}static nor(e,t={errorType:"NOR_ERROR",errorMessage:""}){return new w(this.gates.nor.execute(e,t))}static xnor(e,t={errorType:"XNOR_ERROR",errorMessage:""}){return new w(this.gates.xnor.execute(e,t))}static majority(e,t={max:.5,errorType:"MAJORITY_ERROR",errorMessage:""}){return new w(this.gates.majority.execute(e,t))}static allFulfilled(e){return new w(this.gates.allFulfilled.execute(e))}static allRejected(e){return new w(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,s=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),s=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(s=new Promise(e=>{r=e})),s),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const s=()=>{t===e?r(t):this.waitForChange().then(s)};s()})}}}}exports.createPromiseLogic=function(e={}){const{prefix:t="",suffix:r="",rename:s={}}=e,n={and:x.and.bind(x),or:x.or.bind(x),race:x.race.bind(x),allSettled:x.allSettled.bind(x),xor:x.xor.bind(x),not:x.not.bind(x),nand:x.nand.bind(x),nor:x.nor.bind(x),xnor:x.xnor.bind(x),majority:x.majority.bind(x),allFulfilled:x.allFulfilled.bind(x),allRejected:x.allRejected.bind(x)},l={};return Object.entries(n).forEach(([e,n])=>{const a=s[e]||e;l[`${t}${a}${r}`]=n}),l};
@@ -1 +1 @@
1
- class e extends Error{constructor(e,t,l){super(t),this.name="PromiseLogicError",this.type=e,this.results=l}}function t(t,l,r,n,s){const i={XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${l} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${r} promises fulfilled (expected at least one rejection).`,NOT_ERROR:"NOT condition failed: promise resolved (expected rejection).",NOR_ERROR:`NOR condition failed: ${l} promises fulfilled (expected all rejected).`,MAJORITY_ERROR:`Majority condition failed: ${l}/${r} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${l}/${r} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${r-l}/${r} promises rejected (expected all to fail).`}[t],a=s.length>0?`\n失败原因:${s.map((e,t)=>`[${t+1}] ${e}`).join("\n")}`:"";return new e(t,i+a,n)}class l{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}countRejected(e){return e.filter(e=>"rejected"===e.status).length}}class r extends l{async execute(e,l={}){try{return await Promise.all(e)}catch(l){throw t("AND_ERROR",0,e.length,[...e],l)}}}class n extends l{async execute(e,l={}){try{return await Promise.any(e)}catch(l){throw t("OR_ERROR",0,e.length,[],l)}}}class s extends l{async execute(e,l={}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=this.filterRejectedResults(r),i=n.length,a=r.length;if(1===i)return n[0];throw t("XOR_ERROR",i,a,r,s)}}class i extends l{async execute(e,l={}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=n.length,i=r.length;if(s===i)throw t("NAND_ERROR",s,i,r,n);return n}}class a extends l{async execute(e,l={}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=n.length,i=r.length;if(0===s)return[];throw t("NOR_ERROR",s,i,r,n)}}class o extends l{async execute(e,l={}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=n.length,i=r.length;if(0===s||s===i)return n;throw t("XNOR_ERROR",s,i,r,n)}}class c extends l{async execute(e,l={max:.5}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=n.length,i=r.length;if(s>Math.floor(i*l.max))return n;throw t("MAJORITY_ERROR",s,i,r)}}class u extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let r=0,n=0;const s=[...e],i=s?.length??0;0!==i?s.forEach((e,s)=>{Promise.resolve(e).then(e=>{n++,l[s]=e}).catch(()=>{l[s]=void 0}).finally(()=>{r++,n>0?t(l.filter(e=>void 0!==e)):r===i&&t([])})}):t(l)})}}class d extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let r=0,n=0;const s=[...e],i=s?.length??0;0!==i?s.forEach((e,s)=>{Promise.resolve(e).then(()=>{l[s]=void 0}).catch(e=>{n++,l[s]=e}).finally(()=>{r++,n>0?t(l.filter(e=>void 0!==e)):r===i&&t([])})}):t(l)})}}class f{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let l;return Promise.race([this.promise,new Promise((r,n)=>{l=setTimeout(()=>{n(new Error(t))},e)})]).finally(()=>clearTimeout(l))}then(e,t){return new f(this.promise.then(e,t))}catch(e){return new f(this.promise.catch(e))}finally(e){return new f(this.promise.finally(e))}toPromise(){return this.promise}}class h{static get gates(){return{and:new r,or:new n,xor:new s,nand:new i,nor:new a,xnor:new o,majority:new c,allFulfilled:new u,allRejected:new d}}static and(e){return new f(this.gates.and.execute(e))}static or(e){return new f(this.gates.or.execute(e))}static not(e){return new f(Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e)))}static race(e){return new f(Promise.race(e).then(e=>Promise.resolve(e)))}static allSettled(e){return new f(Promise.allSettled(e))}static xor(e){return new f(this.gates.xor.execute(e))}static nand(e){return new f(this.gates.nand.execute(e))}static nor(e){return new f(this.gates.nor.execute(e))}static xnor(e){return new f(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new f(this.gates.majority.execute(e,t))}static allFulfilled(e){return new f(this.gates.allFulfilled.execute(e))}static allRejected(e){return new f(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,l=null,r=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,l&&(l(t),l=null),r=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(l||(r=new Promise(e=>{l=e})),r),waitFor(e){return t===e?Promise.resolve(t):new Promise(l=>{const r=()=>{t===e?l(t):this.waitForChange().then(r)};r()})}}}}function R(e={}){const{prefix:t="",suffix:l="",rename:r={}}=e,n={and:h.and.bind(h),or:h.or.bind(h),race:h.race.bind(h),allSettled:h.allSettled.bind(h),xor:h.xor.bind(h),not:h.not.bind(h),nand:h.nand.bind(h),nor:h.nor.bind(h),xnor:h.xnor.bind(h),majority:h.majority.bind(h),allFulfilled:h.allFulfilled.bind(h),allRejected:h.allRejected.bind(h)},s={};return Object.entries(n).forEach(([e,n])=>{const i=r[e]||e;s[`${t}${i}${l}`]=n}),s}export{R as createPromiseLogic};
1
+ class e extends Error{constructor(e,t,r,s){super(t),this.name="PromiseLogicError",this.type=e,this.results=r,this.errors=s}}function t(t,r,s,n){return new e(t,r,s,n)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}countRejected(e){return e.filter(e=>"rejected"===e.status).length}}class s extends r{async execute(e,r){try{return await Promise.all(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"AND condition failed: at least one promise rejected";throw t(r.errorType,l,n,s)}}}class n extends r{async execute(e,r){try{return await Promise.any(e)}catch(e){const s=r.errorMessage||"OR condition failed: all promises rejected.";throw t(r.errorType,s,[],[e])}}}class l extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=this.filterRejectedResults(s),a=n.length,o=s.length;if(1===a)return n[0];{const e=r.errorMessage||(a>1?`XOR condition failed: ${a} promises fulfilled (expected exactly 1)`:`XOR condition failed: all ${o} promises rejected (expected exactly 1)`);throw t(r.errorType,e,s,l)}}}class a extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,a=s.length;if(0===a)return[];if(l===a){const e=r.errorMessage||`NAND condition failed: ${l}/${a} fulfilled (need not majority)`;throw t(r.errorType,e,s,n)}return n}}class o extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length;if(0===l)return[];{const e=r.errorMessage||`NOR condition failed: ${l} promises fulfilled (expected all rejected)`;throw t(r.errorType,e,s,n)}}}class i extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,a=s.length;if(0===l||l===a)return n;{const e=r.errorMessage||`XNOR condition failed: ${l}/${a} promises fulfilled (expected all or none)`;throw t(r.errorType,e,s,n)}}}class c extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,a=s.length;if(0===a)return[];if(l>Math.floor(a*r.max))return n;{const e=r.errorMessage||`MAJORITY condition failed: ${l}/${a} fulfilled (need majority)`;throw t(r.errorType,e,s,n)}}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0;const n=[...e],l=n?.length??0;let a=!1;0!==l?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r[n]=e,a=!0,t(r.filter(Boolean))}).catch(()=>{}).finally(()=>{s++,s!==l||a||t([])})}):t([])})}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0;const n=[...e],l=n?.length??0;let a=!1;0!==l?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{}).catch(e=>{r[n]=e,a=!0,t(r.filter(Boolean))}).finally(()=>{s++,s!==l||a||t([])})}):t([])})}}class h extends r{async execute(e,r){try{return await Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e))}catch(e){throw t(r.errorType,r.errorMessage||"NOT condition failed",[],e)}}}class f extends r{async execute(e,r){try{return await Promise.allSettled(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"ALL_SETTLED condition failed: at least one promise rejected";throw t(r.errorType,l,n,s)}}}class m extends r{async execute(e,r){if(0!==e.length)try{return await Promise.race(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"RACE condition failed: all promises rejected";throw t(r.errorType,l,n,s)}}}class w{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;return Promise.race([this.promise,new Promise((s,n)=>{r=setTimeout(()=>{n(new Error(t))},e)})]).finally(()=>clearTimeout(r))}then(e,t){return new w(this.promise.then(e,t))}catch(e){return new w(this.promise.catch(e))}finally(e){return new w(this.promise.finally(e))}toPromise(){return this.promise}}class x{static get gates(){return{and:new s,or:new n,xor:new l,nand:new a,nor:new o,xnor:new i,not:new h,race:new m,allSettled:new f,majority:new c,allFulfilled:new d,allRejected:new u}}static and(e,t={errorType:"AND_ERROR",errorMessage:""}){return new w(this.gates.and.execute(e,t))}static or(e,t={errorType:"OR_ERROR",errorMessage:""}){return new w(this.gates.or.execute(e,t))}static not(e,t={errorType:"NOT_ERROR",errorMessage:""}){return new w(this.gates.not.execute(e,t))}static race(e,t={errorType:"RACE_ERROR",errorMessage:""}){return new w(this.gates.race.execute(e,t))}static allSettled(e,t={errorType:"ALL_SETTLED_ERROR",errorMessage:""}){return new w(this.gates.allSettled.execute(e,t))}static xor(e,t={errorType:"XOR_ERROR",errorMessage:""}){return new w(this.gates.xor.execute(e,t))}static nand(e,t={errorType:"NAND_ERROR",errorMessage:""}){return new w(this.gates.nand.execute(e,t))}static nor(e,t={errorType:"NOR_ERROR",errorMessage:""}){return new w(this.gates.nor.execute(e,t))}static xnor(e,t={errorType:"XNOR_ERROR",errorMessage:""}){return new w(this.gates.xnor.execute(e,t))}static majority(e,t={max:.5,errorType:"MAJORITY_ERROR",errorMessage:""}){return new w(this.gates.majority.execute(e,t))}static allFulfilled(e){return new w(this.gates.allFulfilled.execute(e))}static allRejected(e){return new w(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,s=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),s=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(s=new Promise(e=>{r=e})),s),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const s=()=>{t===e?r(t):this.waitForChange().then(s)};s()})}}}}function R(e={}){const{prefix:t="",suffix:r="",rename:s={}}=e,n={and:x.and.bind(x),or:x.or.bind(x),race:x.race.bind(x),allSettled:x.allSettled.bind(x),xor:x.xor.bind(x),not:x.not.bind(x),nand:x.nand.bind(x),nor:x.nor.bind(x),xnor:x.xnor.bind(x),majority:x.majority.bind(x),allFulfilled:x.allFulfilled.bind(x),allRejected:x.allRejected.bind(x)},l={};return Object.entries(n).forEach(([e,n])=>{const a=s[e]||e;l[`${t}${a}${r}`]=n}),l}export{R as createPromiseLogic};
package/dist/index.cjs.js CHANGED
@@ -1 +1 @@
1
- "use strict";class e extends Error{constructor(e,t,r){super(t),this.name="PromiseLogicError",this.type=e,this.results=r}}function t(t,r,l,s,n){const i={XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${r} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${l} promises fulfilled (expected at least one rejection).`,NOT_ERROR:"NOT condition failed: promise resolved (expected rejection).",NOR_ERROR:`NOR condition failed: ${r} promises fulfilled (expected all rejected).`,MAJORITY_ERROR:`Majority condition failed: ${r}/${l} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${r}/${l} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${l-r}/${l} promises rejected (expected all to fail).`}[t],o=n.length>0?`\n失败原因:${n.map((e,t)=>`[${t+1}] ${e}`).join("\n")}`:"";return new e(t,i+o,s)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}countRejected(e){return e.filter(e=>"rejected"===e.status).length}}class l extends r{async execute(e,r={}){try{return await Promise.all(e)}catch(r){throw t("AND_ERROR",0,e.length,[...e],r)}}}class s extends r{async execute(e,r={}){try{return await Promise.any(e)}catch(r){throw t("OR_ERROR",0,e.length,[],r)}}}class n extends r{async execute(e,r={}){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),n=this.filterRejectedResults(l),i=s.length,o=l.length;if(1===i)return s[0];throw t("XOR_ERROR",i,o,l,n)}}class i extends r{async execute(e,r={}){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),n=s.length,i=l.length;if(n===i)throw t("NAND_ERROR",n,i,l,s);return s}}class o extends r{async execute(e,r={}){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),n=s.length,i=l.length;if(0===n)return[];throw t("NOR_ERROR",n,i,l,s)}}class a extends r{async execute(e,r={}){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),n=s.length,i=l.length;if(0===n||n===i)return s;throw t("XNOR_ERROR",n,i,l,s)}}class c extends r{async execute(e,r={max:.5}){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),n=s.length,i=l.length;if(n>Math.floor(i*r.max))return s;throw t("MAJORITY_ERROR",n,i,l)}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let l=0,s=0;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{s++,r[n]=e}).catch(()=>{r[n]=void 0}).finally(()=>{l++,s>0?t(r.filter(e=>void 0!==e)):l===i&&t([])})}):t(r)})}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let l=0,s=0;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{r[n]=void 0}).catch(e=>{s++,r[n]=e}).finally(()=>{l++,s>0?t(r.filter(e=>void 0!==e)):l===i&&t([])})}):t(r)})}}class f{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;return Promise.race([this.promise,new Promise((l,s)=>{r=setTimeout(()=>{s(new Error(t))},e)})]).finally(()=>clearTimeout(r))}then(e,t){return new f(this.promise.then(e,t))}catch(e){return new f(this.promise.catch(e))}finally(e){return new f(this.promise.finally(e))}toPromise(){return this.promise}}class h{static get gates(){return{and:new l,or:new s,xor:new n,nand:new i,nor:new o,xnor:new a,majority:new c,allFulfilled:new u,allRejected:new d}}static and(e){return new f(this.gates.and.execute(e))}static or(e){return new f(this.gates.or.execute(e))}static not(e){return new f(Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e)))}static race(e){return new f(Promise.race(e).then(e=>Promise.resolve(e)))}static allSettled(e){return new f(Promise.allSettled(e))}static xor(e){return new f(this.gates.xor.execute(e))}static nand(e){return new f(this.gates.nand.execute(e))}static nor(e){return new f(this.gates.nor.execute(e))}static xnor(e){return new f(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new f(this.gates.majority.execute(e,t))}static allFulfilled(e){return new f(this.gates.allFulfilled.execute(e))}static allRejected(e){return new f(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,l=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),l=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(l=new Promise(e=>{r=e})),l),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const l=()=>{t===e?r(t):this.waitForChange().then(l)};l()})}}}}exports.PromiseLogic=h,exports.PromiseLogicError=e,exports.PromiseWithTimer=f,exports.createLogicError=t,exports.createPromiseLogic=function(e={}){const{prefix:t="",suffix:r="",rename:l={}}=e,s={and:h.and.bind(h),or:h.or.bind(h),race:h.race.bind(h),allSettled:h.allSettled.bind(h),xor:h.xor.bind(h),not:h.not.bind(h),nand:h.nand.bind(h),nor:h.nor.bind(h),xnor:h.xnor.bind(h),majority:h.majority.bind(h),allFulfilled:h.allFulfilled.bind(h),allRejected:h.allRejected.bind(h)},n={};return Object.entries(s).forEach(([e,s])=>{const i=l[e]||e;n[`${t}${i}${r}`]=s}),n};
1
+ "use strict";class e extends Error{constructor(e,t,r,s){super(t),this.name="PromiseLogicError",this.type=e,this.results=r,this.errors=s}}function t(t,r,s,n){return new e(t,r,s,n)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}countRejected(e){return e.filter(e=>"rejected"===e.status).length}}class s extends r{async execute(e,r){try{return await Promise.all(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"AND condition failed: at least one promise rejected";throw t(r.errorType,l,n,s)}}}class n extends r{async execute(e,r){try{return await Promise.any(e)}catch(e){const s=r.errorMessage||"OR condition failed: all promises rejected.";throw t(r.errorType,s,[],[e])}}}class l extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=this.filterRejectedResults(s),o=n.length,i=s.length;if(1===o)return n[0];{const e=r.errorMessage||(o>1?`XOR condition failed: ${o} promises fulfilled (expected exactly 1)`:`XOR condition failed: all ${i} promises rejected (expected exactly 1)`);throw t(r.errorType,e,s,l)}}}class o extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,o=s.length;if(0===o)return[];if(l===o){const e=r.errorMessage||`NAND condition failed: ${l}/${o} fulfilled (need not majority)`;throw t(r.errorType,e,s,n)}return n}}class i extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length;if(0===l)return[];{const e=r.errorMessage||`NOR condition failed: ${l} promises fulfilled (expected all rejected)`;throw t(r.errorType,e,s,n)}}}class a extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,o=s.length;if(0===l||l===o)return n;{const e=r.errorMessage||`XNOR condition failed: ${l}/${o} promises fulfilled (expected all or none)`;throw t(r.errorType,e,s,n)}}}class c extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,o=s.length;if(0===o)return[];if(l>Math.floor(o*r.max))return n;{const e=r.errorMessage||`MAJORITY condition failed: ${l}/${o} fulfilled (need majority)`;throw t(r.errorType,e,s,n)}}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0;const n=[...e],l=n?.length??0;let o=!1;0!==l?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r[n]=e,o=!0,t(r.filter(Boolean))}).catch(()=>{}).finally(()=>{s++,s!==l||o||t([])})}):t([])})}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0;const n=[...e],l=n?.length??0;let o=!1;0!==l?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{}).catch(e=>{r[n]=e,o=!0,t(r.filter(Boolean))}).finally(()=>{s++,s!==l||o||t([])})}):t([])})}}class h extends r{async execute(e,r){try{return await Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e))}catch(e){throw t(r.errorType,r.errorMessage||"NOT condition failed",[],e)}}}class f extends r{async execute(e,r){try{return await Promise.allSettled(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"ALL_SETTLED condition failed: at least one promise rejected";throw t(r.errorType,l,n,s)}}}class m extends r{async execute(e,r){if(0!==e.length)try{return await Promise.race(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"RACE condition failed: all promises rejected";throw t(r.errorType,l,n,s)}}}class x{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;return Promise.race([this.promise,new Promise((s,n)=>{r=setTimeout(()=>{n(new Error(t))},e)})]).finally(()=>clearTimeout(r))}then(e,t){return new x(this.promise.then(e,t))}catch(e){return new x(this.promise.catch(e))}finally(e){return new x(this.promise.finally(e))}toPromise(){return this.promise}}class w{static get gates(){return{and:new s,or:new n,xor:new l,nand:new o,nor:new i,xnor:new a,not:new h,race:new m,allSettled:new f,majority:new c,allFulfilled:new d,allRejected:new u}}static and(e,t={errorType:"AND_ERROR",errorMessage:""}){return new x(this.gates.and.execute(e,t))}static or(e,t={errorType:"OR_ERROR",errorMessage:""}){return new x(this.gates.or.execute(e,t))}static not(e,t={errorType:"NOT_ERROR",errorMessage:""}){return new x(this.gates.not.execute(e,t))}static race(e,t={errorType:"RACE_ERROR",errorMessage:""}){return new x(this.gates.race.execute(e,t))}static allSettled(e,t={errorType:"ALL_SETTLED_ERROR",errorMessage:""}){return new x(this.gates.allSettled.execute(e,t))}static xor(e,t={errorType:"XOR_ERROR",errorMessage:""}){return new x(this.gates.xor.execute(e,t))}static nand(e,t={errorType:"NAND_ERROR",errorMessage:""}){return new x(this.gates.nand.execute(e,t))}static nor(e,t={errorType:"NOR_ERROR",errorMessage:""}){return new x(this.gates.nor.execute(e,t))}static xnor(e,t={errorType:"XNOR_ERROR",errorMessage:""}){return new x(this.gates.xnor.execute(e,t))}static majority(e,t={max:.5,errorType:"MAJORITY_ERROR",errorMessage:""}){return new x(this.gates.majority.execute(e,t))}static allFulfilled(e){return new x(this.gates.allFulfilled.execute(e))}static allRejected(e){return new x(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,s=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),s=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(s=new Promise(e=>{r=e})),s),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const s=()=>{t===e?r(t):this.waitForChange().then(s)};s()})}}}}exports.PromiseLogic=w,exports.PromiseLogicError=e,exports.PromiseWithTimer=x,exports.createLogicError=t,exports.createPromiseLogic=function(e={}){const{prefix:t="",suffix:r="",rename:s={}}=e,n={and:w.and.bind(w),or:w.or.bind(w),race:w.race.bind(w),allSettled:w.allSettled.bind(w),xor:w.xor.bind(w),not:w.not.bind(w),nand:w.nand.bind(w),nor:w.nor.bind(w),xnor:w.xnor.bind(w),majority:w.majority.bind(w),allFulfilled:w.allFulfilled.bind(w),allRejected:w.allRejected.bind(w)},l={};return Object.entries(n).forEach(([e,n])=>{const o=s[e]||e;l[`${t}${o}${r}`]=n}),l};
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- class e extends Error{constructor(e,t,l){super(t),this.name="PromiseLogicError",this.type=e,this.results=l}}function t(t,l,r,n,s){const i={XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${l} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${r} promises fulfilled (expected at least one rejection).`,NOT_ERROR:"NOT condition failed: promise resolved (expected rejection).",NOR_ERROR:`NOR condition failed: ${l} promises fulfilled (expected all rejected).`,MAJORITY_ERROR:`Majority condition failed: ${l}/${r} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${l}/${r} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${r-l}/${r} promises rejected (expected all to fail).`}[t],a=s.length>0?`\n失败原因:${s.map((e,t)=>`[${t+1}] ${e}`).join("\n")}`:"";return new e(t,i+a,n)}class l{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}countRejected(e){return e.filter(e=>"rejected"===e.status).length}}class r extends l{async execute(e,l={}){try{return await Promise.all(e)}catch(l){throw t("AND_ERROR",0,e.length,[...e],l)}}}class n extends l{async execute(e,l={}){try{return await Promise.any(e)}catch(l){throw t("OR_ERROR",0,e.length,[],l)}}}class s extends l{async execute(e,l={}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=this.filterRejectedResults(r),i=n.length,a=r.length;if(1===i)return n[0];throw t("XOR_ERROR",i,a,r,s)}}class i extends l{async execute(e,l={}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=n.length,i=r.length;if(s===i)throw t("NAND_ERROR",s,i,r,n);return n}}class a extends l{async execute(e,l={}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=n.length,i=r.length;if(0===s)return[];throw t("NOR_ERROR",s,i,r,n)}}class o extends l{async execute(e,l={}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=n.length,i=r.length;if(0===s||s===i)return n;throw t("XNOR_ERROR",s,i,r,n)}}class c extends l{async execute(e,l={max:.5}){const r=await Promise.allSettled(e),n=this.filterFulfilledResults(r),s=n.length,i=r.length;if(s>Math.floor(i*l.max))return n;throw t("MAJORITY_ERROR",s,i,r)}}class u extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let r=0,n=0;const s=[...e],i=s?.length??0;0!==i?s.forEach((e,s)=>{Promise.resolve(e).then(e=>{n++,l[s]=e}).catch(()=>{l[s]=void 0}).finally(()=>{r++,n>0?t(l.filter(e=>void 0!==e)):r===i&&t([])})}):t(l)})}}class d extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let r=0,n=0;const s=[...e],i=s?.length??0;0!==i?s.forEach((e,s)=>{Promise.resolve(e).then(()=>{l[s]=void 0}).catch(e=>{n++,l[s]=e}).finally(()=>{r++,n>0?t(l.filter(e=>void 0!==e)):r===i&&t([])})}):t(l)})}}class f{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let l;return Promise.race([this.promise,new Promise((r,n)=>{l=setTimeout(()=>{n(new Error(t))},e)})]).finally(()=>clearTimeout(l))}then(e,t){return new f(this.promise.then(e,t))}catch(e){return new f(this.promise.catch(e))}finally(e){return new f(this.promise.finally(e))}toPromise(){return this.promise}}class h{static get gates(){return{and:new r,or:new n,xor:new s,nand:new i,nor:new a,xnor:new o,majority:new c,allFulfilled:new u,allRejected:new d}}static and(e){return new f(this.gates.and.execute(e))}static or(e){return new f(this.gates.or.execute(e))}static not(e){return new f(Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e)))}static race(e){return new f(Promise.race(e).then(e=>Promise.resolve(e)))}static allSettled(e){return new f(Promise.allSettled(e))}static xor(e){return new f(this.gates.xor.execute(e))}static nand(e){return new f(this.gates.nand.execute(e))}static nor(e){return new f(this.gates.nor.execute(e))}static xnor(e){return new f(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new f(this.gates.majority.execute(e,t))}static allFulfilled(e){return new f(this.gates.allFulfilled.execute(e))}static allRejected(e){return new f(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,l=null,r=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,l&&(l(t),l=null),r=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(l||(r=new Promise(e=>{l=e})),r),waitFor(e){return t===e?Promise.resolve(t):new Promise(l=>{const r=()=>{t===e?l(t):this.waitForChange().then(r)};r()})}}}}function R(e={}){const{prefix:t="",suffix:l="",rename:r={}}=e,n={and:h.and.bind(h),or:h.or.bind(h),race:h.race.bind(h),allSettled:h.allSettled.bind(h),xor:h.xor.bind(h),not:h.not.bind(h),nand:h.nand.bind(h),nor:h.nor.bind(h),xnor:h.xnor.bind(h),majority:h.majority.bind(h),allFulfilled:h.allFulfilled.bind(h),allRejected:h.allRejected.bind(h)},s={};return Object.entries(n).forEach(([e,n])=>{const i=r[e]||e;s[`${t}${i}${l}`]=n}),s}export{h as PromiseLogic,e as PromiseLogicError,f as PromiseWithTimer,t as createLogicError,R as createPromiseLogic};
1
+ class e extends Error{constructor(e,t,r,s){super(t),this.name="PromiseLogicError",this.type=e,this.results=r,this.errors=s}}function t(t,r,s,n){return new e(t,r,s,n)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}countRejected(e){return e.filter(e=>"rejected"===e.status).length}}class s extends r{async execute(e,r){try{return await Promise.all(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"AND condition failed: at least one promise rejected";throw t(r.errorType,l,n,s)}}}class n extends r{async execute(e,r){try{return await Promise.any(e)}catch(e){const s=r.errorMessage||"OR condition failed: all promises rejected.";throw t(r.errorType,s,[],[e])}}}class l extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=this.filterRejectedResults(s),a=n.length,o=s.length;if(1===a)return n[0];{const e=r.errorMessage||(a>1?`XOR condition failed: ${a} promises fulfilled (expected exactly 1)`:`XOR condition failed: all ${o} promises rejected (expected exactly 1)`);throw t(r.errorType,e,s,l)}}}class a extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,a=s.length;if(0===a)return[];if(l===a){const e=r.errorMessage||`NAND condition failed: ${l}/${a} fulfilled (need not majority)`;throw t(r.errorType,e,s,n)}return n}}class o extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length;if(0===l)return[];{const e=r.errorMessage||`NOR condition failed: ${l} promises fulfilled (expected all rejected)`;throw t(r.errorType,e,s,n)}}}class i extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,a=s.length;if(0===l||l===a)return n;{const e=r.errorMessage||`XNOR condition failed: ${l}/${a} promises fulfilled (expected all or none)`;throw t(r.errorType,e,s,n)}}}class c extends r{async execute(e,r){const s=await Promise.allSettled(e),n=this.filterFulfilledResults(s),l=n.length,a=s.length;if(0===a)return[];if(l>Math.floor(a*r.max))return n;{const e=r.errorMessage||`MAJORITY condition failed: ${l}/${a} fulfilled (need majority)`;throw t(r.errorType,e,s,n)}}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0;const n=[...e],l=n?.length??0;let a=!1;0!==l?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r[n]=e,a=!0,t(r.filter(Boolean))}).catch(()=>{}).finally(()=>{s++,s!==l||a||t([])})}):t([])})}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0;const n=[...e],l=n?.length??0;let a=!1;0!==l?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{}).catch(e=>{r[n]=e,a=!0,t(r.filter(Boolean))}).finally(()=>{s++,s!==l||a||t([])})}):t([])})}}class h extends r{async execute(e,r){try{return await Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e))}catch(e){throw t(r.errorType,r.errorMessage||"NOT condition failed",[],e)}}}class f extends r{async execute(e,r){try{return await Promise.allSettled(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"ALL_SETTLED condition failed: at least one promise rejected";throw t(r.errorType,l,n,s)}}}class m extends r{async execute(e,r){if(0!==e.length)try{return await Promise.race(e)}catch(s){const n=await Promise.allSettled(e),l=r.errorMessage||"RACE condition failed: all promises rejected";throw t(r.errorType,l,n,s)}}}class w{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;return Promise.race([this.promise,new Promise((s,n)=>{r=setTimeout(()=>{n(new Error(t))},e)})]).finally(()=>clearTimeout(r))}then(e,t){return new w(this.promise.then(e,t))}catch(e){return new w(this.promise.catch(e))}finally(e){return new w(this.promise.finally(e))}toPromise(){return this.promise}}class x{static get gates(){return{and:new s,or:new n,xor:new l,nand:new a,nor:new o,xnor:new i,not:new h,race:new m,allSettled:new f,majority:new c,allFulfilled:new d,allRejected:new u}}static and(e,t={errorType:"AND_ERROR",errorMessage:""}){return new w(this.gates.and.execute(e,t))}static or(e,t={errorType:"OR_ERROR",errorMessage:""}){return new w(this.gates.or.execute(e,t))}static not(e,t={errorType:"NOT_ERROR",errorMessage:""}){return new w(this.gates.not.execute(e,t))}static race(e,t={errorType:"RACE_ERROR",errorMessage:""}){return new w(this.gates.race.execute(e,t))}static allSettled(e,t={errorType:"ALL_SETTLED_ERROR",errorMessage:""}){return new w(this.gates.allSettled.execute(e,t))}static xor(e,t={errorType:"XOR_ERROR",errorMessage:""}){return new w(this.gates.xor.execute(e,t))}static nand(e,t={errorType:"NAND_ERROR",errorMessage:""}){return new w(this.gates.nand.execute(e,t))}static nor(e,t={errorType:"NOR_ERROR",errorMessage:""}){return new w(this.gates.nor.execute(e,t))}static xnor(e,t={errorType:"XNOR_ERROR",errorMessage:""}){return new w(this.gates.xnor.execute(e,t))}static majority(e,t={max:.5,errorType:"MAJORITY_ERROR",errorMessage:""}){return new w(this.gates.majority.execute(e,t))}static allFulfilled(e){return new w(this.gates.allFulfilled.execute(e))}static allRejected(e){return new w(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,s=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),s=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(s=new Promise(e=>{r=e})),s),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const s=()=>{t===e?r(t):this.waitForChange().then(s)};s()})}}}}function R(e={}){const{prefix:t="",suffix:r="",rename:s={}}=e,n={and:x.and.bind(x),or:x.or.bind(x),race:x.race.bind(x),allSettled:x.allSettled.bind(x),xor:x.xor.bind(x),not:x.not.bind(x),nand:x.nand.bind(x),nor:x.nor.bind(x),xnor:x.xnor.bind(x),majority:x.majority.bind(x),allFulfilled:x.allFulfilled.bind(x),allRejected:x.allRejected.bind(x)},l={};return Object.entries(n).forEach(([e,n])=>{const a=s[e]||e;l[`${t}${a}${r}`]=n}),l}export{x as PromiseLogic,e as PromiseLogicError,w as PromiseWithTimer,t as createLogicError,R as createPromiseLogic};
@@ -1,5 +1,5 @@
1
1
  declare class PromiseWithTimer<T> {
2
- maxTimer(ms: number): Promise<T>;
2
+ maxTimer(ms: number, errorMessage?: string): Promise<T>;
3
3
  then<U>(onfulfilled?: ((value: T) => U | PromiseLike<U>) | null, onrejected?: ((reason: Error) => U | PromiseLike<U>) | null): PromiseWithTimer<U>;
4
4
  catch<U>(onrejected?: ((reason: Error) => U | PromiseLike<U>) | null): PromiseWithTimer<U>;
5
5
  finally(onfinally?: (() => void) | null): PromiseWithTimer<T>;
@@ -7,11 +7,18 @@ declare class PromiseWithTimer<T> {
7
7
  }
8
8
 
9
9
  declare class PromiseLogicError extends Error {
10
- type: 'XOR_ERROR' | 'NAND_ERROR' | 'NOR_ERROR' | 'XNOR_ERROR' | 'MAJORITY_ERROR' | 'ALL_SUCCESSFUL_ERROR' | 'ALL_FAILED_ERROR';
10
+ type: string;
11
11
  results: PromiseSettledResult<unknown>[];
12
12
  constructor(type: string, message: string, results: PromiseSettledResult<unknown>[]);
13
13
  }
14
14
 
15
+ interface LogicGateOptions {
16
+ errorType?: string;
17
+ errorMessage?: string;
18
+ max?: number;
19
+ [key: string]: string | number | boolean | undefined;
20
+ }
21
+
15
22
  interface FlipFlop {
16
23
  getState(): boolean;
17
24
  toggle(): Promise<boolean>;
@@ -19,20 +26,20 @@ interface FlipFlop {
19
26
  }
20
27
 
21
28
  declare class PromiseLogic {
22
- static and<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T[]>;
23
- static or<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T>;
24
- static race<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T>;
25
- static not<T>(promise: T | PromiseLike<T>): PromiseWithTimer<unknown>;
26
- static allSettled<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<PromiseSettledResult<T>[]>;
29
+ static and<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOption): PromiseWithTimer<T[]>;
30
+ static or<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T>;
31
+ static race<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T>;
32
+ static not<T>(promise: T | PromiseLike<T>, options?: LogicGateOptions): PromiseWithTimer<T>;
33
+ static allSettled<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<PromiseSettledResult<T>[]>;
27
34
 
28
- static xor<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T>;
29
- static nand<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T[]>;
30
- static nor<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T[]>;
31
- static xnor<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T[]>;
32
- static majority<T>(iterable: Iterable<T | PromiseLike<T>>, options?: { max: number }): PromiseWithTimer<T[]>;
35
+ static xor<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T>;
36
+ static nand<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
37
+ static nor<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
38
+ static xnor<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
39
+ static majority<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
33
40
 
34
41
  static allFulfilled<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T[]>;
35
- static allRejected<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<unknown[]>;
42
+ static allRejected<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<Error[]>;
36
43
 
37
44
  static createFlipFlop(initialState?: boolean): FlipFlop;
38
45
  }
@@ -50,4 +57,4 @@ declare function createPromiseLogic(options?: CreatePromiseLogicOptions): {
50
57
  declare function createLogicError(type: string, fulfilledCount: number, total: number, results: PromiseSettledResult<unknown>[]): PromiseLogicError;
51
58
 
52
59
  export { PromiseLogic, PromiseLogicError, PromiseWithTimer, createLogicError, createPromiseLogic };
53
- export type { CreatePromiseLogicOptions, FlipFlop };
60
+ export type { CreatePromiseLogicOptions, FlipFlop, LogicGateOptions };
@@ -1 +1 @@
1
- "use strict";class e extends Error{constructor(e,t,l){super(t),this.type=e,this.results=l,this.name="PromiseLogicError"}}function t(t,l,s,r,n){const i={XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${l} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${s} promises fulfilled (expected at least one rejection).`,NOR_ERROR:`NOR condition failed: ${l} promises fulfilled (expected all rejected).`,XNOR_ERROR:`XNOR condition failed: ${l}/${s} promises fulfilled (expected all or none).`,MAJORITY_ERROR:`Majority condition failed: ${l}/${s} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${l}/${s} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${s-l}/${s} promises rejected (expected all to fail).`}[t]||"Logic condition failed",a=n&&n?.length>0?`\n失败原因:${n.map((e,t)=>`[${t+1}] ${e}`).join("\n")}`:"";return new e(t,i+a,r)}class l{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}}class s extends l{async execute(e){try{return Promise.any(e)}catch(e){throw t("OR_ERROR",0,0,[],[e])}}}class r extends l{async execute(e){try{return Promise.all(e)}catch(e){throw t("AND_ERROR",0,0,[],[e])}}}class n extends l{async execute(e,l){const s=await Promise.allSettled(e),r=this.filterFulfilledResults(s),n=r.length,i=s.length,a=this.filterRejectedResults(s);if(n>Math.floor(i*l.max))return r;throw t("MAJORITY_ERROR",n,i,s,a)}}class i extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),r=s.length,n=l.length,i=this.filterRejectedResults(l);if(r===n)throw t("NAND_ERROR",r,n,l,i);return s}}class a extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l).length,r=l.length,n=this.filterRejectedResults(l);if(0===s)return[];throw t("NOR_ERROR",s,r,l,n)}}class o extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),r=s.length,n=l.length,i=this.filterRejectedResults(l);if(0===r||r===n)return s;throw t("XNOR_ERROR",r,n,l,i)}}class c extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),r=s.length,n=l.length,i=this.filterRejectedResults(l);if(1===r)return s[0];throw t("XOR_ERROR",r,n,l,i)}}class u extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let s=0,r=0;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r++,l[n]=e}).catch(()=>{l[n]=void 0}).finally(()=>{s++,r>0?t(l.filter(e=>void 0!==e)):s===i&&t([])})}):t(l)})}}class d extends l{async execute(e){return new Promise(t=>{const l=[];let s=0,r=0;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{l[n]=void 0}).catch(e=>{r++,l[n]=e}).finally(()=>{s++,r>0?t(l.filter(e=>void 0!==e)):s===i&&t([])})}):t(l)})}}class f{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let l;return Promise.race([this.promise,new Promise((s,r)=>{l=setTimeout(()=>{r(new Error(t))},e)})]).finally(()=>clearTimeout(l))}then(e,t){return new f(this.promise.then(e,t))}catch(e){return new f(this.promise.catch(e))}finally(e){return new f(this.promise.finally(e))}toPromise(){return this.promise}}class R{static get gates(){return{and:new r,or:new s,xor:new c,nand:new i,nor:new a,xnor:new o,majority:new n,allFulfilled:new u,allRejected:new d}}static and(e){return new f(this.gates.and.execute(e))}static or(e){return new f(this.gates.or.execute(e))}static xor(e){return new f(this.gates.xor.execute(e))}static nand(e){return new f(this.gates.nand.execute(e))}static nor(e){return new f(this.gates.nor.execute(e))}static xnor(e){return new f(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new f(this.gates.majority.execute(e,t))}static allFulfilled(e){return new f(this.gates.allFulfilled.execute(e))}static allRejected(e){return new f(this.gates.allRejected.execute(e))}static not(e){return new f(Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e)))}static race(e){return new f(Promise.race(e))}static allSettled(e){return new f(Promise.allSettled(e))}static createFlipFlop(e=!1){let t=e,l=null,s=Promise.resolve(t);const r=()=>(l||(s=new Promise(e=>{l=e})),s);return{getState:()=>t,set:async e=>(t=e,l&&(l(t),l=null),s=Promise.resolve(t),t),async toggle(){return this.set(!t)},waitForChange:r,waitFor:e=>t===e?Promise.resolve(t):new Promise(l=>{const s=()=>{t===e?l(t):r().then(s)};s()})}}}exports.createPromiseLogic=function(e={}){const{prefix:t="",suffix:l="",rename:s={}}=e,r={and:R.and.bind(R),or:R.or.bind(R),not:R.not.bind(R),race:R.race.bind(R),allSettled:R.allSettled.bind(R),xor:R.xor.bind(R),nand:R.nand.bind(R),nor:R.nor.bind(R),xnor:R.xnor.bind(R),majority:R.majority.bind(R),allFulfilled:R.allFulfilled.bind(R),allRejected:R.allRejected.bind(R)},n={};return Object.entries(r).forEach(([e,r])=>{const i=s[e]||e;n[`${t}${i}${l}`]=r}),n};
1
+ "use strict";class e extends Error{constructor(e,t,r){super(t),this.type=e,this.results=r,this.name="PromiseLogicError"}}function t(t,r,s,l){return new e(t,r,s)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}}class s extends r{async execute(e,r){try{return await Promise.any(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"OR condition failed";throw t(r.errorType||"OR_ERROR",n,l)}}}class l extends r{async execute(e,r){try{return await Promise.all(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"AND condition failed";throw t(r.errorType||"AND_ERROR",n,l)}}}class n extends r{async execute(e,r){const s=r.max||.5,l=await Promise.allSettled(e),n=l.length;if(0===n)return[];const i=this.filterFulfilledResults(l),o=i.length;if(this.filterRejectedResults(l),o>Math.floor(n*s))return i;{const e=r.errorMessage||`Majority condition failed: ${o}/${n} fulfilled (need majority)`;throw t(r.errorType||"MAJORITY_ERROR",e,l)}}}class i extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),n===i){const e=r.errorMessage||`NAND condition failed: all ${i} promises fulfilled (expected at least one rejection)`;throw t(r.errorType||"NAND_ERROR",e,s)}return l}}class o extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s).length;if(s.length,this.filterRejectedResults(s),0===l)return[];{const e=r.errorMessage||`NOR condition failed: ${l} promises fulfilled (expected all rejected)`;throw t(r.errorType||"NOR_ERROR",e,s)}}}class a extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),0===n||n===i)return l;{const e=r.errorMessage||`XNOR condition failed: ${n}/${i} promises fulfilled (expected all or none)`;throw t(r.errorType||"XNOR_ERROR",e,s)}}}class c extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),1===n)return l[0];{const e=r.errorMessage||(n>1?`XOR condition failed: ${n} promises fulfilled (expected exactly 1)`:`XOR condition failed: all ${i} promises rejected (expected exactly 1)`);throw t(r.errorType||"XOR_ERROR",e,s)}}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0,l=!1;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r[n]=e,l=!0,t(r.filter(e=>void 0!==e))}).catch(()=>{}).finally(()=>{s++,s!==i||l||t([])})}):t([])})}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0,l=!1;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{}).catch(e=>{r[n]=e,l=!0,t(r.filter(e=>void 0!==e))}).finally(()=>{s++,s!==i||l||t([])})}):t([])})}}class R extends r{async execute(e,r={}){let s;if("function"==typeof e[Symbol.iterator]){const l=[...e];if(0===l.length)throw t(r.errorType||"NOT_ERROR",r.errorMessage||"NOT gate requires exactly one promise",[]);if(l.length>1)throw t(r.errorType||"NOT_ERROR",r.errorMessage||"NOT gate only accepts one promise",[]);s=l[0]}else s=e;return Promise.resolve(s).then(e=>{throw t(r.errorType||"NOT_ERROR",r.errorMessage||`NOT condition failed: ${e}`,[])},e=>e)}}class f extends r{async execute(e,r){if(0===Array.from(e).length)return{};try{return await Promise.race(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"RACE condition failed: all promises rejected";throw t(r.errorType||"RACE_ERROR",n,l)}}}class h extends r{async execute(e,r){try{return await Promise.allSettled(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"ALL_SETTLED condition failed: at least one promise rejected";throw t(r.errorType||"ALL_SETTLED_ERROR",n,l)}}}class m{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;const s=Promise.race([this.promise,new Promise((s,l)=>{r=setTimeout(()=>{l(new Error(t))},e)})]).finally(()=>clearTimeout(r));return new m(s)}then(e,t){return new m(this.promise.then(e,t))}catch(e){return new m(this.promise.catch(e))}finally(e){return new m(this.promise.finally(e))}toPromise(){return this.promise}}class w{static get gates(){return{and:new l,or:new s,xor:new c,nand:new i,nor:new o,xnor:new a,not:new R,race:new f,allSettled:new h,majority:new n,allFulfilled:new d,allRejected:new u}}static and(e,t={errorType:"AND_ERROR",errorMessage:""}){return new m(this.gates.and.execute(e,t))}static or(e,t={errorType:"OR_ERROR",errorMessage:""}){return new m(this.gates.or.execute(e,t))}static not(e,t={errorType:"NOT_ERROR",errorMessage:""}){return new m(this.gates.not.execute(e,t))}static race(e,t={errorType:"RACE_ERROR",errorMessage:""}){return new m(this.gates.race.execute(e,t))}static allSettled(e,t={errorType:"ALL_SETTLED_ERROR",errorMessage:""}){return new m(this.gates.allSettled.execute(e,t))}static xor(e,t={errorType:"XOR_ERROR",errorMessage:""}){return new m(this.gates.xor.execute(e,t))}static nand(e,t={errorType:"NAND_ERROR",errorMessage:""}){return new m(this.gates.nand.execute(e,t))}static nor(e,t={errorType:"NOR_ERROR",errorMessage:""}){return new m(this.gates.nor.execute(e,t))}static xnor(e,t={errorType:"XNOR_ERROR",errorMessage:""}){return new m(this.gates.xnor.execute(e,t))}static majority(e,t={max:.5,errorType:"MAJORITY_ERROR",errorMessage:""}){return new m(this.gates.majority.execute(e,t))}static allFulfilled(e){return new m(this.gates.allFulfilled.execute(e))}static allRejected(e){return new m(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,s=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),s=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(s=new Promise(e=>{r=e})),s),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const s=()=>{t===e?r(t):this.waitForChange().then(s)};s()})}}}}exports.createPromiseLogic=function(e={}){const{prefix:t="",suffix:r="",rename:s={}}=e,l={and:w.and.bind(w),or:w.or.bind(w),not:w.not.bind(w),race:w.race.bind(w),allSettled:w.allSettled.bind(w),xor:w.xor.bind(w),nand:w.nand.bind(w),nor:w.nor.bind(w),xnor:w.xnor.bind(w),majority:w.majority.bind(w),allFulfilled:w.allFulfilled.bind(w),allRejected:w.allRejected.bind(w)},n={};return Object.entries(l).forEach(([e,l])=>{const i=s[e]||e;n[`${t}${i}${r}`]=l}),n};
@@ -1 +1 @@
1
- class e extends Error{constructor(e,t,l){super(t),this.type=e,this.results=l,this.name="PromiseLogicError"}}function t(t,l,s,r,n){const i={XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${l} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${s} promises fulfilled (expected at least one rejection).`,NOR_ERROR:`NOR condition failed: ${l} promises fulfilled (expected all rejected).`,XNOR_ERROR:`XNOR condition failed: ${l}/${s} promises fulfilled (expected all or none).`,MAJORITY_ERROR:`Majority condition failed: ${l}/${s} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${l}/${s} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${s-l}/${s} promises rejected (expected all to fail).`}[t]||"Logic condition failed",a=n&&n?.length>0?`\n失败原因:${n.map((e,t)=>`[${t+1}] ${e}`).join("\n")}`:"";return new e(t,i+a,r)}class l{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}}class s extends l{async execute(e){try{return Promise.any(e)}catch(e){throw t("OR_ERROR",0,0,[],[e])}}}class r extends l{async execute(e){try{return Promise.all(e)}catch(e){throw t("AND_ERROR",0,0,[],[e])}}}class n extends l{async execute(e,l){const s=await Promise.allSettled(e),r=this.filterFulfilledResults(s),n=r.length,i=s.length,a=this.filterRejectedResults(s);if(n>Math.floor(i*l.max))return r;throw t("MAJORITY_ERROR",n,i,s,a)}}class i extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),r=s.length,n=l.length,i=this.filterRejectedResults(l);if(r===n)throw t("NAND_ERROR",r,n,l,i);return s}}class a extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l).length,r=l.length,n=this.filterRejectedResults(l);if(0===s)return[];throw t("NOR_ERROR",s,r,l,n)}}class o extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),r=s.length,n=l.length,i=this.filterRejectedResults(l);if(0===r||r===n)return s;throw t("XNOR_ERROR",r,n,l,i)}}class c extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),r=s.length,n=l.length,i=this.filterRejectedResults(l);if(1===r)return s[0];throw t("XOR_ERROR",r,n,l,i)}}class u extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let s=0,r=0;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r++,l[n]=e}).catch(()=>{l[n]=void 0}).finally(()=>{s++,r>0?t(l.filter(e=>void 0!==e)):s===i&&t([])})}):t(l)})}}class d extends l{async execute(e){return new Promise(t=>{const l=[];let s=0,r=0;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{l[n]=void 0}).catch(e=>{r++,l[n]=e}).finally(()=>{s++,r>0?t(l.filter(e=>void 0!==e)):s===i&&t([])})}):t(l)})}}class f{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let l;return Promise.race([this.promise,new Promise((s,r)=>{l=setTimeout(()=>{r(new Error(t))},e)})]).finally(()=>clearTimeout(l))}then(e,t){return new f(this.promise.then(e,t))}catch(e){return new f(this.promise.catch(e))}finally(e){return new f(this.promise.finally(e))}toPromise(){return this.promise}}class R{static get gates(){return{and:new r,or:new s,xor:new c,nand:new i,nor:new a,xnor:new o,majority:new n,allFulfilled:new u,allRejected:new d}}static and(e){return new f(this.gates.and.execute(e))}static or(e){return new f(this.gates.or.execute(e))}static xor(e){return new f(this.gates.xor.execute(e))}static nand(e){return new f(this.gates.nand.execute(e))}static nor(e){return new f(this.gates.nor.execute(e))}static xnor(e){return new f(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new f(this.gates.majority.execute(e,t))}static allFulfilled(e){return new f(this.gates.allFulfilled.execute(e))}static allRejected(e){return new f(this.gates.allRejected.execute(e))}static not(e){return new f(Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e)))}static race(e){return new f(Promise.race(e))}static allSettled(e){return new f(Promise.allSettled(e))}static createFlipFlop(e=!1){let t=e,l=null,s=Promise.resolve(t);const r=()=>(l||(s=new Promise(e=>{l=e})),s);return{getState:()=>t,set:async e=>(t=e,l&&(l(t),l=null),s=Promise.resolve(t),t),async toggle(){return this.set(!t)},waitForChange:r,waitFor:e=>t===e?Promise.resolve(t):new Promise(l=>{const s=()=>{t===e?l(t):r().then(s)};s()})}}}function h(e={}){const{prefix:t="",suffix:l="",rename:s={}}=e,r={and:R.and.bind(R),or:R.or.bind(R),not:R.not.bind(R),race:R.race.bind(R),allSettled:R.allSettled.bind(R),xor:R.xor.bind(R),nand:R.nand.bind(R),nor:R.nor.bind(R),xnor:R.xnor.bind(R),majority:R.majority.bind(R),allFulfilled:R.allFulfilled.bind(R),allRejected:R.allRejected.bind(R)},n={};return Object.entries(r).forEach(([e,r])=>{const i=s[e]||e;n[`${t}${i}${l}`]=r}),n}export{h as createPromiseLogic};
1
+ class e extends Error{constructor(e,t,r){super(t),this.type=e,this.results=r,this.name="PromiseLogicError"}}function t(t,r,s,l){return new e(t,r,s)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}}class s extends r{async execute(e,r){try{return await Promise.any(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"OR condition failed";throw t(r.errorType||"OR_ERROR",n,l)}}}class l extends r{async execute(e,r){try{return await Promise.all(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"AND condition failed";throw t(r.errorType||"AND_ERROR",n,l)}}}class n extends r{async execute(e,r){const s=r.max||.5,l=await Promise.allSettled(e),n=l.length;if(0===n)return[];const i=this.filterFulfilledResults(l),o=i.length;if(this.filterRejectedResults(l),o>Math.floor(n*s))return i;{const e=r.errorMessage||`Majority condition failed: ${o}/${n} fulfilled (need majority)`;throw t(r.errorType||"MAJORITY_ERROR",e,l)}}}class i extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),n===i){const e=r.errorMessage||`NAND condition failed: all ${i} promises fulfilled (expected at least one rejection)`;throw t(r.errorType||"NAND_ERROR",e,s)}return l}}class o extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s).length;if(s.length,this.filterRejectedResults(s),0===l)return[];{const e=r.errorMessage||`NOR condition failed: ${l} promises fulfilled (expected all rejected)`;throw t(r.errorType||"NOR_ERROR",e,s)}}}class a extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),0===n||n===i)return l;{const e=r.errorMessage||`XNOR condition failed: ${n}/${i} promises fulfilled (expected all or none)`;throw t(r.errorType||"XNOR_ERROR",e,s)}}}class c extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),1===n)return l[0];{const e=r.errorMessage||(n>1?`XOR condition failed: ${n} promises fulfilled (expected exactly 1)`:`XOR condition failed: all ${i} promises rejected (expected exactly 1)`);throw t(r.errorType||"XOR_ERROR",e,s)}}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0,l=!1;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r[n]=e,l=!0,t(r.filter(e=>void 0!==e))}).catch(()=>{}).finally(()=>{s++,s!==i||l||t([])})}):t([])})}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0,l=!1;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{}).catch(e=>{r[n]=e,l=!0,t(r.filter(e=>void 0!==e))}).finally(()=>{s++,s!==i||l||t([])})}):t([])})}}class R extends r{async execute(e,r={}){let s;if("function"==typeof e[Symbol.iterator]){const l=[...e];if(0===l.length)throw t(r.errorType||"NOT_ERROR",r.errorMessage||"NOT gate requires exactly one promise",[]);if(l.length>1)throw t(r.errorType||"NOT_ERROR",r.errorMessage||"NOT gate only accepts one promise",[]);s=l[0]}else s=e;return Promise.resolve(s).then(e=>{throw t(r.errorType||"NOT_ERROR",r.errorMessage||`NOT condition failed: ${e}`,[])},e=>e)}}class f extends r{async execute(e,r){if(0===Array.from(e).length)return{};try{return await Promise.race(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"RACE condition failed: all promises rejected";throw t(r.errorType||"RACE_ERROR",n,l)}}}class h extends r{async execute(e,r){try{return await Promise.allSettled(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"ALL_SETTLED condition failed: at least one promise rejected";throw t(r.errorType||"ALL_SETTLED_ERROR",n,l)}}}class m{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;const s=Promise.race([this.promise,new Promise((s,l)=>{r=setTimeout(()=>{l(new Error(t))},e)})]).finally(()=>clearTimeout(r));return new m(s)}then(e,t){return new m(this.promise.then(e,t))}catch(e){return new m(this.promise.catch(e))}finally(e){return new m(this.promise.finally(e))}toPromise(){return this.promise}}class w{static get gates(){return{and:new l,or:new s,xor:new c,nand:new i,nor:new o,xnor:new a,not:new R,race:new f,allSettled:new h,majority:new n,allFulfilled:new d,allRejected:new u}}static and(e,t={errorType:"AND_ERROR",errorMessage:""}){return new m(this.gates.and.execute(e,t))}static or(e,t={errorType:"OR_ERROR",errorMessage:""}){return new m(this.gates.or.execute(e,t))}static not(e,t={errorType:"NOT_ERROR",errorMessage:""}){return new m(this.gates.not.execute(e,t))}static race(e,t={errorType:"RACE_ERROR",errorMessage:""}){return new m(this.gates.race.execute(e,t))}static allSettled(e,t={errorType:"ALL_SETTLED_ERROR",errorMessage:""}){return new m(this.gates.allSettled.execute(e,t))}static xor(e,t={errorType:"XOR_ERROR",errorMessage:""}){return new m(this.gates.xor.execute(e,t))}static nand(e,t={errorType:"NAND_ERROR",errorMessage:""}){return new m(this.gates.nand.execute(e,t))}static nor(e,t={errorType:"NOR_ERROR",errorMessage:""}){return new m(this.gates.nor.execute(e,t))}static xnor(e,t={errorType:"XNOR_ERROR",errorMessage:""}){return new m(this.gates.xnor.execute(e,t))}static majority(e,t={max:.5,errorType:"MAJORITY_ERROR",errorMessage:""}){return new m(this.gates.majority.execute(e,t))}static allFulfilled(e){return new m(this.gates.allFulfilled.execute(e))}static allRejected(e){return new m(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,s=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),s=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(s=new Promise(e=>{r=e})),s),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const s=()=>{t===e?r(t):this.waitForChange().then(s)};s()})}}}}function x(e={}){const{prefix:t="",suffix:r="",rename:s={}}=e,l={and:w.and.bind(w),or:w.or.bind(w),not:w.not.bind(w),race:w.race.bind(w),allSettled:w.allSettled.bind(w),xor:w.xor.bind(w),nand:w.nand.bind(w),nor:w.nor.bind(w),xnor:w.xnor.bind(w),majority:w.majority.bind(w),allFulfilled:w.allFulfilled.bind(w),allRejected:w.allRejected.bind(w)},n={};return Object.entries(l).forEach(([e,l])=>{const i=s[e]||e;n[`${t}${i}${r}`]=l}),n}export{x as createPromiseLogic};
@@ -1 +1 @@
1
- "use strict";class e extends Error{constructor(e,t,l){super(t),this.type=e,this.results=l,this.name="PromiseLogicError"}}function t(t,l,r,s,i){const n={XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${l} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${r} promises fulfilled (expected at least one rejection).`,NOR_ERROR:`NOR condition failed: ${l} promises fulfilled (expected all rejected).`,XNOR_ERROR:`XNOR condition failed: ${l}/${r} promises fulfilled (expected all or none).`,MAJORITY_ERROR:`Majority condition failed: ${l}/${r} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${l}/${r} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${r-l}/${r} promises rejected (expected all to fail).`}[t]||"Logic condition failed",o=i&&i?.length>0?`\n失败原因:${i.map((e,t)=>`[${t+1}] ${e}`).join("\n")}`:"";return new e(t,n+o,s)}class l{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}}class r extends l{async execute(e){try{return Promise.any(e)}catch(e){throw t("OR_ERROR",0,0,[],[e])}}}class s extends l{async execute(e){try{return Promise.all(e)}catch(e){throw t("AND_ERROR",0,0,[],[e])}}}class i extends l{async execute(e,l){const r=await Promise.allSettled(e),s=this.filterFulfilledResults(r),i=s.length,n=r.length,o=this.filterRejectedResults(r);if(i>Math.floor(n*l.max))return s;throw t("MAJORITY_ERROR",i,n,r,o)}}class n extends l{async execute(e){const l=await Promise.allSettled(e),r=this.filterFulfilledResults(l),s=r.length,i=l.length,n=this.filterRejectedResults(l);if(s===i)throw t("NAND_ERROR",s,i,l,n);return r}}class o extends l{async execute(e){const l=await Promise.allSettled(e),r=this.filterFulfilledResults(l).length,s=l.length,i=this.filterRejectedResults(l);if(0===r)return[];throw t("NOR_ERROR",r,s,l,i)}}class a extends l{async execute(e){const l=await Promise.allSettled(e),r=this.filterFulfilledResults(l),s=r.length,i=l.length,n=this.filterRejectedResults(l);if(0===s||s===i)return r;throw t("XNOR_ERROR",s,i,l,n)}}class c extends l{async execute(e){const l=await Promise.allSettled(e),r=this.filterFulfilledResults(l),s=r.length,i=l.length,n=this.filterRejectedResults(l);if(1===s)return r[0];throw t("XOR_ERROR",s,i,l,n)}}class u extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let r=0,s=0;const i=[...e],n=i?.length??0;0!==n?i.forEach((e,i)=>{Promise.resolve(e).then(e=>{s++,l[i]=e}).catch(()=>{l[i]=void 0}).finally(()=>{r++,s>0?t(l.filter(e=>void 0!==e)):r===n&&t([])})}):t(l)})}}class d extends l{async execute(e){return new Promise(t=>{const l=[];let r=0,s=0;const i=[...e],n=i?.length??0;0!==n?i.forEach((e,i)=>{Promise.resolve(e).then(()=>{l[i]=void 0}).catch(e=>{s++,l[i]=e}).finally(()=>{r++,s>0?t(l.filter(e=>void 0!==e)):r===n&&t([])})}):t(l)})}}class f{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let l;return Promise.race([this.promise,new Promise((r,s)=>{l=setTimeout(()=>{s(new Error(t))},e)})]).finally(()=>clearTimeout(l))}then(e,t){return new f(this.promise.then(e,t))}catch(e){return new f(this.promise.catch(e))}finally(e){return new f(this.promise.finally(e))}toPromise(){return this.promise}}class R{static get gates(){return{and:new s,or:new r,xor:new c,nand:new n,nor:new o,xnor:new a,majority:new i,allFulfilled:new u,allRejected:new d}}static and(e){return new f(this.gates.and.execute(e))}static or(e){return new f(this.gates.or.execute(e))}static xor(e){return new f(this.gates.xor.execute(e))}static nand(e){return new f(this.gates.nand.execute(e))}static nor(e){return new f(this.gates.nor.execute(e))}static xnor(e){return new f(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new f(this.gates.majority.execute(e,t))}static allFulfilled(e){return new f(this.gates.allFulfilled.execute(e))}static allRejected(e){return new f(this.gates.allRejected.execute(e))}static not(e){return new f(Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e)))}static race(e){return new f(Promise.race(e))}static allSettled(e){return new f(Promise.allSettled(e))}static createFlipFlop(e=!1){let t=e,l=null,r=Promise.resolve(t);const s=()=>(l||(r=new Promise(e=>{l=e})),r);return{getState:()=>t,set:async e=>(t=e,l&&(l(t),l=null),r=Promise.resolve(t),t),async toggle(){return this.set(!t)},waitForChange:s,waitFor:e=>t===e?Promise.resolve(t):new Promise(l=>{const r=()=>{t===e?l(t):s().then(r)};r()})}}}exports.PromiseLogic=R,exports.PromiseLogicError=e,exports.PromiseWithTimer=f,exports.createPromiseLogic=function(e={}){const{prefix:t="",suffix:l="",rename:r={}}=e,s={and:R.and.bind(R),or:R.or.bind(R),not:R.not.bind(R),race:R.race.bind(R),allSettled:R.allSettled.bind(R),xor:R.xor.bind(R),nand:R.nand.bind(R),nor:R.nor.bind(R),xnor:R.xnor.bind(R),majority:R.majority.bind(R),allFulfilled:R.allFulfilled.bind(R),allRejected:R.allRejected.bind(R)},i={};return Object.entries(s).forEach(([e,s])=>{const n=r[e]||e;i[`${t}${n}${l}`]=s}),i};
1
+ "use strict";class e extends Error{constructor(e,t,r){super(t),this.type=e,this.results=r,this.name="PromiseLogicError"}}function t(t,r,s,l){return new e(t,r,s)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}}class s extends r{async execute(e,r){try{return await Promise.any(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"OR condition failed";throw t(r.errorType||"OR_ERROR",n,l)}}}class l extends r{async execute(e,r){try{return await Promise.all(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"AND condition failed";throw t(r.errorType||"AND_ERROR",n,l)}}}class n extends r{async execute(e,r){const s=r.max||.5,l=await Promise.allSettled(e),n=l.length;if(0===n)return[];const i=this.filterFulfilledResults(l),o=i.length;if(this.filterRejectedResults(l),o>Math.floor(n*s))return i;{const e=r.errorMessage||`Majority condition failed: ${o}/${n} fulfilled (need majority)`;throw t(r.errorType||"MAJORITY_ERROR",e,l)}}}class i extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),n===i){const e=r.errorMessage||`NAND condition failed: all ${i} promises fulfilled (expected at least one rejection)`;throw t(r.errorType||"NAND_ERROR",e,s)}return l}}class o extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s).length;if(s.length,this.filterRejectedResults(s),0===l)return[];{const e=r.errorMessage||`NOR condition failed: ${l} promises fulfilled (expected all rejected)`;throw t(r.errorType||"NOR_ERROR",e,s)}}}class a extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),0===n||n===i)return l;{const e=r.errorMessage||`XNOR condition failed: ${n}/${i} promises fulfilled (expected all or none)`;throw t(r.errorType||"XNOR_ERROR",e,s)}}}class c extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),1===n)return l[0];{const e=r.errorMessage||(n>1?`XOR condition failed: ${n} promises fulfilled (expected exactly 1)`:`XOR condition failed: all ${i} promises rejected (expected exactly 1)`);throw t(r.errorType||"XOR_ERROR",e,s)}}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0,l=!1;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r[n]=e,l=!0,t(r.filter(e=>void 0!==e))}).catch(()=>{}).finally(()=>{s++,s!==i||l||t([])})}):t([])})}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0,l=!1;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{}).catch(e=>{r[n]=e,l=!0,t(r.filter(e=>void 0!==e))}).finally(()=>{s++,s!==i||l||t([])})}):t([])})}}class R extends r{async execute(e,r={}){let s;if("function"==typeof e[Symbol.iterator]){const l=[...e];if(0===l.length)throw t(r.errorType||"NOT_ERROR",r.errorMessage||"NOT gate requires exactly one promise",[]);if(l.length>1)throw t(r.errorType||"NOT_ERROR",r.errorMessage||"NOT gate only accepts one promise",[]);s=l[0]}else s=e;return Promise.resolve(s).then(e=>{throw t(r.errorType||"NOT_ERROR",r.errorMessage||`NOT condition failed: ${e}`,[])},e=>e)}}class h extends r{async execute(e,r){if(0===Array.from(e).length)return{};try{return await Promise.race(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"RACE condition failed: all promises rejected";throw t(r.errorType||"RACE_ERROR",n,l)}}}class f extends r{async execute(e,r){try{return await Promise.allSettled(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"ALL_SETTLED condition failed: at least one promise rejected";throw t(r.errorType||"ALL_SETTLED_ERROR",n,l)}}}class m{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;const s=Promise.race([this.promise,new Promise((s,l)=>{r=setTimeout(()=>{l(new Error(t))},e)})]).finally(()=>clearTimeout(r));return new m(s)}then(e,t){return new m(this.promise.then(e,t))}catch(e){return new m(this.promise.catch(e))}finally(e){return new m(this.promise.finally(e))}toPromise(){return this.promise}}class x{static get gates(){return{and:new l,or:new s,xor:new c,nand:new i,nor:new o,xnor:new a,not:new R,race:new h,allSettled:new f,majority:new n,allFulfilled:new d,allRejected:new u}}static and(e,t={errorType:"AND_ERROR",errorMessage:""}){return new m(this.gates.and.execute(e,t))}static or(e,t={errorType:"OR_ERROR",errorMessage:""}){return new m(this.gates.or.execute(e,t))}static not(e,t={errorType:"NOT_ERROR",errorMessage:""}){return new m(this.gates.not.execute(e,t))}static race(e,t={errorType:"RACE_ERROR",errorMessage:""}){return new m(this.gates.race.execute(e,t))}static allSettled(e,t={errorType:"ALL_SETTLED_ERROR",errorMessage:""}){return new m(this.gates.allSettled.execute(e,t))}static xor(e,t={errorType:"XOR_ERROR",errorMessage:""}){return new m(this.gates.xor.execute(e,t))}static nand(e,t={errorType:"NAND_ERROR",errorMessage:""}){return new m(this.gates.nand.execute(e,t))}static nor(e,t={errorType:"NOR_ERROR",errorMessage:""}){return new m(this.gates.nor.execute(e,t))}static xnor(e,t={errorType:"XNOR_ERROR",errorMessage:""}){return new m(this.gates.xnor.execute(e,t))}static majority(e,t={max:.5,errorType:"MAJORITY_ERROR",errorMessage:""}){return new m(this.gates.majority.execute(e,t))}static allFulfilled(e){return new m(this.gates.allFulfilled.execute(e))}static allRejected(e){return new m(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,s=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),s=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(s=new Promise(e=>{r=e})),s),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const s=()=>{t===e?r(t):this.waitForChange().then(s)};s()})}}}}exports.PromiseLogic=x,exports.PromiseLogicError=e,exports.PromiseWithTimer=m,exports.createPromiseLogic=function(e={}){const{prefix:t="",suffix:r="",rename:s={}}=e,l={and:x.and.bind(x),or:x.or.bind(x),not:x.not.bind(x),race:x.race.bind(x),allSettled:x.allSettled.bind(x),xor:x.xor.bind(x),nand:x.nand.bind(x),nor:x.nor.bind(x),xnor:x.xnor.bind(x),majority:x.majority.bind(x),allFulfilled:x.allFulfilled.bind(x),allRejected:x.allRejected.bind(x)},n={};return Object.entries(l).forEach(([e,l])=>{const i=s[e]||e;n[`${t}${i}${r}`]=l}),n};
@@ -1 +1 @@
1
- class e extends Error{constructor(e,t,l){super(t),this.type=e,this.results=l,this.name="PromiseLogicError"}}function t(t,l,s,r,n){const i={XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${l} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${s} promises fulfilled (expected at least one rejection).`,NOR_ERROR:`NOR condition failed: ${l} promises fulfilled (expected all rejected).`,XNOR_ERROR:`XNOR condition failed: ${l}/${s} promises fulfilled (expected all or none).`,MAJORITY_ERROR:`Majority condition failed: ${l}/${s} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${l}/${s} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${s-l}/${s} promises rejected (expected all to fail).`}[t]||"Logic condition failed",a=n&&n?.length>0?`\n失败原因:${n.map((e,t)=>`[${t+1}] ${e}`).join("\n")}`:"";return new e(t,i+a,r)}class l{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}}class s extends l{async execute(e){try{return Promise.any(e)}catch(e){throw t("OR_ERROR",0,0,[],[e])}}}class r extends l{async execute(e){try{return Promise.all(e)}catch(e){throw t("AND_ERROR",0,0,[],[e])}}}class n extends l{async execute(e,l){const s=await Promise.allSettled(e),r=this.filterFulfilledResults(s),n=r.length,i=s.length,a=this.filterRejectedResults(s);if(n>Math.floor(i*l.max))return r;throw t("MAJORITY_ERROR",n,i,s,a)}}class i extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),r=s.length,n=l.length,i=this.filterRejectedResults(l);if(r===n)throw t("NAND_ERROR",r,n,l,i);return s}}class a extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l).length,r=l.length,n=this.filterRejectedResults(l);if(0===s)return[];throw t("NOR_ERROR",s,r,l,n)}}class o extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),r=s.length,n=l.length,i=this.filterRejectedResults(l);if(0===r||r===n)return s;throw t("XNOR_ERROR",r,n,l,i)}}class c extends l{async execute(e){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),r=s.length,n=l.length,i=this.filterRejectedResults(l);if(1===r)return s[0];throw t("XOR_ERROR",r,n,l,i)}}class u extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let s=0,r=0;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r++,l[n]=e}).catch(()=>{l[n]=void 0}).finally(()=>{s++,r>0?t(l.filter(e=>void 0!==e)):s===i&&t([])})}):t(l)})}}class d extends l{async execute(e){return new Promise(t=>{const l=[];let s=0,r=0;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{l[n]=void 0}).catch(e=>{r++,l[n]=e}).finally(()=>{s++,r>0?t(l.filter(e=>void 0!==e)):s===i&&t([])})}):t(l)})}}class f{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let l;return Promise.race([this.promise,new Promise((s,r)=>{l=setTimeout(()=>{r(new Error(t))},e)})]).finally(()=>clearTimeout(l))}then(e,t){return new f(this.promise.then(e,t))}catch(e){return new f(this.promise.catch(e))}finally(e){return new f(this.promise.finally(e))}toPromise(){return this.promise}}class R{static get gates(){return{and:new r,or:new s,xor:new c,nand:new i,nor:new a,xnor:new o,majority:new n,allFulfilled:new u,allRejected:new d}}static and(e){return new f(this.gates.and.execute(e))}static or(e){return new f(this.gates.or.execute(e))}static xor(e){return new f(this.gates.xor.execute(e))}static nand(e){return new f(this.gates.nand.execute(e))}static nor(e){return new f(this.gates.nor.execute(e))}static xnor(e){return new f(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new f(this.gates.majority.execute(e,t))}static allFulfilled(e){return new f(this.gates.allFulfilled.execute(e))}static allRejected(e){return new f(this.gates.allRejected.execute(e))}static not(e){return new f(Promise.resolve(e).then(e=>Promise.reject(new Error(`NOT: ${e}`)),e=>Promise.resolve(e)))}static race(e){return new f(Promise.race(e))}static allSettled(e){return new f(Promise.allSettled(e))}static createFlipFlop(e=!1){let t=e,l=null,s=Promise.resolve(t);const r=()=>(l||(s=new Promise(e=>{l=e})),s);return{getState:()=>t,set:async e=>(t=e,l&&(l(t),l=null),s=Promise.resolve(t),t),async toggle(){return this.set(!t)},waitForChange:r,waitFor:e=>t===e?Promise.resolve(t):new Promise(l=>{const s=()=>{t===e?l(t):r().then(s)};s()})}}}function h(e={}){const{prefix:t="",suffix:l="",rename:s={}}=e,r={and:R.and.bind(R),or:R.or.bind(R),not:R.not.bind(R),race:R.race.bind(R),allSettled:R.allSettled.bind(R),xor:R.xor.bind(R),nand:R.nand.bind(R),nor:R.nor.bind(R),xnor:R.xnor.bind(R),majority:R.majority.bind(R),allFulfilled:R.allFulfilled.bind(R),allRejected:R.allRejected.bind(R)},n={};return Object.entries(r).forEach(([e,r])=>{const i=s[e]||e;n[`${t}${i}${l}`]=r}),n}export{R as PromiseLogic,e as PromiseLogicError,f as PromiseWithTimer,h as createPromiseLogic};
1
+ class e extends Error{constructor(e,t,r){super(t),this.type=e,this.results=r,this.name="PromiseLogicError"}}function t(t,r,s,l){return new e(t,r,s)}class r{filterFulfilledResults(e){return e.filter(e=>"fulfilled"===e.status).map(e=>e.value)}filterRejectedResults(e){return e.filter(e=>"rejected"===e.status).map(e=>e.reason)}countFulfilled(e){return e.filter(e=>"fulfilled"===e.status).length}}class s extends r{async execute(e,r){try{return await Promise.any(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"OR condition failed";throw t(r.errorType||"OR_ERROR",n,l)}}}class l extends r{async execute(e,r){try{return await Promise.all(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"AND condition failed";throw t(r.errorType||"AND_ERROR",n,l)}}}class n extends r{async execute(e,r){const s=r.max||.5,l=await Promise.allSettled(e),n=l.length;if(0===n)return[];const i=this.filterFulfilledResults(l),o=i.length;if(this.filterRejectedResults(l),o>Math.floor(n*s))return i;{const e=r.errorMessage||`Majority condition failed: ${o}/${n} fulfilled (need majority)`;throw t(r.errorType||"MAJORITY_ERROR",e,l)}}}class i extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),n===i){const e=r.errorMessage||`NAND condition failed: all ${i} promises fulfilled (expected at least one rejection)`;throw t(r.errorType||"NAND_ERROR",e,s)}return l}}class o extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s).length;if(s.length,this.filterRejectedResults(s),0===l)return[];{const e=r.errorMessage||`NOR condition failed: ${l} promises fulfilled (expected all rejected)`;throw t(r.errorType||"NOR_ERROR",e,s)}}}class a extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),0===n||n===i)return l;{const e=r.errorMessage||`XNOR condition failed: ${n}/${i} promises fulfilled (expected all or none)`;throw t(r.errorType||"XNOR_ERROR",e,s)}}}class c extends r{async execute(e,r){const s=await Promise.allSettled(e),l=this.filterFulfilledResults(s),n=l.length,i=s.length;if(this.filterRejectedResults(s),1===n)return l[0];{const e=r.errorMessage||(n>1?`XOR condition failed: ${n} promises fulfilled (expected exactly 1)`:`XOR condition failed: all ${i} promises rejected (expected exactly 1)`);throw t(r.errorType||"XOR_ERROR",e,s)}}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0,l=!1;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(e=>{r[n]=e,l=!0,t(r.filter(e=>void 0!==e))}).catch(()=>{}).finally(()=>{s++,s!==i||l||t([])})}):t([])})}}class u extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let s=0,l=!1;const n=[...e],i=n?.length??0;0!==i?n.forEach((e,n)=>{Promise.resolve(e).then(()=>{}).catch(e=>{r[n]=e,l=!0,t(r.filter(e=>void 0!==e))}).finally(()=>{s++,s!==i||l||t([])})}):t([])})}}class R extends r{async execute(e,r={}){let s;if("function"==typeof e[Symbol.iterator]){const l=[...e];if(0===l.length)throw t(r.errorType||"NOT_ERROR",r.errorMessage||"NOT gate requires exactly one promise",[]);if(l.length>1)throw t(r.errorType||"NOT_ERROR",r.errorMessage||"NOT gate only accepts one promise",[]);s=l[0]}else s=e;return Promise.resolve(s).then(e=>{throw t(r.errorType||"NOT_ERROR",r.errorMessage||`NOT condition failed: ${e}`,[])},e=>e)}}class f extends r{async execute(e,r){if(0===Array.from(e).length)return{};try{return await Promise.race(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"RACE condition failed: all promises rejected";throw t(r.errorType||"RACE_ERROR",n,l)}}}class h extends r{async execute(e,r){try{return await Promise.allSettled(e)}catch(s){const l=await Promise.allSettled(e),n=r.errorMessage||"ALL_SETTLED condition failed: at least one promise rejected";throw t(r.errorType||"ALL_SETTLED_ERROR",n,l)}}}class m{constructor(e){this.promise=e}maxTimer(e,t=`Promise timed out after ${e}ms`){let r;const s=Promise.race([this.promise,new Promise((s,l)=>{r=setTimeout(()=>{l(new Error(t))},e)})]).finally(()=>clearTimeout(r));return new m(s)}then(e,t){return new m(this.promise.then(e,t))}catch(e){return new m(this.promise.catch(e))}finally(e){return new m(this.promise.finally(e))}toPromise(){return this.promise}}class w{static get gates(){return{and:new l,or:new s,xor:new c,nand:new i,nor:new o,xnor:new a,not:new R,race:new f,allSettled:new h,majority:new n,allFulfilled:new d,allRejected:new u}}static and(e,t={errorType:"AND_ERROR",errorMessage:""}){return new m(this.gates.and.execute(e,t))}static or(e,t={errorType:"OR_ERROR",errorMessage:""}){return new m(this.gates.or.execute(e,t))}static not(e,t={errorType:"NOT_ERROR",errorMessage:""}){return new m(this.gates.not.execute(e,t))}static race(e,t={errorType:"RACE_ERROR",errorMessage:""}){return new m(this.gates.race.execute(e,t))}static allSettled(e,t={errorType:"ALL_SETTLED_ERROR",errorMessage:""}){return new m(this.gates.allSettled.execute(e,t))}static xor(e,t={errorType:"XOR_ERROR",errorMessage:""}){return new m(this.gates.xor.execute(e,t))}static nand(e,t={errorType:"NAND_ERROR",errorMessage:""}){return new m(this.gates.nand.execute(e,t))}static nor(e,t={errorType:"NOR_ERROR",errorMessage:""}){return new m(this.gates.nor.execute(e,t))}static xnor(e,t={errorType:"XNOR_ERROR",errorMessage:""}){return new m(this.gates.xnor.execute(e,t))}static majority(e,t={max:.5,errorType:"MAJORITY_ERROR",errorMessage:""}){return new m(this.gates.majority.execute(e,t))}static allFulfilled(e){return new m(this.gates.allFulfilled.execute(e))}static allRejected(e){return new m(this.gates.allRejected.execute(e))}static createFlipFlop(e=!1){let t=e,r=null,s=Promise.resolve(t);return{getState:()=>t,set(e){return t=e,r&&(r(t),r=null),s=Promise.resolve(t),this},toggle(){return this.set(!t)},waitForChange:()=>(r||(s=new Promise(e=>{r=e})),s),waitFor(e){return t===e?Promise.resolve(t):new Promise(r=>{const s=()=>{t===e?r(t):this.waitForChange().then(s)};s()})}}}}function x(e={}){const{prefix:t="",suffix:r="",rename:s={}}=e,l={and:w.and.bind(w),or:w.or.bind(w),not:w.not.bind(w),race:w.race.bind(w),allSettled:w.allSettled.bind(w),xor:w.xor.bind(w),nand:w.nand.bind(w),nor:w.nor.bind(w),xnor:w.xnor.bind(w),majority:w.majority.bind(w),allFulfilled:w.allFulfilled.bind(w),allRejected:w.allRejected.bind(w)},n={};return Object.entries(l).forEach(([e,l])=>{const i=s[e]||e;n[`${t}${i}${r}`]=l}),n}export{w as PromiseLogic,e as PromiseLogicError,m as PromiseWithTimer,x as createPromiseLogic};
@@ -1,11 +1,22 @@
1
1
  // v2版本类型定义 (TypeScript版本 - 现代化设计)
2
2
 
3
+ /**
4
+ * 选项参数接口
5
+ */
6
+ interface LogicGateOptions {
7
+ errorType?: string | undefined;
8
+ errorMessage?: string | undefined;
9
+ max?: number | undefined;
10
+ [key: string]: string | number | boolean | undefined;
11
+
12
+ }
13
+
3
14
  /**
4
15
  * PromiseWithTimer 包装类 - 提供超时控制功能
5
16
  */
6
17
  declare class PromiseWithTimer<T> {
7
18
  /** 添加超时控制 */
8
- maxTimer(ms: number): Promise<T>;
19
+ maxTimer(ms: number, errorMessage?: string): PromiseWithTimer<T>;
9
20
 
10
21
  /** Promise 链式调用 */
11
22
  then<U>(onfulfilled?: ((value: T) => U | PromiseLike<U>) | null, onrejected?: ((reason: Error) => U | PromiseLike<U>) | null): PromiseWithTimer<U>;
@@ -22,10 +33,9 @@ declare class PromiseWithTimer<T> {
22
33
 
23
34
  /**
24
35
  * Promise逻辑错误类
25
- * @deprecated 在v2版本中建议使用更具体的错误类型
26
36
  */
27
37
  declare class PromiseLogicError extends Error {
28
- readonly type: 'XOR_ERROR' | 'NAND_ERROR' | 'NOR_ERROR' | 'XNOR_ERROR' | 'MAJORITY_ERROR' | 'ALL_SUCCESSFUL_ERROR' | 'ALL_FAILED_ERROR';
38
+ readonly type: string;
29
39
  readonly results: PromiseSettledResult<unknown>[];
30
40
 
31
41
  constructor(type: string, message: string, results: PromiseSettledResult<unknown>[]);
@@ -56,22 +66,22 @@ interface FlipFlop {
56
66
  */
57
67
  declare class PromiseLogic {
58
68
  // 基础逻辑门
59
- static and<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T[]>;
60
- static or<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T>;
61
- static race<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T>;
62
- static allSettled<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<PromiseSettledResult<T>[]>;
69
+ static and<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
70
+ static or<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T>;
71
+ static race<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T | undefined>;
72
+ static allSettled<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<PromiseSettledResult<T>[]>;
63
73
 
64
74
  // 扩展逻辑门
65
- static xor<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T>;
66
- static not<T>(promise: T | PromiseLike<T>): PromiseWithTimer<unknown>;
67
- static nand<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T[]>;
68
- static nor<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T[]>;
69
- static xnor<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<T[]>;
70
- static majority<T>(iterable: Iterable<T | PromiseLike<T>>, options?: { max: number }): PromiseWithTimer<T[]>;
75
+ static xor<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T>;
76
+ static not<T>(promise: T | PromiseLike<T>, options?: LogicGateOptions): PromiseWithTimer<T>;
77
+ static nand<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
78
+ static nor<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
79
+ static xnor<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
80
+ static majority<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
71
81
 
72
82
  // 实用方法
73
- static allFulfilled(iterable: Iterable<PromiseLike<unknown>>): PromiseWithTimer<unknown[]>;
74
- static allRejected<T>(iterable: Iterable<T | PromiseLike<T>>): PromiseWithTimer<unknown[]>;
83
+ static allFulfilled<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<T[]>;
84
+ static allRejected<T>(iterable: Iterable<T | PromiseLike<T>>, options?: LogicGateOptions): PromiseWithTimer<Error[]>;
75
85
 
76
86
  // 状态管理
77
87
  static createFlipFlop(initialState?: boolean): FlipFlop;
@@ -98,9 +108,8 @@ declare function createPromiseLogic(options?: CreatePromiseLogicOptions): Record
98
108
 
99
109
  /**
100
110
  * 创建逻辑错误
101
- * @deprecated 在v2版本中建议使用更具体的错误构造器
102
111
  */
103
- declare function createLogicError(type: string, fulfilledCount: number, total: number, results: PromiseSettledResult<unknown>[]): PromiseLogicError;
112
+ declare function createLogicError(type: string, message: string, results: PromiseSettledResult<unknown>[], error?: unknown): PromiseLogicError;
104
113
 
105
114
  export { PromiseLogic, PromiseLogicError, PromiseWithTimer, createLogicError, createPromiseLogic };
106
- export type { CreatePromiseLogicOptions, FlipFlop };
115
+ export type { CreatePromiseLogicOptions, FlipFlop, LogicGateOptions };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "promise-logic",
3
- "version": "2.8.5",
3
+ "version": "2.9.1",
4
4
  "description": "Compose promises with logic gate semantics (AND, OR, XOR, NAND, NOR, XNOR, Majority). Forget APIs, remember logic.",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs.js",