promise-logic 2.6.5 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,10 +1,7 @@
1
-
2
-
3
-
4
1
  ### **1. Core Philosophy**
5
2
 
6
3
  **Replace API Memory with Logical Concepts**
7
- The design philosophy of `promise-logic` is: **Developers should focus on business logic, not the details of Promise APIs**.
4
+ The design philosophy of `promise-logic` is: **Developers should focus on business logic, not on details of Promise APIs**.
8
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.
9
6
  `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.
10
7
 
@@ -12,31 +9,34 @@ Traditional Promise combinations (such as `Promise.all`, `Promise.race`) have na
12
9
 
13
10
  ### **2. Features**
14
11
 
15
- 1. **Logical Semantics**
16
- - `and`: All tasks must succeed (equivalent to `Promise.all`)
17
- - `or`: At least one task succeeds (equivalent to `Promise.race`)
18
- - `xor`: **Exactly one task succeeds** (no direct equivalent in traditional Promise)
19
- - `nand`: All tasks fail
20
-
21
- - `not`: Inverts the result of a single Promise
22
- - `majority`: Most tasks succeed
23
-
24
- 2. **Zero Dependencies**
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
21
+
22
+ 2. **Zero Dependencies**
25
23
  Only depends on native Promise, no additional runtime dependencies.
26
24
 
27
- 3. **Full Test Coverage**
25
+ 3. **Full Test Coverage**
28
26
  All logic gates have undergone rigorous unit testing to ensure behavior meets expectations.
29
27
 
30
- 4. **Clear Error Classification**
31
- - `PromiseLogicError` unified error type
28
+ 4. **Clear Error Classification**
29
+ - `PromiseLogicError` unified error type
32
30
  - `error.type` distinguishes specific logical errors (e.g., `'XOR_ERROR'`)
33
31
 
34
- 5. **Timeout Control**
35
- - `maxTimer`: Adds timeout functionality to any Promise operation
32
+ 5. **Timeout Control**
33
+ - `maxTimer`: Adds timeout functionality to any Promise operation (unit: milliseconds).
36
34
 
37
- 6. **Extended Operations**
38
- - `allFulfilled`: Returns all successful results
39
- - `allRejected`: Returns all failed results
35
+ `maxTimer` can only detect timeout of Promise operations, cannot interrupt or cancel Promise operations themselves, this is a JavaScript characteristic.
36
+
37
+ 6. **Extended Operations**
38
+ - `allFulfilled`: Returns all successful results. Returns immediately when a result exists, while maintaining input order.
39
+ - `allRejected`: Returns all failed results. Returns immediately when a result exists, while maintaining input order.
40
40
  - `allSettled`: Returns all results (both successful and failed)
41
41
 
42
42
  ---
@@ -52,6 +52,7 @@ npm install promise-logic
52
52
  ### **4. Quick Start**
53
53
 
54
54
  #### Example: Primary/Backup Service Call (XOR Scenario)
55
+
55
56
  ```javascript
56
57
  import { PromiseLogic } from 'promise-logic';
57
58
 
@@ -62,10 +63,10 @@ const backup = fetch('https://api.backup.com/data');
62
63
 
63
64
  // Execute XOR logic: exactly one success
64
65
  PromiseLogic.xor([primary, backup])
65
- .then(result => {
66
+ .then((result) => {
66
67
  console.log('Successfully fetched data:', result);
67
68
  })
68
- .catch(error => {
69
+ .catch((error) => {
69
70
  if (error.type === 'XOR_ERROR') {
70
71
  console.error('Both primary and backup services succeeded or failed, which does not meet XOR semantics');
71
72
  } else {
@@ -75,6 +76,7 @@ PromiseLogic.xor([primary, backup])
75
76
  ```
76
77
 
77
78
  #### Example: Majority Decision (Majority Scenario)
79
+
78
80
  ```javascript
79
81
  import { PromiseLogic } from 'promise-logic';
80
82
 
@@ -85,10 +87,10 @@ const services = [
85
87
  ];
86
88
 
87
89
  PromiseLogic.majority(services)
88
- .then(results => {
90
+ .then((results) => {
89
91
  console.log('Majority of services returned success:', results);
90
92
  })
91
- .catch(error => {
93
+ .catch((error) => {
92
94
  console.error('Majority of services failed:', error);
93
95
  });
94
96
  ```
@@ -102,35 +104,38 @@ const services = [
102
104
  fetch('https://api.node3.com/vote')
103
105
  ];
104
106
 
107
+ // Type assertion can be done, or let PromiseLogic infer types automatically
105
108
  PromiseLogic.majority<Response>(services)
106
- .then(results => {
109
+ .then((results) => {
107
110
  console.log('Majority of services returned success:', results);
108
111
  })
109
- .catch(error => {
112
+ .catch((error) => {
110
113
  console.error('Majority of services failed:', error);
111
114
  });
112
115
  ```
113
116
 
114
117
  #### Example: Timeout Control
118
+
115
119
  ```javascript
116
120
  import { PromiseLogic } from 'promise-logic';
117
121
 
118
- // Execute operation with timeout
122
+ // Execute operation with custom timeout error message
119
123
  PromiseLogic.and([
120
124
  Promise.resolve(1),
121
- new Promise(resolve => setTimeout(resolve, 1000)), // 1 second operation
125
+ new Promise((resolve) => setTimeout(resolve, 3000)), // 3 second operation
122
126
  Promise.resolve(3)
123
127
  ])
124
- .maxTimer(2000) // 2 second timeout
125
- .then(result => {
126
- console.log('Operation completed within timeout:', result);
127
- })
128
- .catch(error => {
129
- console.error('Operation timed out or failed:', error.message);
130
- });
128
+ .maxTimer(2000, 'Custom timeout error: operation did not complete within 2000ms') // 2 second timeout, custom error message
129
+ .then((result) => {
130
+ console.log('Operation completed within timeout:', result);
131
+ })
132
+ .catch((error) => {
133
+ console.error('Operation timed out:', error.message); // Output: Custom timeout error: operation did not complete within 2000ms
134
+ });
131
135
  ```
132
136
 
133
137
  #### Example: Extended Operations
138
+
134
139
  ```javascript
135
140
  import { PromiseLogic } from 'promise-logic';
136
141
 
@@ -141,26 +146,105 @@ const operations = [
141
146
  Promise.reject('error2')
142
147
  ];
143
148
 
144
- // Get all successful results
145
- PromiseLogic.allFulfilled(operations)
146
- .then(results => {
147
- console.log('Successful results:', results); // ['success1', 'success2']
148
- });
149
+ // Get all successful results (returns immediately when a result exists)
150
+ PromiseLogic.allFulfilled(operations).then((results) => {
151
+ console.log('Successful results:', results); // ['success1', 'success2']
152
+ });
149
153
 
150
- // Get all failed results
151
- PromiseLogic.allRejected(operations)
152
- .then(errors => {
153
- console.log('Failed results:', errors); // ['error1', 'error2']
154
- });
154
+ // Get all failed results (returns immediately when a result exists)
155
+ PromiseLogic.allRejected(operations).then((errors) => {
156
+ console.log('Failed results:', errors); // ['error1', 'error2']
157
+ });
155
158
 
156
159
  // Get all results (both success and failure)
157
- PromiseLogic.allSettled(operations)
158
- .then(results => {
159
- console.log('All results:', results);
160
- });
160
+ PromiseLogic.allSettled(operations).then((results) => {
161
+ console.log('All results:', results);
162
+ // Output:
163
+ // [
164
+ // { status: 'fulfilled', value: 'success1' },
165
+ // { status: 'rejected', reason: 'error1' },
166
+ // { status: 'fulfilled', value: 'success2' },
167
+ // { status: 'rejected', reason: 'error2' }
168
+ // ]
169
+ });
170
+ ```
171
+
172
+ #### Example: allFulfilled - Execution Timing and Results
173
+
174
+ ```javascript
175
+ import { PromiseLogic } from 'promise-logic';
176
+
177
+ const startTime = Date.now();
178
+ console.log('Start executing allFulfilled, time:', startTime);
179
+
180
+ const allFulfilledResult = await PromiseLogic.allFulfilled([
181
+ new Promise(resolve => {
182
+ console.log('First Promise started (slow)');
183
+ setTimeout(() => {
184
+ console.log('First Promise completed:', 'success1');
185
+ resolve('success1');
186
+ }, 100);
187
+ }),
188
+ Promise.reject('error'),
189
+ new Promise(resolve => {
190
+ console.log('Third Promise started (fast)');
191
+ setTimeout(() => {
192
+ console.log('Third Promise completed:', 'success2');
193
+ resolve('success2');
194
+ }, 10);
195
+ })
196
+ ]);
197
+
198
+ const endTime = Date.now();
199
+ const elapsedTime = endTime - startTime;
200
+ console.log('allFulfilled complete results:', allFulfilledResult); // ['success1', 'success2']
201
+ ```
202
+
203
+ **Explanation:**
204
+ - **First return info**: Third Promise completes at 10ms, immediately returns `['success2']`
205
+ - **Complete return info**: First Promise completes at 100ms, final complete result is `['success1', 'success2']`
206
+ - **Execution timing**: Returns immediately when a result exists, does not wait for all Promises to complete
207
+ - **Order preservation**: Complete results are returned in input order, not completion order
208
+
209
+ #### Example: allRejected - Execution Timing and Results
210
+
211
+ ```javascript
212
+ import { PromiseLogic } from 'promise-logic';
213
+
214
+ const startTime = Date.now();
215
+ console.log('Start executing allRejected, time:', startTime);
216
+
217
+ const allRejectedResult = await PromiseLogic.allRejected([
218
+ Promise.resolve('success1'),
219
+ new Promise((_, reject) => {
220
+ console.log('Second Promise started (fast)');
221
+ setTimeout(() => {
222
+ console.log('Second Promise completed:', 'error1');
223
+ reject('error1');
224
+ }, 10);
225
+ }),
226
+ new Promise((_, reject) => {
227
+ console.log('Third Promise started (slow)');
228
+ setTimeout(() => {
229
+ console.log('Third Promise completed:', 'error2');
230
+ reject('error2');
231
+ }, 100);
232
+ })
233
+ ]);
234
+
235
+ const endTime = Date.now();
236
+ const elapsedTime = endTime - startTime;
237
+ console.log('allRejected complete results:', allRejectedResult); // ['error1', 'error2']
161
238
  ```
162
239
 
240
+ **Explanation:**
241
+ - **First return info**: Second Promise completes at 10ms, immediately returns `['error1']`
242
+ - **Complete return info**: Third Promise completes at 100ms, final complete result is `['error1', 'error2']`
243
+ - **Execution timing**: Returns immediately when a result exists, does not wait for all Promises to complete
244
+ - **Order preservation**: Complete results are returned in input order, not completion order
245
+
163
246
  #### Example: Custom majority threshold
247
+
164
248
  ```javascript
165
249
  import { PromiseLogic } from 'promise-logic';
166
250
 
@@ -174,68 +258,151 @@ const services = [
174
258
  // Default threshold (0.5): requires at least 3 successes
175
259
  // Custom threshold (0.4): requires at least 2 successes
176
260
  PromiseLogic.majority(services, { max: 0.4 })
177
- .then(results => {
261
+ .then((results) => {
178
262
  console.log('Custom threshold met, successful results:', results); // ['service1', 'service2']
179
263
  })
180
- .catch(error => {
264
+ .catch((error) => {
181
265
  console.error('Custom threshold not met:', error);
182
266
  });
183
267
  ```
184
268
 
185
- ---
269
+ ## Recent Updates
186
270
 
187
- ### **5. API Reference**
271
+ ### v2.8.0
272
+
273
+ - **Performance optimization**: Optimized `allFulfilled` and `allRejected` implementation logic from the bottom layer, existing results return immediately while maintaining consistent input and output order
274
+ - **Added chain timeout control with custom error messages**: Can customize timeout error messages in the `maxTimer` method
275
+ - **Type fixes**: Fixed TypeScript version type declaration issues
276
+ - **Test completion**: Added complete test cases for `allFulfilled`, `allRejected`, and `maxTimer`
277
+ - **Code refactoring**: Improved code structure for better maintainability
278
+
279
+ ### v2.7.0
280
+
281
+ - **Added modular architecture**: Separated logic gate implementations into independent modules for better code maintainability
282
+ - **Fixed NOT Logic Gate**: Fixed potential risks in NOT logic gate in production environments
283
+ - **Improved Error Messages**: Enhanced error message format for clearer error details
284
+ - **Enhanced Test Coverage**: Added complete factory function tests for v1 and v2 versions
285
+ - **Updated Documentation**: Added custom factory function usage guide
286
+
287
+
288
+ ### Using Factory Function
289
+
290
+ The factory function allows you to create PromiseLogic methods with custom names:
291
+
292
+ ```javascript
293
+ import { createPromiseLogic } from 'promise-logic/factory';
294
+
295
+ // Create instance with custom naming
296
+ const logic = createPromiseLogic({
297
+ prefix: 'api_',
298
+ suffix: '_call',
299
+ rename: {
300
+ and: 'all',
301
+ or: 'any',
302
+ xor: 'exclusive'
303
+ }
304
+ });
305
+
306
+ // Use custom-named methods
307
+ logic.api_all_call([fetch('/api/users'), fetch('/api/posts')]);
308
+
309
+ logic.api_any_call([fetch('/api/cache'), fetch('/api/database')]);
310
+ ```
188
311
 
189
- | API | Description |
190
- | :------------ | :-------------------------------------------------------------------------- |
191
- | `and` | All Promises succeed, returns result array; any failure causes overall failure. |
192
- | `or` | At least one Promise succeeds, returns first success result; all failures cause overall failure. |
193
- | `xor` | **Exactly one Promise succeeds**, returns that result; otherwise throws `XOR_ERROR`. |
194
- | `nand` | All Promises fail, returns error array; any success causes overall failure. |
195
- | `not` | Inverts the result of a single Promise |
196
- | `majority` | More than half of Promises succeed, returns success result array; otherwise overall failure. Accepts `options` parameter, where `max` property can customize threshold (default: 0.5). |
197
- | `allFulfilled` | Returns all successful results as an array, ignoring failures. |
198
- | `allRejected` | Returns all failed results as an array, ignoring successes. |
199
- | `allSettled` | Returns all results (both successful and failed) as an array. |
200
- | `maxTimer` | Adds timeout functionality to any Promise operation (unit: milliseconds). |
312
+ ### TypeScript Support
313
+
314
+ ```typescript
315
+ import { PromiseLogic } from 'promise-logic/typescript';
316
+
317
+ // Type inference
318
+ PromiseLogic.and([Promise.resolve(1), Promise.resolve(2)]).then(
319
+ (results: number[]) => {
320
+ console.log(results);
321
+ }
322
+ );
323
+
324
+ // Type assertion
325
+ PromiseLogic.and<number>([Promise.resolve(1), Promise.resolve(2)]);
326
+ ```
201
327
 
202
328
  ---
203
329
 
330
+ ### **5. API Reference**
331
+
332
+ | API | Description |
333
+ | :------------- | :--------------------------------------------------------------------------------------------------------------------------- |
334
+ | `and` | All Promises succeed, returns result array; any failure causes overall failure. Equivalent to native `Promise.all`. |
335
+ | `or` | At least one Promise succeeds, returns first success result; all failures cause overall failure. Equivalent to native `Promise.any`. |
336
+ | `xor` | **Exactly one Promise succeeds**, returns that result; otherwise throws `XOR_ERROR`. |
337
+ | `nand` | Not all Promises succeed (at least one fails), returns success result array; all succeed causes overall failure. |
338
+ | `nor` | All Promises fail (no task succeeds), returns empty array; any success causes overall failure. |
339
+ | `xnor` | All Promises succeed or all fail (same state), returns success result array; otherwise throws `XNOR_ERROR`. |
340
+ | `not` | Inverts the result of a single Promise: success becomes failure, failure becomes success. |
341
+ | `majority` | More than specified threshold of Promises succeed, returns success result array; otherwise overall failure. Accepts `options` parameter, where `max` property can customize threshold (default: 0.5), range: (0, 1). |
342
+ | `allFulfilled` | Returns all successful results as an array, ignoring failures. Returns immediately when a result exists, while maintaining input order. |
343
+ | `allRejected` | Returns all failed results as an array, ignoring successes. Returns immediately when a result exists, while maintaining input order. |
344
+ | `allSettled` | Returns all results (both successful and failed) as an array. Equivalent to native `Promise.allSettled`. |
345
+ | `race` | Returns the first completed Promise result (regardless of success or failure). Equivalent to native `Promise.race`. |
346
+ | `maxTimer` | Adds timeout functionality to any Promise operation (unit: milliseconds). Supports custom timeout error messages. |
347
+
348
+ ## **Note**: `maxTimer` can only detect timeout of Promise operations, cannot interrupt or cancel Promise operations themselves, this is a JavaScript characteristic.
349
+
204
350
  ### **6. Real-world Application Scenarios**
205
351
 
206
- 1. **Primary/Backup Service Calls**
207
- - Use `xor` to ensure **exactly one service responds**, avoiding duplicate processing.
208
- 2. **Distributed Decision Making**
209
- - Use `majority` to implement majority consensus (e.g., distributed voting).
210
- 3. **Resource Competition**
211
- - Use `or` to get the first available resource (e.g., CDN node selection).
212
- - Use `not` to check if a resource is available.
213
- 4. **Full-link Validation**
214
- - Use `and` to ensure all dependent services succeed (e.g., order creation).
352
+ 1. **Primary/Backup Service Calls**
353
+ - Use `xor` to ensure **exactly one service responds**, avoiding duplicate processing.
354
+
355
+ 2. **Distributed Decision Making**
356
+ - Use `majority` to implement majority consensus (e.g., distributed voting).
357
+
358
+ 3. **Resource Competition**
359
+ - Use `or` to get the first available resource (e.g., CDN node selection).
360
+ - Use `not` to check if a resource is available.
361
+
362
+ 4. **Full-link Validation**
363
+ - Use `and` to ensure all dependent services succeed (e.g., order creation).
364
+
365
+ 5. **Timeout Control**
366
+ - Use `maxTimer` to add timeout functionality to any Promise operation (unit: milliseconds).
367
+ - Returns custom error message after timeout, default: `Promise timed out after ${ms} ms`.
368
+
369
+ 6. **Partial Success Handling**
370
+ - 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).
371
+ - Use `allRejected` to execute all Promises concurrently and return failed result array (e.g., error log collection, suitable for batch failure processing scenarios).
372
+
373
+ 7. **Full Result Retrieval**
374
+ - Use `allSettled` to get results from all Promises (regardless of success or failure).
375
+
376
+ 8. **Fast Response**
377
+ - Use `race` to return the first completed Promise result (regardless of success or failure).
378
+
379
+ 9. **State Validation**
380
+ - Use `nand` to verify that not all Promises succeed (at least one fails).
381
+ - Use `nor` to verify that all Promises fail (no task succeeds).
382
+ - Use `xnor` to verify that all Promises succeed or all fail (same state).
215
383
 
216
384
  ---
217
385
 
218
386
  ### **7. Contribution Guide**
219
387
 
220
- 1. **Development Environment**
388
+ 1. **Development Environment**
221
389
  ```bash
222
- git clone https://github.com/haowhite/promise-logic.git
390
+ git clone https://github.com/xier123456/promise-logic.git
223
391
  cd promise-logic
224
392
  npm install
225
393
  ```
226
- 2. **Testing**
394
+ 2. **Testing**
227
395
  ```bash
228
396
  npm test
229
397
  ```
230
- 3. **Commit Guidelines**
231
- - Commit messages must include prefixes like `feat:` (new feature), `fix:` (bug fix), `docs:` (documentation).
232
- - Pull Requests must include test cases.
398
+ 3. **Commit Guidelines**
399
+ - Commit messages must include prefixes like `feat:` (new feature), `fix:` (bug fix), `docs:` (documentation).
400
+ - Pull Requests must include test cases.
233
401
 
234
402
  ---
235
403
 
236
404
  ### **8. Resource Links**
237
405
 
238
- - **GitHub Repository**:[https://github.com/xier123456/promise-logic](https://github.com/xier123456/promise-logic)
239
- - **npm Package**:[https://www.npmjs.com/package/promise-logic](https://www.npmjs.com/package/promise-logic)
240
- - **Issue Tracking**:[GitHub Issues](https://github.com/xier123456/promise-logic/issues)
241
-
406
+ - **GitHub Repository**: [https://github.com/xier123456/promise-logic](https://github.com/xier123456/promise-logic)
407
+ - **npm Package**: [https://www.npmjs.com/package/promise-logic](https://www.npmjs.com/package/promise-logic)
408
+ - **Issue Tracking**: [GitHub Issues](https://github.com/xier123456/promise-logic/issues)
@@ -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,i){return new e(t,{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]||"Logic condition failed",i)}class r{constructor(e){this.promise=e}maxTimer(e){let t;return Promise.race([this.promise,new Promise((r,l)=>{t=setTimeout(()=>{l(new Error(`Promise timed out after ${e}ms`))},e)})]).finally(()=>clearTimeout(t))}then(e,t){return new r(this.promise.then(e,t))}catch(e){return new r(this.promise.catch(e))}finally(e){return new r(this.promise.finally(e))}toPromise(){return this.promise}}class l{static and(e){return new r(Promise.all(e))}static or(e){return new r(Promise.any(e))}static not(e){return new r(Promise.resolve(e).then(e=>Promise.reject(e),e=>Promise.resolve(e)).catch(e=>Promise.resolve(e)))}static race(e){return new r(Promise.race(e))}static allSettled(e){return new r(Promise.allSettled(e))}static xor(e){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status),l=r.length,i=e.length;if(1===l)return r[0].value;throw t("XOR_ERROR",l,i,e)}))}static nand(e){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status),l=r.length,i=e.length;if(l===i)throw t("NAND_ERROR",l,i,e);return r.map(e=>e.value)}))}static nor(e){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status).length,l=e.length;if(0===r)return[];throw t("NOR_ERROR",r,l,e)}))}static xnor(e){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status),l=r.length,i=e.length;if(0===l||l===i)return r.map(e=>e.value);throw t("XNOR_ERROR",l,i,e)}))}static majority(e,l={max:.5}){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status),i=r.length,n=e.length;if(i>n*l.max)return r.map(e=>e.value);throw t("MAJORITY_ERROR",i,n,e)}))}static allFulfilled(e){return new r(Promise.allSettled(e).then(e=>e.filter(e=>"fulfilled"===e.status).map(e=>e.value)))}static allRejected(e){return new r(Promise.allSettled(e).then(e=>e.filter(e=>"rejected"===e.status).map(e=>e.reason)))}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:i={}}=e,n={and:l.and.bind(l),or:l.or.bind(l),race:l.race.bind(l),allSettled:l.allSettled.bind(l),xor:l.xor.bind(l),not:l.not.bind(l),nand:l.nand.bind(l),nor:l.nor.bind(l),xnor:l.xnor.bind(l),majority:l.majority.bind(l),allFulfilled:l.allFulfilled.bind(l),allRejected:l.allRejected.bind(l)},o={};return Object.entries(n).forEach(([e,l])=>{const n=i[e]||e;o[`${t}${n}${r}`]=l}),o};
1
+ "use strict";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,[...e],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;0!==([...e]?.length??0)?e.forEach((e,n)=>{e.then(e=>{r++,l[n]=e}).catch(()=>{l[n]=void 0}).finally(()=>{r>0&&t(l.filter(e=>void 0!==e))})}):t(l)})}}class d extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let r=0;0!==([...e]?.length??0)?e.forEach((e,n)=>{e.then(()=>{l[n]=void 0}).catch(e=>{r++,l[n]=e}).finally(()=>{r>0&&t(l.filter(e=>void 0!==e))})}):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()})}}}}exports.createPromiseLogic=function(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};
@@ -1 +1 @@
1
- class e extends Error{constructor(e,t,r){super(t),this.name="PromiseLogicError",this.type=e,this.results=r}}function t(t,r,l,i){return new e(t,{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]||"Logic condition failed",i)}class r{constructor(e){this.promise=e}maxTimer(e){let t;return Promise.race([this.promise,new Promise((r,l)=>{t=setTimeout(()=>{l(new Error(`Promise timed out after ${e}ms`))},e)})]).finally(()=>clearTimeout(t))}then(e,t){return new r(this.promise.then(e,t))}catch(e){return new r(this.promise.catch(e))}finally(e){return new r(this.promise.finally(e))}toPromise(){return this.promise}}class l{static and(e){return new r(Promise.all(e))}static or(e){return new r(Promise.any(e))}static not(e){return new r(Promise.resolve(e).then(e=>Promise.reject(e),e=>Promise.resolve(e)).catch(e=>Promise.resolve(e)))}static race(e){return new r(Promise.race(e))}static allSettled(e){return new r(Promise.allSettled(e))}static xor(e){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status),l=r.length,i=e.length;if(1===l)return r[0].value;throw t("XOR_ERROR",l,i,e)}))}static nand(e){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status),l=r.length,i=e.length;if(l===i)throw t("NAND_ERROR",l,i,e);return r.map(e=>e.value)}))}static nor(e){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status).length,l=e.length;if(0===r)return[];throw t("NOR_ERROR",r,l,e)}))}static xnor(e){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status),l=r.length,i=e.length;if(0===l||l===i)return r.map(e=>e.value);throw t("XNOR_ERROR",l,i,e)}))}static majority(e,l={max:.5}){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status),i=r.length,n=e.length;if(i>n*l.max)return r.map(e=>e.value);throw t("MAJORITY_ERROR",i,n,e)}))}static allFulfilled(e){return new r(Promise.allSettled(e).then(e=>e.filter(e=>"fulfilled"===e.status).map(e=>e.value)))}static allRejected(e){return new r(Promise.allSettled(e).then(e=>e.filter(e=>"rejected"===e.status).map(e=>e.reason)))}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()})}}}}function i(e={}){const{prefix:t="",suffix:r="",rename:i={}}=e,n={and:l.and.bind(l),or:l.or.bind(l),race:l.race.bind(l),allSettled:l.allSettled.bind(l),xor:l.xor.bind(l),not:l.not.bind(l),nand:l.nand.bind(l),nor:l.nor.bind(l),xnor:l.xnor.bind(l),majority:l.majority.bind(l),allFulfilled:l.allFulfilled.bind(l),allRejected:l.allRejected.bind(l)},o={};return Object.entries(n).forEach(([e,l])=>{const n=i[e]||e;o[`${t}${n}${r}`]=l}),o}export{i as createPromiseLogic};
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,[...e],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;0!==([...e]?.length??0)?e.forEach((e,n)=>{e.then(e=>{r++,l[n]=e}).catch(()=>{l[n]=void 0}).finally(()=>{r>0&&t(l.filter(e=>void 0!==e))})}):t(l)})}}class d extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let r=0;0!==([...e]?.length??0)?e.forEach((e,n)=>{e.then(()=>{l[n]=void 0}).catch(e=>{r++,l[n]=e}).finally(()=>{r>0&&t(l.filter(e=>void 0!==e))})}):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};
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,i){return new e(t,{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]||"Logic condition failed",i)}class r{constructor(e){this.promise=e}maxTimer(e){let t;return Promise.race([this.promise,new Promise((r,l)=>{t=setTimeout(()=>{l(new Error(`Promise timed out after ${e}ms`))},e)})]).finally(()=>clearTimeout(t))}then(e,t){return new r(this.promise.then(e,t))}catch(e){return new r(this.promise.catch(e))}finally(e){return new r(this.promise.finally(e))}toPromise(){return this.promise}}class l{static and(e){return new r(Promise.all(e))}static or(e){return new r(Promise.any(e))}static not(e){return new r(Promise.resolve(e).then(e=>Promise.reject(e),e=>Promise.resolve(e)).catch(e=>Promise.resolve(e)))}static race(e){return new r(Promise.race(e))}static allSettled(e){return new r(Promise.allSettled(e))}static xor(e){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status),l=r.length,i=e.length;if(1===l)return r[0].value;throw t("XOR_ERROR",l,i,e)}))}static nand(e){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status),l=r.length,i=e.length;if(l===i)throw t("NAND_ERROR",l,i,e);return r.map(e=>e.value)}))}static nor(e){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status).length,l=e.length;if(0===r)return[];throw t("NOR_ERROR",r,l,e)}))}static xnor(e){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status),l=r.length,i=e.length;if(0===l||l===i)return r.map(e=>e.value);throw t("XNOR_ERROR",l,i,e)}))}static majority(e,l={max:.5}){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status),i=r.length,n=e.length;if(i>n*l.max)return r.map(e=>e.value);throw t("MAJORITY_ERROR",i,n,e)}))}static allFulfilled(e){return new r(Promise.allSettled(e).then(e=>e.filter(e=>"fulfilled"===e.status).map(e=>e.value)))}static allRejected(e){return new r(Promise.allSettled(e).then(e=>e.filter(e=>"rejected"===e.status).map(e=>e.reason)))}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=l,exports.PromiseLogicError=e,exports.PromiseWithTimer=r,exports.createLogicError=t,exports.createPromiseLogic=function(e={}){const{prefix:t="",suffix:r="",rename:i={}}=e,n={and:l.and.bind(l),or:l.or.bind(l),race:l.race.bind(l),allSettled:l.allSettled.bind(l),xor:l.xor.bind(l),not:l.not.bind(l),nand:l.nand.bind(l),nor:l.nor.bind(l),xnor:l.xnor.bind(l),majority:l.majority.bind(l),allFulfilled:l.allFulfilled.bind(l),allRejected:l.allRejected.bind(l)},o={};return Object.entries(n).forEach(([e,l])=>{const n=i[e]||e;o[`${t}${n}${r}`]=l}),o};
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],a=n.length>0?`\n失败原因:${n.map((e,t)=>`[${t+1}] ${e}`).join("\n")}`:"";return new e(t,i+a,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,[...e],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,a=l.length;if(1===i)return s[0];throw t("XOR_ERROR",i,a,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 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)return[];throw t("NOR_ERROR",n,i,l,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||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;0!==([...e]?.length??0)?e.forEach((e,s)=>{e.then(e=>{l++,r[s]=e}).catch(()=>{r[s]=void 0}).finally(()=>{l>0&&t(r.filter(e=>void 0!==e))})}):t(r)})}}class d extends r{async execute(e,t={}){return new Promise(t=>{const r=[];let l=0;0!==([...e]?.length??0)?e.forEach((e,s)=>{e.then(()=>{r[s]=void 0}).catch(e=>{l++,r[s]=e}).finally(()=>{l>0&&t(r.filter(e=>void 0!==e))})}):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 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.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};
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- class e extends Error{constructor(e,t,r){super(t),this.name="PromiseLogicError",this.type=e,this.results=r}}function t(t,r,l,i){return new e(t,{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]||"Logic condition failed",i)}class r{constructor(e){this.promise=e}maxTimer(e){let t;return Promise.race([this.promise,new Promise((r,l)=>{t=setTimeout(()=>{l(new Error(`Promise timed out after ${e}ms`))},e)})]).finally(()=>clearTimeout(t))}then(e,t){return new r(this.promise.then(e,t))}catch(e){return new r(this.promise.catch(e))}finally(e){return new r(this.promise.finally(e))}toPromise(){return this.promise}}class l{static and(e){return new r(Promise.all(e))}static or(e){return new r(Promise.any(e))}static not(e){return new r(Promise.resolve(e).then(e=>Promise.reject(e),e=>Promise.resolve(e)).catch(e=>Promise.resolve(e)))}static race(e){return new r(Promise.race(e))}static allSettled(e){return new r(Promise.allSettled(e))}static xor(e){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status),l=r.length,i=e.length;if(1===l)return r[0].value;throw t("XOR_ERROR",l,i,e)}))}static nand(e){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status),l=r.length,i=e.length;if(l===i)throw t("NAND_ERROR",l,i,e);return r.map(e=>e.value)}))}static nor(e){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status).length,l=e.length;if(0===r)return[];throw t("NOR_ERROR",r,l,e)}))}static xnor(e){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status),l=r.length,i=e.length;if(0===l||l===i)return r.map(e=>e.value);throw t("XNOR_ERROR",l,i,e)}))}static majority(e,l={max:.5}){return new r(Promise.allSettled(e).then(e=>{const r=e.filter(e=>"fulfilled"===e.status),i=r.length,n=e.length;if(i>n*l.max)return r.map(e=>e.value);throw t("MAJORITY_ERROR",i,n,e)}))}static allFulfilled(e){return new r(Promise.allSettled(e).then(e=>e.filter(e=>"fulfilled"===e.status).map(e=>e.value)))}static allRejected(e){return new r(Promise.allSettled(e).then(e=>e.filter(e=>"rejected"===e.status).map(e=>e.reason)))}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()})}}}}function i(e={}){const{prefix:t="",suffix:r="",rename:i={}}=e,n={and:l.and.bind(l),or:l.or.bind(l),race:l.race.bind(l),allSettled:l.allSettled.bind(l),xor:l.xor.bind(l),not:l.not.bind(l),nand:l.nand.bind(l),nor:l.nor.bind(l),xnor:l.xnor.bind(l),majority:l.majority.bind(l),allFulfilled:l.allFulfilled.bind(l),allRejected:l.allRejected.bind(l)},o={};return Object.entries(n).forEach(([e,l])=>{const n=i[e]||e;o[`${t}${n}${r}`]=l}),o}export{l as PromiseLogic,e as PromiseLogicError,r as PromiseWithTimer,t as createLogicError,i as createPromiseLogic};
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,[...e],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;0!==([...e]?.length??0)?e.forEach((e,n)=>{e.then(e=>{r++,l[n]=e}).catch(()=>{l[n]=void 0}).finally(()=>{r>0&&t(l.filter(e=>void 0!==e))})}):t(l)})}}class d extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let r=0;0!==([...e]?.length??0)?e.forEach((e,n)=>{e.then(()=>{l[n]=void 0}).catch(e=>{r++,l[n]=e}).finally(()=>{r>0&&t(l.filter(e=>void 0!==e))})}):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 +1 @@
1
- "use strict";class e{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 t extends e{async execute(e){return Promise.any(e)}}class l extends Error{constructor(e,t,l){super(t),this.type=e,this.results=l,this.name="PromiseLogicError"}}function r(e,t,r,s){return new l(e,{XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${t} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${r} promises fulfilled (expected at least one rejection).`,NOR_ERROR:`NOR condition failed: ${t} promises fulfilled (expected all rejected).`,XNOR_ERROR:`XNOR condition failed: ${t}/${r} promises fulfilled (expected all or none).`,MAJORITY_ERROR:`Majority condition failed: ${t}/${r} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${t}/${r} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${r-t}/${r} promises rejected (expected all to fail).`}[e]||"Logic condition failed",s)}class s extends e{async execute(e){try{return Promise.all(e)}catch(e){throw new l("AND_ERROR","AND gate failed",[e])}}}class i extends e{async execute(e,t){const l=await Promise.allSettled(e),s=this.filterFulfilledResults(l),i=s.length,n=l.length;if(i>n*t.max)return s;throw r("MAJORITY_ERROR",i,n,l)}}class n extends e{async execute(e){const t=await Promise.allSettled(e),l=this.filterFulfilledResults(t),s=l.length,i=t.length;if(s===i)throw r("NAND_ERROR",s,i,t);return l}}class a extends e{async execute(e){const t=await Promise.allSettled(e),l=this.filterFulfilledResults(t).length,s=t.length;if(0===l)return[];throw r("NOR_ERROR",l,s,t)}}class o extends e{async execute(e){const t=await Promise.allSettled(e),l=this.filterFulfilledResults(t),s=l.length,i=t.length;if(0===s||s===i)return l;throw r("XNOR_ERROR",s,i,t)}}class c extends e{async execute(e){const t=await Promise.allSettled(e),l=this.filterFulfilledResults(t),s=l.length,i=t.length;if(1===s)return l[0];throw r("XOR_ERROR",s,i,t)}}class u{constructor(e){this.promise=e}maxTimer(e){let t;return Promise.race([this.promise,new Promise((l,r)=>{t=setTimeout(()=>{r(new Error(`Promise timed out after ${e}ms,${this.promise}`))},e)})]).finally(()=>clearTimeout(t))}then(e,t){return new u(this.promise.then(e,t))}catch(e){return new u(this.promise.catch(e))}finally(e){return new u(this.promise.finally(e))}toPromise(){return this.promise}}class d{static get gates(){return{and:new s,or:new t,xor:new c,nand:new n,nor:new a,xnor:new o,majority:new i}}static and(e){return new u(this.gates.and.execute(e))}static or(e){return new u(this.gates.or.execute(e))}static xor(e){return new u(this.gates.xor.execute(e))}static nand(e){return new u(this.gates.nand.execute(e))}static nor(e){return new u(this.gates.nor.execute(e))}static xnor(e){return new u(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new u(this.gates.majority.execute(e,t))}static allFulfilled(e){return new u(Promise.allSettled(e).then(e=>e.filter(e=>"fulfilled"===e.status).map(e=>e.value)))}static allRejected(e){return new u(Promise.allSettled(e).then(e=>e.filter(e=>"rejected"===e.status).map(e=>e.reason)))}static not(e){return new u(Promise.resolve(e).then(e=>Promise.reject(e),e=>Promise.resolve(e)))}static race(e){return new u(Promise.race(e))}static allSettled(e){return new u(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.createPromiseLogic=function(e={}){const{prefix:t="",suffix:l="",rename:r={}}=e,s={and:d.and.bind(d),or:d.or.bind(d),not:d.not.bind(d),race:d.race.bind(d),allSettled:d.allSettled.bind(d),xor:d.xor.bind(d),nand:d.nand.bind(d),nor:d.nor.bind(d),xnor:d.xnor.bind(d),majority:d.majority.bind(d),allFulfilled:d.allFulfilled.bind(d),allRejected:d.allRejected.bind(d)},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,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;const r=[...e];0!==(r?.length??0)?r.forEach((e,r)=>{Promise.resolve(e).then(e=>{s++,l[r]=e}).catch(()=>{l[r]=void 0}).finally(()=>{s>0&&t(l.filter(e=>void 0!==e))})}):t(l)})}}class d extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let s=0;const r=[...e];0!==(r?.length??0)?r.forEach((e,r)=>{Promise.resolve(e).then(()=>{l[r]=void 0}).catch(e=>{s++,l[r]=e}).finally(()=>{s>0&&t(l.filter(e=>void 0!==e))})}):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 +1 @@
1
- class e{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 t extends e{async execute(e){return Promise.any(e)}}class l extends Error{constructor(e,t,l){super(t),this.type=e,this.results=l,this.name="PromiseLogicError"}}function r(e,t,r,n){return new l(e,{XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${t} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${r} promises fulfilled (expected at least one rejection).`,NOR_ERROR:`NOR condition failed: ${t} promises fulfilled (expected all rejected).`,XNOR_ERROR:`XNOR condition failed: ${t}/${r} promises fulfilled (expected all or none).`,MAJORITY_ERROR:`Majority condition failed: ${t}/${r} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${t}/${r} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${r-t}/${r} promises rejected (expected all to fail).`}[e]||"Logic condition failed",n)}class n extends e{async execute(e){try{return Promise.all(e)}catch(e){throw new l("AND_ERROR","AND gate failed",[e])}}}class s extends e{async execute(e,t){const l=await Promise.allSettled(e),n=this.filterFulfilledResults(l),s=n.length,i=l.length;if(s>i*t.max)return n;throw r("MAJORITY_ERROR",s,i,l)}}class i extends e{async execute(e){const t=await Promise.allSettled(e),l=this.filterFulfilledResults(t),n=l.length,s=t.length;if(n===s)throw r("NAND_ERROR",n,s,t);return l}}class a extends e{async execute(e){const t=await Promise.allSettled(e),l=this.filterFulfilledResults(t).length,n=t.length;if(0===l)return[];throw r("NOR_ERROR",l,n,t)}}class o extends e{async execute(e){const t=await Promise.allSettled(e),l=this.filterFulfilledResults(t),n=l.length,s=t.length;if(0===n||n===s)return l;throw r("XNOR_ERROR",n,s,t)}}class c extends e{async execute(e){const t=await Promise.allSettled(e),l=this.filterFulfilledResults(t),n=l.length,s=t.length;if(1===n)return l[0];throw r("XOR_ERROR",n,s,t)}}class u{constructor(e){this.promise=e}maxTimer(e){let t;return Promise.race([this.promise,new Promise((l,r)=>{t=setTimeout(()=>{r(new Error(`Promise timed out after ${e}ms,${this.promise}`))},e)})]).finally(()=>clearTimeout(t))}then(e,t){return new u(this.promise.then(e,t))}catch(e){return new u(this.promise.catch(e))}finally(e){return new u(this.promise.finally(e))}toPromise(){return this.promise}}class d{static get gates(){return{and:new n,or:new t,xor:new c,nand:new i,nor:new a,xnor:new o,majority:new s}}static and(e){return new u(this.gates.and.execute(e))}static or(e){return new u(this.gates.or.execute(e))}static xor(e){return new u(this.gates.xor.execute(e))}static nand(e){return new u(this.gates.nand.execute(e))}static nor(e){return new u(this.gates.nor.execute(e))}static xnor(e){return new u(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new u(this.gates.majority.execute(e,t))}static allFulfilled(e){return new u(Promise.allSettled(e).then(e=>e.filter(e=>"fulfilled"===e.status).map(e=>e.value)))}static allRejected(e){return new u(Promise.allSettled(e).then(e=>e.filter(e=>"rejected"===e.status).map(e=>e.reason)))}static not(e){return new u(Promise.resolve(e).then(e=>Promise.reject(e),e=>Promise.resolve(e)))}static race(e){return new u(Promise.race(e))}static allSettled(e){return new u(Promise.allSettled(e))}static createFlipFlop(e=!1){let t=e,l=null,r=Promise.resolve(t);const n=()=>(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:n,waitFor:e=>t===e?Promise.resolve(t):new Promise(l=>{const r=()=>{t===e?l(t):n().then(r)};r()})}}}function f(e={}){const{prefix:t="",suffix:l="",rename:r={}}=e,n={and:d.and.bind(d),or:d.or.bind(d),not:d.not.bind(d),race:d.race.bind(d),allSettled:d.allSettled.bind(d),xor:d.xor.bind(d),nand:d.nand.bind(d),nor:d.nor.bind(d),xnor:d.xnor.bind(d),majority:d.majority.bind(d),allFulfilled:d.allFulfilled.bind(d),allRejected:d.allRejected.bind(d)},s={};return Object.entries(n).forEach(([e,n])=>{const i=r[e]||e;s[`${t}${i}${l}`]=n}),s}export{f as createPromiseLogic};
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;const r=[...e];0!==(r?.length??0)?r.forEach((e,r)=>{Promise.resolve(e).then(e=>{s++,l[r]=e}).catch(()=>{l[r]=void 0}).finally(()=>{s>0&&t(l.filter(e=>void 0!==e))})}):t(l)})}}class d extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let s=0;const r=[...e];0!==(r?.length??0)?r.forEach((e,r)=>{Promise.resolve(e).then(()=>{l[r]=void 0}).catch(e=>{s++,l[r]=e}).finally(()=>{s>0&&t(l.filter(e=>void 0!==e))})}):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 +1 @@
1
- "use strict";class e{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 t extends e{async execute(e){return Promise.any(e)}}class r extends Error{constructor(e,t,r){super(t),this.type=e,this.results=r,this.name="PromiseLogicError"}}function l(e,t,l,s){return new r(e,{XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${t} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${l} promises fulfilled (expected at least one rejection).`,NOR_ERROR:`NOR condition failed: ${t} promises fulfilled (expected all rejected).`,XNOR_ERROR:`XNOR condition failed: ${t}/${l} promises fulfilled (expected all or none).`,MAJORITY_ERROR:`Majority condition failed: ${t}/${l} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${t}/${l} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${l-t}/${l} promises rejected (expected all to fail).`}[e]||"Logic condition failed",s)}class s extends e{async execute(e){try{return Promise.all(e)}catch(e){throw new r("AND_ERROR","AND gate failed",[e])}}}class i extends e{async execute(e,t){const r=await Promise.allSettled(e),s=this.filterFulfilledResults(r),i=s.length,n=r.length;if(i>n*t.max)return s;throw l("MAJORITY_ERROR",i,n,r)}}class n extends e{async execute(e){const t=await Promise.allSettled(e),r=this.filterFulfilledResults(t),s=r.length,i=t.length;if(s===i)throw l("NAND_ERROR",s,i,t);return r}}class a extends e{async execute(e){const t=await Promise.allSettled(e),r=this.filterFulfilledResults(t).length,s=t.length;if(0===r)return[];throw l("NOR_ERROR",r,s,t)}}class o extends e{async execute(e){const t=await Promise.allSettled(e),r=this.filterFulfilledResults(t),s=r.length,i=t.length;if(0===s||s===i)return r;throw l("XNOR_ERROR",s,i,t)}}class c extends e{async execute(e){const t=await Promise.allSettled(e),r=this.filterFulfilledResults(t),s=r.length,i=t.length;if(1===s)return r[0];throw l("XOR_ERROR",s,i,t)}}class u{constructor(e){this.promise=e}maxTimer(e){let t;return Promise.race([this.promise,new Promise((r,l)=>{t=setTimeout(()=>{l(new Error(`Promise timed out after ${e}ms,${this.promise}`))},e)})]).finally(()=>clearTimeout(t))}then(e,t){return new u(this.promise.then(e,t))}catch(e){return new u(this.promise.catch(e))}finally(e){return new u(this.promise.finally(e))}toPromise(){return this.promise}}class d{static get gates(){return{and:new s,or:new t,xor:new c,nand:new n,nor:new a,xnor:new o,majority:new i}}static and(e){return new u(this.gates.and.execute(e))}static or(e){return new u(this.gates.or.execute(e))}static xor(e){return new u(this.gates.xor.execute(e))}static nand(e){return new u(this.gates.nand.execute(e))}static nor(e){return new u(this.gates.nor.execute(e))}static xnor(e){return new u(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new u(this.gates.majority.execute(e,t))}static allFulfilled(e){return new u(Promise.allSettled(e).then(e=>e.filter(e=>"fulfilled"===e.status).map(e=>e.value)))}static allRejected(e){return new u(Promise.allSettled(e).then(e=>e.filter(e=>"rejected"===e.status).map(e=>e.reason)))}static not(e){return new u(Promise.resolve(e).then(e=>Promise.reject(e),e=>Promise.resolve(e)))}static race(e){return new u(Promise.race(e))}static allSettled(e){return new u(Promise.allSettled(e))}static createFlipFlop(e=!1){let t=e,r=null,l=Promise.resolve(t);const s=()=>(r||(l=new Promise(e=>{r=e})),l);return{getState:()=>t,set:async e=>(t=e,r&&(r(t),r=null),l=Promise.resolve(t),t),async toggle(){return this.set(!t)},waitForChange:s,waitFor:e=>t===e?Promise.resolve(t):new Promise(r=>{const l=()=>{t===e?r(t):s().then(l)};l()})}}}exports.PromiseLogic=d,exports.PromiseLogicError=r,exports.PromiseWithTimer=u,exports.createPromiseLogic=function(e={}){const{prefix:t="",suffix:r="",rename:l={}}=e,s={and:d.and.bind(d),or:d.or.bind(d),not:d.not.bind(d),race:d.race.bind(d),allSettled:d.allSettled.bind(d),xor:d.xor.bind(d),nand:d.nand.bind(d),nor:d.nor.bind(d),xnor:d.xnor.bind(d),majority:d.majority.bind(d),allFulfilled:d.allFulfilled.bind(d),allRejected:d.allRejected.bind(d)},i={};return Object.entries(s).forEach(([e,s])=>{const n=l[e]||e;i[`${t}${n}${r}`]=s}),i};
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;const s=[...e];0!==(s?.length??0)?s.forEach((e,s)=>{Promise.resolve(e).then(e=>{r++,l[s]=e}).catch(()=>{l[s]=void 0}).finally(()=>{r>0&&t(l.filter(e=>void 0!==e))})}):t(l)})}}class d extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let r=0;const s=[...e];0!==(s?.length??0)?s.forEach((e,s)=>{Promise.resolve(e).then(()=>{l[s]=void 0}).catch(e=>{r++,l[s]=e}).finally(()=>{r>0&&t(l.filter(e=>void 0!==e))})}):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 +1 @@
1
- class e{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 t extends e{async execute(e){return Promise.any(e)}}class l extends Error{constructor(e,t,l){super(t),this.type=e,this.results=l,this.name="PromiseLogicError"}}function r(e,t,r,n){return new l(e,{XOR_ERROR:`XOR condition failed: expected exactly 1 promise to fulfill, but ${t} fulfilled.`,NAND_ERROR:`NAND condition failed: all ${r} promises fulfilled (expected at least one rejection).`,NOR_ERROR:`NOR condition failed: ${t} promises fulfilled (expected all rejected).`,XNOR_ERROR:`XNOR condition failed: ${t}/${r} promises fulfilled (expected all or none).`,MAJORITY_ERROR:`Majority condition failed: ${t}/${r} fulfilled (need majority).`,ALL_SUCCESSFUL_ERROR:`All successful condition failed: ${t}/${r} promises fulfilled (expected all to succeed).`,ALL_FAILED_ERROR:`All failed condition failed: ${r-t}/${r} promises rejected (expected all to fail).`}[e]||"Logic condition failed",n)}class n extends e{async execute(e){try{return Promise.all(e)}catch(e){throw new l("AND_ERROR","AND gate failed",[e])}}}class s extends e{async execute(e,t){const l=await Promise.allSettled(e),n=this.filterFulfilledResults(l),s=n.length,i=l.length;if(s>i*t.max)return n;throw r("MAJORITY_ERROR",s,i,l)}}class i extends e{async execute(e){const t=await Promise.allSettled(e),l=this.filterFulfilledResults(t),n=l.length,s=t.length;if(n===s)throw r("NAND_ERROR",n,s,t);return l}}class a extends e{async execute(e){const t=await Promise.allSettled(e),l=this.filterFulfilledResults(t).length,n=t.length;if(0===l)return[];throw r("NOR_ERROR",l,n,t)}}class o extends e{async execute(e){const t=await Promise.allSettled(e),l=this.filterFulfilledResults(t),n=l.length,s=t.length;if(0===n||n===s)return l;throw r("XNOR_ERROR",n,s,t)}}class c extends e{async execute(e){const t=await Promise.allSettled(e),l=this.filterFulfilledResults(t),n=l.length,s=t.length;if(1===n)return l[0];throw r("XOR_ERROR",n,s,t)}}class u{constructor(e){this.promise=e}maxTimer(e){let t;return Promise.race([this.promise,new Promise((l,r)=>{t=setTimeout(()=>{r(new Error(`Promise timed out after ${e}ms,${this.promise}`))},e)})]).finally(()=>clearTimeout(t))}then(e,t){return new u(this.promise.then(e,t))}catch(e){return new u(this.promise.catch(e))}finally(e){return new u(this.promise.finally(e))}toPromise(){return this.promise}}class d{static get gates(){return{and:new n,or:new t,xor:new c,nand:new i,nor:new a,xnor:new o,majority:new s}}static and(e){return new u(this.gates.and.execute(e))}static or(e){return new u(this.gates.or.execute(e))}static xor(e){return new u(this.gates.xor.execute(e))}static nand(e){return new u(this.gates.nand.execute(e))}static nor(e){return new u(this.gates.nor.execute(e))}static xnor(e){return new u(this.gates.xnor.execute(e))}static majority(e,t={max:.5}){return new u(this.gates.majority.execute(e,t))}static allFulfilled(e){return new u(Promise.allSettled(e).then(e=>e.filter(e=>"fulfilled"===e.status).map(e=>e.value)))}static allRejected(e){return new u(Promise.allSettled(e).then(e=>e.filter(e=>"rejected"===e.status).map(e=>e.reason)))}static not(e){return new u(Promise.resolve(e).then(e=>Promise.reject(e),e=>Promise.resolve(e)))}static race(e){return new u(Promise.race(e))}static allSettled(e){return new u(Promise.allSettled(e))}static createFlipFlop(e=!1){let t=e,l=null,r=Promise.resolve(t);const n=()=>(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:n,waitFor:e=>t===e?Promise.resolve(t):new Promise(l=>{const r=()=>{t===e?l(t):n().then(r)};r()})}}}function f(e={}){const{prefix:t="",suffix:l="",rename:r={}}=e,n={and:d.and.bind(d),or:d.or.bind(d),not:d.not.bind(d),race:d.race.bind(d),allSettled:d.allSettled.bind(d),xor:d.xor.bind(d),nand:d.nand.bind(d),nor:d.nor.bind(d),xnor:d.xnor.bind(d),majority:d.majority.bind(d),allFulfilled:d.allFulfilled.bind(d),allRejected:d.allRejected.bind(d)},s={};return Object.entries(n).forEach(([e,n])=>{const i=r[e]||e;s[`${t}${i}${l}`]=n}),s}export{d as PromiseLogic,l as PromiseLogicError,u as PromiseWithTimer,f as createPromiseLogic};
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;const r=[...e];0!==(r?.length??0)?r.forEach((e,r)=>{Promise.resolve(e).then(e=>{s++,l[r]=e}).catch(()=>{l[r]=void 0}).finally(()=>{s>0&&t(l.filter(e=>void 0!==e))})}):t(l)})}}class d extends l{async execute(e,t={}){return new Promise(t=>{const l=[];let s=0;const r=[...e];0!==(r?.length??0)?r.forEach((e,r)=>{Promise.resolve(e).then(()=>{l[r]=void 0}).catch(e=>{s++,l[r]=e}).finally(()=>{s>0&&t(l.filter(e=>void 0!==e))})}):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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "promise-logic",
3
- "version": "2.6.5",
3
+ "version": "2.8.0",
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",
@@ -12,11 +12,6 @@
12
12
  "require": "./dist/index.cjs.js",
13
13
  "types": "./dist/types/index.d.ts"
14
14
  },
15
- "./factory": {
16
- "import": "./dist/factory.esm.js",
17
- "require": "./dist/factory.cjs.js",
18
- "types": "./dist/types/factory.d.ts"
19
- },
20
15
  "./typescript": {
21
16
  "import": "./dist/v2/index.esm.js",
22
17
  "require": "./dist/v2/index.cjs.js",