@fgv/ts-utils 5.1.0-4 → 5.1.0-40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (303) hide show
  1. package/README.md +21 -0
  2. package/dist/index.js +2 -2
  3. package/dist/index.js.map +1 -0
  4. package/dist/packlets/base/brand.js.map +1 -0
  5. package/dist/packlets/base/index.js +2 -0
  6. package/dist/packlets/base/index.js.map +1 -0
  7. package/dist/packlets/base/mapResults.js.map +1 -0
  8. package/dist/packlets/base/messageAggregator.js.map +1 -0
  9. package/dist/packlets/base/normalize.js +54 -1
  10. package/dist/packlets/base/normalize.js.map +1 -0
  11. package/dist/packlets/base/result.js +326 -2
  12. package/dist/packlets/base/result.js.map +1 -0
  13. package/dist/packlets/base/shouldNotFail.js +123 -0
  14. package/dist/packlets/base/shouldNotFail.js.map +1 -0
  15. package/dist/packlets/base/utils.js.map +1 -0
  16. package/dist/packlets/base/uuid.js +55 -0
  17. package/dist/packlets/base/uuid.js.map +1 -0
  18. package/dist/packlets/collections/aggregatedResultMap.js.map +1 -0
  19. package/dist/packlets/collections/collectible.js.map +1 -0
  20. package/dist/packlets/collections/collector.js +23 -9
  21. package/dist/packlets/collections/collector.js.map +1 -0
  22. package/dist/packlets/collections/collectorValidator.js +6 -1
  23. package/dist/packlets/collections/collectorValidator.js.map +1 -0
  24. package/dist/packlets/collections/common.js.map +1 -0
  25. package/dist/packlets/collections/converters.js.map +1 -0
  26. package/dist/packlets/collections/convertingCollector.js.map +1 -0
  27. package/dist/packlets/collections/convertingCollectorValidator.js.map +1 -0
  28. package/dist/packlets/collections/convertingResultMap.js.map +1 -0
  29. package/dist/packlets/collections/index.js +1 -0
  30. package/dist/packlets/collections/index.js.map +1 -0
  31. package/dist/packlets/collections/keyValueConverters.js.map +1 -0
  32. package/dist/packlets/collections/readOnlyConvertingResultMap.js +18 -0
  33. package/dist/packlets/collections/readOnlyConvertingResultMap.js.map +1 -0
  34. package/dist/packlets/collections/readonlyResultMap.js.map +1 -0
  35. package/dist/packlets/collections/resultMap.js.map +1 -0
  36. package/dist/packlets/collections/resultMapValidator.js.map +1 -0
  37. package/dist/packlets/collections/retainingRingBuffer.js +159 -0
  38. package/dist/packlets/collections/retainingRingBuffer.js.map +1 -0
  39. package/dist/packlets/collections/utils.js.map +1 -0
  40. package/dist/packlets/collections/validatingCollector.js.map +1 -0
  41. package/dist/packlets/collections/validatingConvertingCollector.js.map +1 -0
  42. package/dist/packlets/collections/validatingConvertingResultMap.js.map +1 -0
  43. package/dist/packlets/collections/validatingResultMap.js.map +1 -0
  44. package/dist/packlets/conversion/advancedConverters.js.map +1 -0
  45. package/dist/packlets/conversion/baseConverter.js +107 -18
  46. package/dist/packlets/conversion/baseConverter.js.map +1 -0
  47. package/dist/packlets/conversion/basicConverters.js +24 -5
  48. package/dist/packlets/conversion/basicConverters.js.map +1 -0
  49. package/dist/packlets/conversion/converter.js +11 -1
  50. package/dist/packlets/conversion/converter.js.map +1 -0
  51. package/dist/packlets/conversion/converters.js.map +1 -0
  52. package/dist/packlets/conversion/defaultingConverter.js.map +1 -0
  53. package/dist/packlets/conversion/index.js.map +1 -0
  54. package/dist/packlets/conversion/objectConverter.js.map +1 -0
  55. package/dist/packlets/conversion/stringConverter.js.map +1 -0
  56. package/dist/packlets/hash/crcNormalizer.js.map +1 -0
  57. package/dist/packlets/hash/hashingNormalizer.js.map +1 -0
  58. package/dist/packlets/hash/index.js.map +1 -0
  59. package/dist/packlets/logging/bootLogger.js.map +1 -0
  60. package/dist/packlets/logging/index.js +2 -0
  61. package/dist/packlets/logging/index.js.map +1 -0
  62. package/dist/packlets/logging/logReporter.js.map +1 -0
  63. package/dist/packlets/logging/logger.js +51 -18
  64. package/dist/packlets/logging/logger.js.map +1 -0
  65. package/dist/packlets/logging/multiLogger.js +104 -0
  66. package/dist/packlets/logging/multiLogger.js.map +1 -0
  67. package/dist/packlets/logging/retainingLogger.js +114 -0
  68. package/dist/packlets/logging/retainingLogger.js.map +1 -0
  69. package/dist/packlets/logging-interface/index.js +28 -0
  70. package/dist/packlets/logging-interface/index.js.map +1 -0
  71. package/dist/packlets/validation/array.js.map +1 -0
  72. package/dist/packlets/validation/boolean.js.map +1 -0
  73. package/dist/packlets/validation/classes.js.map +1 -0
  74. package/dist/packlets/validation/common.js.map +1 -0
  75. package/dist/packlets/validation/compositeId.js.map +1 -0
  76. package/dist/packlets/validation/field.js.map +1 -0
  77. package/dist/packlets/validation/genericValidator.js.map +1 -0
  78. package/dist/packlets/validation/index.js.map +1 -0
  79. package/dist/packlets/validation/number.js.map +1 -0
  80. package/dist/packlets/validation/object.js.map +1 -0
  81. package/dist/packlets/validation/oneOf.js.map +1 -0
  82. package/dist/packlets/validation/string.js.map +1 -0
  83. package/dist/packlets/validation/traits.js.map +1 -0
  84. package/dist/packlets/validation/typeGuard.js.map +1 -0
  85. package/dist/packlets/validation/validator.js.map +1 -0
  86. package/dist/packlets/validation/validatorBase.js.map +1 -0
  87. package/dist/packlets/validation/validators.js.map +1 -0
  88. package/dist/ts-utils.d.ts +1089 -59
  89. package/dist/tsdoc-metadata.json +1 -1
  90. package/lib/index.d.ts +2 -2
  91. package/lib/index.d.ts.map +1 -0
  92. package/lib/index.js +2 -1
  93. package/lib/index.js.map +1 -0
  94. package/lib/packlets/base/brand.d.ts.map +1 -0
  95. package/lib/packlets/base/brand.js.map +1 -0
  96. package/lib/packlets/base/index.d.ts +2 -0
  97. package/lib/packlets/base/index.d.ts.map +1 -0
  98. package/lib/packlets/base/index.js +2 -0
  99. package/lib/packlets/base/index.js.map +1 -0
  100. package/lib/packlets/base/mapResults.d.ts.map +1 -0
  101. package/lib/packlets/base/mapResults.js.map +1 -0
  102. package/lib/packlets/base/messageAggregator.d.ts.map +1 -0
  103. package/lib/packlets/base/messageAggregator.js.map +1 -0
  104. package/lib/packlets/base/normalize.d.ts +24 -0
  105. package/lib/packlets/base/normalize.d.ts.map +1 -0
  106. package/lib/packlets/base/normalize.js +53 -0
  107. package/lib/packlets/base/normalize.js.map +1 -0
  108. package/lib/packlets/base/result.d.ts +295 -1
  109. package/lib/packlets/base/result.d.ts.map +1 -0
  110. package/lib/packlets/base/result.js +330 -3
  111. package/lib/packlets/base/result.js.map +1 -0
  112. package/lib/packlets/base/shouldNotFail.d.ts +53 -0
  113. package/lib/packlets/base/shouldNotFail.d.ts.map +1 -0
  114. package/lib/packlets/base/shouldNotFail.js +129 -0
  115. package/lib/packlets/base/shouldNotFail.js.map +1 -0
  116. package/lib/packlets/base/utils.d.ts +12 -0
  117. package/lib/packlets/base/utils.d.ts.map +1 -0
  118. package/lib/packlets/base/utils.js.map +1 -0
  119. package/lib/packlets/base/uuid.d.ts +27 -0
  120. package/lib/packlets/base/uuid.d.ts.map +1 -0
  121. package/lib/packlets/base/uuid.js +59 -0
  122. package/lib/packlets/base/uuid.js.map +1 -0
  123. package/lib/packlets/collections/aggregatedResultMap.d.ts.map +1 -0
  124. package/lib/packlets/collections/aggregatedResultMap.js.map +1 -0
  125. package/lib/packlets/collections/collectible.d.ts.map +1 -0
  126. package/lib/packlets/collections/collectible.js.map +1 -0
  127. package/lib/packlets/collections/collector.d.ts +23 -9
  128. package/lib/packlets/collections/collector.d.ts.map +1 -0
  129. package/lib/packlets/collections/collector.js +23 -9
  130. package/lib/packlets/collections/collector.js.map +1 -0
  131. package/lib/packlets/collections/collectorValidator.d.ts +29 -5
  132. package/lib/packlets/collections/collectorValidator.d.ts.map +1 -0
  133. package/lib/packlets/collections/collectorValidator.js +6 -1
  134. package/lib/packlets/collections/collectorValidator.js.map +1 -0
  135. package/lib/packlets/collections/common.d.ts.map +1 -0
  136. package/lib/packlets/collections/common.js.map +1 -0
  137. package/lib/packlets/collections/converters.d.ts.map +1 -0
  138. package/lib/packlets/collections/converters.js.map +1 -0
  139. package/lib/packlets/collections/convertingCollector.d.ts +21 -3
  140. package/lib/packlets/collections/convertingCollector.d.ts.map +1 -0
  141. package/lib/packlets/collections/convertingCollector.js.map +1 -0
  142. package/lib/packlets/collections/convertingCollectorValidator.d.ts +22 -3
  143. package/lib/packlets/collections/convertingCollectorValidator.d.ts.map +1 -0
  144. package/lib/packlets/collections/convertingCollectorValidator.js.map +1 -0
  145. package/lib/packlets/collections/convertingResultMap.d.ts.map +1 -0
  146. package/lib/packlets/collections/convertingResultMap.js.map +1 -0
  147. package/lib/packlets/collections/index.d.ts +1 -0
  148. package/lib/packlets/collections/index.d.ts.map +1 -0
  149. package/lib/packlets/collections/index.js +1 -0
  150. package/lib/packlets/collections/index.js.map +1 -0
  151. package/lib/packlets/collections/keyValueConverters.d.ts.map +1 -0
  152. package/lib/packlets/collections/keyValueConverters.js.map +1 -0
  153. package/lib/packlets/collections/readOnlyConvertingResultMap.d.ts +13 -1
  154. package/lib/packlets/collections/readOnlyConvertingResultMap.d.ts.map +1 -0
  155. package/lib/packlets/collections/readOnlyConvertingResultMap.js +19 -1
  156. package/lib/packlets/collections/readOnlyConvertingResultMap.js.map +1 -0
  157. package/lib/packlets/collections/readonlyResultMap.d.ts +18 -7
  158. package/lib/packlets/collections/readonlyResultMap.d.ts.map +1 -0
  159. package/lib/packlets/collections/readonlyResultMap.js.map +1 -0
  160. package/lib/packlets/collections/resultMap.d.ts.map +1 -0
  161. package/lib/packlets/collections/resultMap.js.map +1 -0
  162. package/lib/packlets/collections/resultMapValidator.d.ts.map +1 -0
  163. package/lib/packlets/collections/resultMapValidator.js.map +1 -0
  164. package/lib/packlets/collections/retainingRingBuffer.d.ts +147 -0
  165. package/lib/packlets/collections/retainingRingBuffer.d.ts.map +1 -0
  166. package/lib/packlets/collections/retainingRingBuffer.js +163 -0
  167. package/lib/packlets/collections/retainingRingBuffer.js.map +1 -0
  168. package/lib/packlets/collections/utils.d.ts.map +1 -0
  169. package/lib/packlets/collections/utils.js.map +1 -0
  170. package/lib/packlets/collections/validatingCollector.d.ts +7 -3
  171. package/lib/packlets/collections/validatingCollector.d.ts.map +1 -0
  172. package/lib/packlets/collections/validatingCollector.js.map +1 -0
  173. package/lib/packlets/collections/validatingConvertingCollector.d.ts.map +1 -0
  174. package/lib/packlets/collections/validatingConvertingCollector.js.map +1 -0
  175. package/lib/packlets/collections/validatingConvertingResultMap.d.ts.map +1 -0
  176. package/lib/packlets/collections/validatingConvertingResultMap.js.map +1 -0
  177. package/lib/packlets/collections/validatingResultMap.d.ts +2 -1
  178. package/lib/packlets/collections/validatingResultMap.d.ts.map +1 -0
  179. package/lib/packlets/collections/validatingResultMap.js.map +1 -0
  180. package/lib/packlets/conversion/advancedConverters.d.ts.map +1 -0
  181. package/lib/packlets/conversion/advancedConverters.js.map +1 -0
  182. package/lib/packlets/conversion/baseConverter.d.ts +108 -19
  183. package/lib/packlets/conversion/baseConverter.d.ts.map +1 -0
  184. package/lib/packlets/conversion/baseConverter.js +107 -18
  185. package/lib/packlets/conversion/baseConverter.js.map +1 -0
  186. package/lib/packlets/conversion/basicConverters.d.ts +14 -0
  187. package/lib/packlets/conversion/basicConverters.d.ts.map +1 -0
  188. package/lib/packlets/conversion/basicConverters.js +24 -5
  189. package/lib/packlets/conversion/basicConverters.js.map +1 -0
  190. package/lib/packlets/conversion/converter.d.ts +9 -1
  191. package/lib/packlets/conversion/converter.d.ts.map +1 -0
  192. package/lib/packlets/conversion/converter.js +12 -0
  193. package/lib/packlets/conversion/converter.js.map +1 -0
  194. package/lib/packlets/conversion/converters.d.ts.map +1 -0
  195. package/lib/packlets/conversion/converters.js.map +1 -0
  196. package/lib/packlets/conversion/defaultingConverter.d.ts.map +1 -0
  197. package/lib/packlets/conversion/defaultingConverter.js.map +1 -0
  198. package/lib/packlets/conversion/index.d.ts.map +1 -0
  199. package/lib/packlets/conversion/index.js.map +1 -0
  200. package/lib/packlets/conversion/objectConverter.d.ts.map +1 -0
  201. package/lib/packlets/conversion/objectConverter.js.map +1 -0
  202. package/lib/packlets/conversion/stringConverter.d.ts.map +1 -0
  203. package/lib/packlets/conversion/stringConverter.js.map +1 -0
  204. package/lib/packlets/hash/crcNormalizer.d.ts.map +1 -0
  205. package/lib/packlets/hash/crcNormalizer.js.map +1 -0
  206. package/lib/packlets/hash/hashingNormalizer.d.ts.map +1 -0
  207. package/lib/packlets/hash/hashingNormalizer.js.map +1 -0
  208. package/lib/packlets/hash/index.d.ts.map +1 -0
  209. package/lib/packlets/hash/index.js.map +1 -0
  210. package/lib/packlets/logging/bootLogger.d.ts.map +1 -0
  211. package/lib/packlets/logging/bootLogger.js.map +1 -0
  212. package/lib/packlets/logging/index.d.ts +2 -0
  213. package/lib/packlets/logging/index.d.ts.map +1 -0
  214. package/lib/packlets/logging/index.js +2 -0
  215. package/lib/packlets/logging/index.js.map +1 -0
  216. package/lib/packlets/logging/logReporter.d.ts.map +1 -0
  217. package/lib/packlets/logging/logReporter.js.map +1 -0
  218. package/lib/packlets/logging/logger.d.ts +25 -70
  219. package/lib/packlets/logging/logger.d.ts.map +1 -0
  220. package/lib/packlets/logging/logger.js +54 -20
  221. package/lib/packlets/logging/logger.js.map +1 -0
  222. package/lib/packlets/logging/multiLogger.d.ts +54 -0
  223. package/lib/packlets/logging/multiLogger.d.ts.map +1 -0
  224. package/lib/packlets/logging/multiLogger.js +108 -0
  225. package/lib/packlets/logging/multiLogger.js.map +1 -0
  226. package/lib/packlets/logging/retainingLogger.d.ts +123 -0
  227. package/lib/packlets/logging/retainingLogger.d.ts.map +1 -0
  228. package/lib/packlets/logging/retainingLogger.js +118 -0
  229. package/lib/packlets/logging/retainingLogger.js.map +1 -0
  230. package/lib/packlets/logging-interface/index.d.ts +98 -0
  231. package/lib/packlets/logging-interface/index.d.ts.map +1 -0
  232. package/lib/packlets/logging-interface/index.js +32 -0
  233. package/lib/packlets/logging-interface/index.js.map +1 -0
  234. package/lib/packlets/validation/array.d.ts.map +1 -0
  235. package/lib/packlets/validation/array.js.map +1 -0
  236. package/lib/packlets/validation/boolean.d.ts.map +1 -0
  237. package/lib/packlets/validation/boolean.js.map +1 -0
  238. package/lib/packlets/validation/classes.d.ts.map +1 -0
  239. package/lib/packlets/validation/classes.js.map +1 -0
  240. package/lib/packlets/validation/common.d.ts.map +1 -0
  241. package/lib/packlets/validation/common.js.map +1 -0
  242. package/lib/packlets/validation/compositeId.d.ts.map +1 -0
  243. package/lib/packlets/validation/compositeId.js.map +1 -0
  244. package/lib/packlets/validation/field.d.ts.map +1 -0
  245. package/lib/packlets/validation/field.js.map +1 -0
  246. package/lib/packlets/validation/genericValidator.d.ts.map +1 -0
  247. package/lib/packlets/validation/genericValidator.js.map +1 -0
  248. package/lib/packlets/validation/index.d.ts.map +1 -0
  249. package/lib/packlets/validation/index.js.map +1 -0
  250. package/lib/packlets/validation/number.d.ts.map +1 -0
  251. package/lib/packlets/validation/number.js.map +1 -0
  252. package/lib/packlets/validation/object.d.ts.map +1 -0
  253. package/lib/packlets/validation/object.js.map +1 -0
  254. package/lib/packlets/validation/oneOf.d.ts.map +1 -0
  255. package/lib/packlets/validation/oneOf.js.map +1 -0
  256. package/lib/packlets/validation/string.d.ts.map +1 -0
  257. package/lib/packlets/validation/string.js.map +1 -0
  258. package/lib/packlets/validation/traits.d.ts.map +1 -0
  259. package/lib/packlets/validation/traits.js.map +1 -0
  260. package/lib/packlets/validation/typeGuard.d.ts.map +1 -0
  261. package/lib/packlets/validation/typeGuard.js.map +1 -0
  262. package/lib/packlets/validation/validator.d.ts.map +1 -0
  263. package/lib/packlets/validation/validator.js.map +1 -0
  264. package/lib/packlets/validation/validatorBase.d.ts +2 -1
  265. package/lib/packlets/validation/validatorBase.d.ts.map +1 -0
  266. package/lib/packlets/validation/validatorBase.js.map +1 -0
  267. package/lib/packlets/validation/validators.d.ts.map +1 -0
  268. package/lib/packlets/validation/validators.js.map +1 -0
  269. package/package.json +3 -3
  270. package/dist/test/helpers/jest/helpers/fsHelpers.js +0 -139
  271. package/dist/test/helpers/jest/helpers/index.js +0 -2
  272. package/dist/test/helpers/jest/index.js +0 -17
  273. package/dist/test/helpers/jest/matchers/index.js +0 -14
  274. package/dist/test/helpers/jest/matchers/toFail/index.js +0 -23
  275. package/dist/test/helpers/jest/matchers/toFail/predicate.js +0 -5
  276. package/dist/test/helpers/jest/matchers/toFailTest/index.js +0 -28
  277. package/dist/test/helpers/jest/matchers/toFailTest/predicate.js +0 -8
  278. package/dist/test/helpers/jest/matchers/toFailTestAndMatchSnapshot/index.js +0 -24
  279. package/dist/test/helpers/jest/matchers/toFailTestAndMatchSnapshot/predicate.js +0 -11
  280. package/dist/test/helpers/jest/matchers/toFailTestWith/index.js +0 -29
  281. package/dist/test/helpers/jest/matchers/toFailTestWith/predicate.js +0 -26
  282. package/dist/test/helpers/jest/matchers/toFailWith/index.js +0 -27
  283. package/dist/test/helpers/jest/matchers/toFailWith/predicate.js +0 -16
  284. package/dist/test/helpers/jest/matchers/toFailWithDetail/index.js +0 -27
  285. package/dist/test/helpers/jest/matchers/toFailWithDetail/predicate.js +0 -22
  286. package/dist/test/helpers/jest/matchers/toSucceed/index.js +0 -23
  287. package/dist/test/helpers/jest/matchers/toSucceed/predicate.js +0 -5
  288. package/dist/test/helpers/jest/matchers/toSucceedAndMatchInlineSnapshot/index.js +0 -24
  289. package/dist/test/helpers/jest/matchers/toSucceedAndMatchSnapshot/index.js +0 -24
  290. package/dist/test/helpers/jest/matchers/toSucceedAndSatisfy/index.js +0 -53
  291. package/dist/test/helpers/jest/matchers/toSucceedAndSatisfy/predicate.js +0 -17
  292. package/dist/test/helpers/jest/matchers/toSucceedWith/index.js +0 -27
  293. package/dist/test/helpers/jest/matchers/toSucceedWith/predicate.js +0 -12
  294. package/dist/test/helpers/jest/matchers/toSucceedWithDetail/index.js +0 -27
  295. package/dist/test/helpers/jest/matchers/toSucceedWithDetail/predicate.js +0 -17
  296. package/dist/test/helpers/jest/resolvers/cli.js +0 -10
  297. package/dist/test/helpers/jest/resolvers/ide.js +0 -10
  298. package/dist/test/helpers/jest/ts-utils.js +0 -2
  299. package/dist/test/helpers/jest/types/index.js +0 -3
  300. package/dist/test/helpers/jest/utils/matcherHelpers.js +0 -47
  301. package/dist/test/helpers/jest/utils/snapshotResolver.js +0 -11
  302. package/dist/test/unit/collections/helpers.js +0 -106
  303. package/dist/test/unit/hashTextEncodeCompat.js +0 -23
package/README.md CHANGED
@@ -56,6 +56,27 @@ function processData(input: string): Result<ProcessedData> {
56
56
  }
57
57
  ```
58
58
 
59
+ ### Async Chaining
60
+
61
+ Use `thenOnSuccess()` to chain async operations without breaking the fluent style:
62
+
63
+ ```typescript
64
+ import { Result, succeed, captureAsyncResult } from '@fgv/ts-utils';
65
+
66
+ async function processData(input: string): Promise<Result<SavedData>> {
67
+ return parseInput(input)
68
+ .onSuccess((parsed) => validate(parsed))
69
+ .thenOnSuccess(async (valid) => fetchRelatedData(valid.id))
70
+ .onSuccess((data) => transform(data))
71
+ .thenOnSuccess(async (transformed) => saveData(transformed))
72
+ .withErrorFormat((msg) => `pipeline failed: ${msg}`);
73
+ }
74
+ ```
75
+
76
+ `AsyncResult<T>` implements `PromiseLike`, so the entire chain can be directly `await`ed. Rejected promises are caught and converted to `Failure`.
77
+
78
+ [Full async chaining documentation &rarr;](./src/packlets/base/README.md#async-result-chaining)
79
+
59
80
  ### Error Context
60
81
 
61
82
  ```typescript
package/dist/index.js CHANGED
@@ -24,9 +24,9 @@ import * as Conversion from './packlets/conversion';
24
24
  import * as Hash from './packlets/hash';
25
25
  import * as Logging from './packlets/logging';
26
26
  import * as Validation from './packlets/validation';
27
- import { AggregatedResultMap, Collector, ConvertingCollector, ResultMap, ValidatingCollector, ValidatingConvertingCollector, ValidatingResultMap } from './packlets/collections';
27
+ import { AggregatedResultMap, Collector, ConvertingCollector, ResultMap, RetainingRingBuffer, ValidatingCollector, ValidatingConvertingCollector, ValidatingResultMap } from './packlets/collections';
28
28
  import { Converters, ObjectConverter, StringConverter } from './packlets/conversion';
29
29
  import { Validators } from './packlets/validation';
30
30
  export * from './packlets/base';
31
- export { AggregatedResultMap, Collections, Collector, ConvertingCollector, Conversion, Converters, Hash, Logging, ObjectConverter, ResultMap, StringConverter, ValidatingCollector, ValidatingConvertingCollector, ValidatingResultMap, Validation, Validators };
31
+ export { AggregatedResultMap, Collections, Collector, ConvertingCollector, Conversion, Converters, Hash, Logging, ObjectConverter, ResultMap, RetainingRingBuffer, StringConverter, ValidatingCollector, ValidatingConvertingCollector, ValidatingResultMap, Validation, Validators };
32
32
  //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,KAAK,WAAW,MAAM,wBAAwB,CAAC;AACtD,OAAO,KAAK,UAAU,MAAM,uBAAuB,CAAC;AACpD,OAAO,KAAK,IAAI,MAAM,iBAAiB,CAAC;AACxC,OAAO,KAAK,OAAO,MAAM,oBAAoB,CAAC;AAC9C,OAAO,KAAK,UAAU,MAAM,uBAAuB,CAAC;AAEpD,OAAO,EACL,mBAAmB,EACnB,SAAS,EAET,mBAAmB,EAKnB,SAAS,EACT,mBAAmB,EACnB,mBAAmB,EACnB,6BAA6B,EAC7B,mBAAmB,EACpB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAa,UAAU,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAChG,OAAO,EAAa,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAE9D,cAAc,iBAAiB,CAAC;AAChC,OAAO,EACL,mBAAmB,EACnB,WAAW,EACX,SAAS,EACT,mBAAmB,EACnB,UAAU,EAEV,UAAU,EACV,IAAI,EAGJ,OAAO,EAIP,eAAe,EACf,SAAS,EACT,mBAAmB,EACnB,eAAe,EACf,mBAAmB,EACnB,6BAA6B,EAC7B,mBAAmB,EACnB,UAAU,EAEV,UAAU,EACX,CAAC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport * as Collections from './packlets/collections';\nimport * as Conversion from './packlets/conversion';\nimport * as Hash from './packlets/hash';\nimport * as Logging from './packlets/logging';\nimport * as Validation from './packlets/validation';\n\nimport {\n AggregatedResultMap,\n Collector,\n ICollectible,\n ConvertingCollector,\n IReadOnlyResultMap,\n IRetainedRecord,\n IRetainingRingBufferCreateParams,\n IRetainingRingBufferQuery,\n ResultMap,\n RetainingRingBuffer,\n ValidatingCollector,\n ValidatingConvertingCollector,\n ValidatingResultMap\n} from './packlets/collections';\nimport { Converter, Converters, ObjectConverter, StringConverter } from './packlets/conversion';\nimport { Validator, Validators } from './packlets/validation';\n\nexport * from './packlets/base';\nexport {\n AggregatedResultMap,\n Collections,\n Collector,\n ConvertingCollector,\n Conversion,\n Converter,\n Converters,\n Hash,\n ICollectible,\n IReadOnlyResultMap,\n Logging,\n IRetainedRecord,\n IRetainingRingBufferCreateParams,\n IRetainingRingBufferQuery,\n ObjectConverter,\n ResultMap,\n RetainingRingBuffer,\n StringConverter,\n ValidatingCollector,\n ValidatingConvertingCollector,\n ValidatingResultMap,\n Validation,\n Validator,\n Validators\n};\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"brand.js","sourceRoot":"","sources":["../../../src/packlets/base/brand.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG","sourcesContent":["/*\n * Copyright (c) 2021 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Helper type to brand a simple type to prevent inappropriate use\n * @public\n */\n\nexport type Brand<T, B> = T & { __brand: B };\n"]}
@@ -24,5 +24,7 @@ export * from './mapResults';
24
24
  export * from './messageAggregator';
25
25
  export { Normalizer } from './normalize';
26
26
  export * from './result';
27
+ export * from './shouldNotFail';
27
28
  export * from './utils';
29
+ export * from './uuid';
28
30
  //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/base/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,cAAc,SAAS,CAAC;AACxB,cAAc,cAAc,CAAC;AAC7B,cAAc,qBAAqB,CAAC;AACpC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,cAAc,UAAU,CAAC;AACzB,cAAc,iBAAiB,CAAC;AAChC,cAAc,SAAS,CAAC;AACxB,cAAc,QAAQ,CAAC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nexport * from './brand';\nexport * from './mapResults';\nexport * from './messageAggregator';\nexport { Normalizer } from './normalize';\nexport * from './result';\nexport * from './shouldNotFail';\nexport * from './utils';\nexport * from './uuid';\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mapResults.js","sourceRoot":"","sources":["../../../src/packlets/base/mapResults.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAKL,IAAI,EACJ,gBAAgB,EAChB,OAAO,EACR,MAAM,UAAU,CAAC;AAElB;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C,iBAAiB,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EACrF,CAAC;wBACD,SAAS;oBACX,CAAC;gBACH,CAAC;gBACD,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC;YAC5B,CAAC;iBAAM,CAAC;gBACN,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YAC9B,CAAC;QACH,CAAC;aAAM,CAAC;YACN,MAAM,CAAC,IAAI,CAAC,uBAAuB,MAAM,CAAC,GAAG,CAAC,oCAAoC,CAAC,CAAC;QACtF,CAAC;IACH,CAAC;IAED,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACtB,gBAAgB,aAAhB,gBAAgB,uBAAhB,gBAAgB,CAAE,WAAW,CAAC,MAAM,CAAC,CAAC;QACtC,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IACjC,CAAC;IACD,OAAO,OAAO,CAAC,KAAU,CAAC,CAAC;AAC7B,CAAC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { MessageAggregator } from './messageAggregator';\nimport {\n DeferredResult,\n DetailedResult,\n IMessageAggregator,\n Result,\n fail,\n isDeferredResult,\n succeed\n} from './result';\n\n/**\n * Aggregates successful result values from a collection of {@link Result | Result<T>}.\n * @param results - The collection of {@link Result | Result<T>} to be mapped.\n * @param aggregatedErrors - Optional string array to which any error messages will be\n * appended. Each error is appended as an individual string.\n * @returns If all {@link Result | results} are successful, returns {@link Success} with an\n * array containing all returned values. If any {@link Result | results} failed, returns\n * {@link Failure} with a concatenated summary of all error messages.\n * @public\n */\nexport function mapResults<T>(\n results: Iterable<Result<T>>,\n aggregatedErrors?: IMessageAggregator\n): Result<T[]> {\n const errors: string[] = [];\n const elements: T[] = [];\n\n for (const result of results) {\n if (result.isSuccess()) {\n elements.push(result.value);\n } else {\n errors.push(result.message);\n }\n }\n\n if (errors.length > 0) {\n aggregatedErrors?.addMessages(errors);\n return fail(errors.join('\\n'));\n }\n return succeed(elements);\n}\n\n/**\n * Aggregates successful results from a collection of {@link DetailedResult | DetailedResult<T, TD>},\n * optionally ignoring certain error details.\n * @param results - The collection of {@link DetailedResult | DetailedResult<T, TD>} to be mapped.\n * @param ignore - An array of error detail values (of type `<TD>`) that should be ignored.\n * @param aggregatedErrors - Optional string array to which any non-ignorable error messages will be\n * appended. Each error is appended as an individual string.\n * @returns {@link Success} with an array containing all successful results if all results either\n * succeeded or returned error details listed in `ignore`. If any results failed with details\n * that cannot be ignored, returns {@link Failure} with an concatenated summary of all non-ignorable\n * error messages.\n * @public\n */\nexport function mapDetailedResults<T, TD>(\n results: Iterable<DetailedResult<T, TD>>,\n ignore: TD[],\n aggregatedErrors?: IMessageAggregator\n): Result<T[]> {\n const errors: string[] = [];\n const elements: T[] = [];\n\n for (const result of results) {\n if (result.isSuccess()) {\n elements.push(result.value);\n } else if (result.detail && !ignore.includes(result.detail)) {\n errors.push(result.message);\n }\n }\n\n if (errors.length > 0) {\n aggregatedErrors?.addMessages(errors);\n return fail(errors.join('\\n'));\n }\n return succeed(elements);\n}\n\n/**\n * Aggregates successful results from a a collection of {@link Result | Result<T>}.\n * @param results - An `Iterable` of {@link Result | Result<T>} from which success\n * results are to be aggregated.\n * @param aggregatedErrors - Optional string array to which any returned error messages will be\n * appended. Each error is appended as an individual string.\n * @returns {@link Success} with an array of `<T>` if any results were successful. If\n * all {@link Result | results} failed, returns {@link Failure} with a concatenated\n * summary of all error messages.\n * @public\n */\nexport function mapSuccess<T>(\n results: Iterable<Result<T>>,\n aggregatedErrors?: IMessageAggregator\n): Result<T[]> {\n const errors: string[] = [];\n const elements: T[] = [];\n\n for (const result of results) {\n if (result.isSuccess()) {\n elements.push(result.value);\n } else {\n errors.push(result.message);\n }\n }\n\n if (elements.length === 0 && errors.length > 0) {\n aggregatedErrors?.addMessages(errors);\n return fail(errors.join('\\n'));\n }\n return succeed(elements);\n}\n\n/**\n * Aggregates error messages from a collection of {@link Result | Result<T>}.\n * @param results - An iterable collection of {@link Result | Result<T>} for which\n * error messages are aggregated.\n * @param aggregatedErrors - Optional string array to which any returned error messages will be\n * appended. Each error is appended as an individual string.\n * @returns An array of strings consisting of all error messages returned by\n * {@link Result | results} in the source collection. Ignores {@link Success}\n * results and returns an empty array if there were no errors.\n * @public\n */\nexport function mapFailures<T>(\n results: Iterable<Result<T>>,\n aggregatedErrors?: IMessageAggregator\n): string[] {\n const errors: string[] = [];\n for (const result of results) {\n if (result.isFailure()) {\n errors.push(result.message);\n aggregatedErrors?.addMessage(result.message);\n }\n }\n return errors;\n}\n\n/**\n * Determines if an iterable collection of {@link Result | Result<T>} were all successful.\n * @param results - The collection of {@link Result | Result<T>} to be tested.\n * @param successValue - The value to be returned if results are successful.\n * @param aggregatedErrors - Optional string array to which any returned error messages will be\n * appended. Each error is appended as an individual string.\n * @returns Returns {@link Success} with `successValue` if all {@link Result | results} are successful.\n * If any are unsuccessful, returns {@link Failure} with a concatenated summary of the error\n * messages from all failed elements.\n * @public\n */\nexport function allSucceed<T>(\n results: Iterable<Result<unknown>>,\n successValue: T,\n aggregatedErrors?: IMessageAggregator\n): Result<T> {\n const errors: string[] = [];\n\n if (results !== undefined) {\n for (const result of results) {\n if (result.isFailure()) {\n errors.push(result.message);\n }\n }\n }\n\n if (errors.length > 0) {\n aggregatedErrors?.addMessages(errors);\n return fail(errors.join('\\n'));\n }\n return succeed(successValue);\n}\n\n/**\n * Returns the first successful result from a collection of {@link Result | Result<T>} or {@link DeferredResult | DeferredResult<T>}.\n * @param results - The collection of {@link Result | Result<T>} or {@link DeferredResult | DeferredResult<T>} to be tested.\n * @returns The first successful result, or {@link Failure} with a concatenated summary of all error messages.\n * @public\n */\nexport function firstSuccess<T>(results: Iterable<Result<T> | DeferredResult<T>>): Result<T> {\n const errors: MessageAggregator = new MessageAggregator();\n for (const r of results) {\n const result = isDeferredResult(r) ? r() : r;\n if (result.isSuccess()) {\n return result;\n }\n errors.addMessage(result.message);\n }\n return errors.returnOrReport(fail('no results found'));\n}\n\n/**\n * String-keyed record of initialization functions to be passed to {@link populateObject}\n * or {@link populateObject}.\n * @public\n */\nexport type FieldInitializers<T> = { [key in keyof T]: (state: Partial<T>) => Result<T[key]> };\n\n/**\n * Options for the {@link populateObject} function.\n * @public\n */\n\nexport interface PopulateObjectOptions<T> {\n /**\n * If present, specifies the order in which property values should\n * be evaluated. Any keys not listed are evaluated after all listed\n * keys in indeterminate order. If 'order' is not present, keys\n * are evaluated in indeterminate order.\n */\n order?: (keyof T)[];\n\n /**\n * Specify handling of `undefined` values. By default, successful\n * `undefined` results are written to the result object. If this value\n * is `true` then `undefined` results are suppressed for all properties.\n * If this value is an array of property keys then `undefined` results\n * are suppressed for those properties only.\n */\n suppressUndefined?: boolean | (keyof T)[];\n}\n\n/**\n * Populates an an object based on a prototype full of field initializers that return {@link Result | Result<T[key]>}.\n * Returns {@link Success} with the populated object if all initializers succeed, or {@link Failure} with a\n * concatenated list of all error messages.\n * @param initializers - An object with the shape of the target but with initializer functions for\n * each property.\n * @param options - An optional {@link PopulateObjectOptions | set of options} which\n * modify the behavior of this call.\n * @param aggregatedErrors - Optional string array to which any returned error messages will be\n * appended. Each error is appended as an individual string.\n * {@label WITH_OPTIONS}\n * @public\n */\nexport function populateObject<T>(\n initializers: FieldInitializers<T>,\n options?: PopulateObjectOptions<T>,\n aggregatedErrors?: IMessageAggregator\n): Result<T>;\n\n/**\n * Populates an an object based on a prototype full of field initializers that return {@link Result | Result<T[key]>}.\n * Returns {@link Success} with the populated object if all initializers succeed, or {@link Failure} with a\n * concatenated list of all error messages.\n * @param initializers - An object with the shape of the target but with initializer functions for\n * each property.\n * @param order - Optional order in which keys should be written.\n * @param aggregatedErrors - Optional string array to which any returned error messages will be\n * appended. Each error is appended as an individual string.\n * @public\n * {@label WITH_ORDER}\n * @deprecated Pass {@link PopulateObjectOptions} instead.\n */\nexport function populateObject<T>(\n initializers: FieldInitializers<T>,\n order: (keyof T)[] | undefined,\n aggregatedErrors?: IMessageAggregator\n): Result<T>;\n\nexport function populateObject<T>(\n initializers: FieldInitializers<T>,\n optionsOrOrder?: PopulateObjectOptions<T> | (keyof T)[],\n aggregatedErrors?: IMessageAggregator\n): Result<T> {\n const options: PopulateObjectOptions<T> = optionsOrOrder\n ? Array.isArray(optionsOrOrder)\n ? { order: optionsOrOrder }\n : optionsOrOrder\n : {};\n const state = {} as { [key in keyof T]: T[key] };\n const errors: string[] = [];\n const keys: (keyof T)[] = Array.from(options.order ?? []);\n const foundKeys = new Set<keyof T>(options.order);\n\n // start with the supplied order then append anything else we find\n for (const key in initializers) {\n if (!foundKeys.has(key)) {\n keys.push(key);\n foundKeys.add(key);\n }\n }\n\n for (const key of keys) {\n if (initializers[key]) {\n const result = initializers[key](state);\n if (result.isSuccess()) {\n if (result.value === undefined) {\n if (\n options.suppressUndefined === true ||\n (Array.isArray(options.suppressUndefined) && options.suppressUndefined.includes(key))\n ) {\n continue;\n }\n }\n state[key] = result.value;\n } else {\n errors.push(result.message);\n }\n } else {\n errors.push(`populateObject: Key ${String(key)} is present but has no initializer`);\n }\n }\n\n if (errors.length > 0) {\n aggregatedErrors?.addMessages(errors);\n return fail(errors.join('\\n'));\n }\n return succeed(state as T);\n}\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"messageAggregator.js","sourceRoot":"","sources":["../../../src/packlets/base/messageAggregator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAA8B,IAAI,EAAE,MAAM,UAAU,CAAC;AAE5D;;;;GAIG;AACH,MAAM,OAAO,iBAAiB;IAG5B;;;;;OAKG;IACH,YAAmB,MAAiB;QAClC,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACpD,CAAC;IAED;;OAEG;IACH,IAAW,WAAW;QACpB,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC;IACnC,CAAC;IAED;;OAEG;IACH,IAAW,WAAW;QACpB,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC;IAC/B,CAAC;IAED;;OAEG;IACH,IAAW,QAAQ;QACjB,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED;;OAEG;IACI,UAAU,CAAC,OAA2B;QAC3C,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC/B,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;OAEG;IACI,WAAW,CAAC,QAA8B;QAC/C,IAAI,QAAQ,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACpC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC,CAAC;QACnC,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;OAEG;IACI,QAAQ,CAAC,SAAkB;QAChC,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,SAAS,aAAT,SAAS,cAAT,SAAS,GAAI,IAAI,CAAC,CAAC;IAChD,CAAC;IAED;;;;;;;;;;;;;;;;;OAiBG;IACI,cAAc,CAAI,MAAiB,EAAE,SAAkB;QAC5D,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;YACtB,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YACpB,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC;gBACtD,OAAO,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,SAAS,aAAT,SAAS,cAAT,SAAS,GAAI,IAAI,CAAC,CAAC,CAAC;YAC3E,CAAC;QACH,CAAC;QACD,OAAO,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC;IACxC,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2024 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { IMessageAggregator, Result, fail } from './result';\n\n/**\n * A simple error aggregator to simplify collecting and reporting all errors in\n * a flow.\n * @public\n */\nexport class MessageAggregator implements IMessageAggregator {\n private readonly _messages: string[];\n\n /**\n * Constructs a new {@link MessageAggregator | ErrorAggregator} with an\n * optionally specified initial set of error messages.\n * @param errors - optional array of errors to be included\n * in the aggregation.\n */\n public constructor(errors?: string[]) {\n this._messages = errors ? Array.from(errors) : [];\n }\n\n /**\n * {@inheritDoc IMessageAggregator.hasMessages}\n */\n public get hasMessages(): boolean {\n return this._messages.length > 0;\n }\n\n /**\n * {@inheritDoc IMessageAggregator.numMessages}\n */\n public get numMessages(): number {\n return this._messages.length;\n }\n\n /**\n * {@inheritDoc IMessageAggregator.messages}\n */\n public get messages(): string[] {\n return this._messages;\n }\n\n /**\n * {@inheritDoc IMessageAggregator.addMessage}\n */\n public addMessage(message: string | undefined): this {\n if (message) {\n this._messages.push(message);\n }\n return this;\n }\n\n /**\n * {@inheritDoc IMessageAggregator.addMessages}\n */\n public addMessages(messages: string[] | undefined): this {\n if (messages && messages.length > 0) {\n this._messages.push(...messages);\n }\n return this;\n }\n\n /**\n * {@inheritDoc IMessageAggregator.toString}\n */\n public toString(separator?: string): string {\n return this._messages.join(separator ?? '\\n');\n }\n\n /**\n * If any error messages have been aggregated, returns\n * {@link Failure | Failure<T>} with the aggregated\n * messages concatenated using the optionally-supplied\n * separator, or newline. If the supplied {@link Result | Result<T>}\n * contains an error message that has not already been aggregated,\n * it will be included in the aggregated messages.\n *\n * If no error messages have been aggregated, returns\n * the supplied {@link Result | Result<T>}.\n * @param result - The {@link Result | Result<T>} to be returned\n * if no messages have been aggregated.\n * @param separator - Optional string separator used to construct\n * the error message.\n * @returns {@link Failure | Failure<T>} with an aggregated message\n * if any error messages were collected, the supplied\n * {@link Result | Result<T>} otherwise.\n */\n public returnOrReport<T>(result: Result<T>, separator?: string): Result<T> {\n if (!this.hasMessages) {\n return result;\n }\n if (!result.success) {\n if (!this._messages.find((s) => s === result.message)) {\n return fail([...this._messages, result.message].join(separator ?? '\\n'));\n }\n }\n return fail(this.toString(separator));\n }\n}\n"]}
@@ -20,7 +20,7 @@
20
20
  * SOFTWARE.
21
21
  */
22
22
  import { mapResults } from './mapResults';
23
- import { fail, succeed } from './result';
23
+ import { captureResult, fail, succeed } from './result';
24
24
  /**
25
25
  * Normalizes an arbitrary JSON object
26
26
  * @public
@@ -62,6 +62,59 @@ export class Normalizer {
62
62
  }
63
63
  return fail(`normalize: Unexpected type - cannot normalize '${typeof from}'`);
64
64
  }
65
+ /**
66
+ * Produces a stable, byte-identical JSON string following RFC 8785
67
+ * (JSON Canonicalization Scheme) key-ordering rules.
68
+ *
69
+ * Builds the output string directly rather than constructing an intermediate
70
+ * JS object, so integer-string keys (`"10"`, `"2"`) retain lexicographic
71
+ * order instead of being reordered numerically by the JS engine during
72
+ * `JSON.stringify`.
73
+ *
74
+ * @param from - Any JSON-compatible value (string, number, boolean, null,
75
+ * plain object, or array). Fails for non-JSON types (Map, Set, Date,
76
+ * RegExp, function, symbol, bigint, undefined).
77
+ * @returns `Result<string>` — the canonical JSON string, or a failure if
78
+ * `from` contains non-serializable types.
79
+ * @public
80
+ */
81
+ canonicalize(from) {
82
+ return captureResult(() => this._canonicalizeRfc8785(from));
83
+ }
84
+ /**
85
+ * Recursively builds a byte-identical RFC 8785 JSON string.
86
+ * @throws For non-JSON-serializable types (non-finite numbers, Date, RegExp,
87
+ * Map, Set, class instances, function, symbol, bigint, undefined).
88
+ * Callers must wrap in captureResult.
89
+ */
90
+ _canonicalizeRfc8785(value) {
91
+ if (value === null)
92
+ return 'null';
93
+ if (typeof value === 'boolean')
94
+ return value ? 'true' : 'false';
95
+ if (typeof value === 'number') {
96
+ if (!Number.isFinite(value)) {
97
+ throw new Error(`canonicalize: non-finite number (${value}) is not representable in JSON`);
98
+ }
99
+ return JSON.stringify(value);
100
+ }
101
+ if (typeof value === 'string')
102
+ return JSON.stringify(value);
103
+ if (Array.isArray(value)) {
104
+ return '[' + value.map((item) => this._canonicalizeRfc8785(item)).join(',') + ']';
105
+ }
106
+ if (typeof value === 'object') {
107
+ const proto = Object.getPrototypeOf(value);
108
+ if (proto !== Object.prototype && proto !== null) {
109
+ throw new Error(`canonicalize: cannot serialize non-plain object (${Object.prototype.toString.call(value)})`);
110
+ }
111
+ const obj = value;
112
+ const sortedKeys = Object.keys(obj).sort((k1, k2) => this._compareKeys(k1, k2));
113
+ const pairs = sortedKeys.map((k) => JSON.stringify(k) + ':' + this._canonicalizeRfc8785(obj[k]));
114
+ return '{' + pairs.join(',') + '}';
115
+ }
116
+ throw new Error(`canonicalize: cannot serialize value of type '${typeof value}'`);
117
+ }
65
118
  /**
66
119
  * Compares two property names from some object being normalized.
67
120
  * @param k1 - First key to be compared.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normalize.js","sourceRoot":"","sources":["../../../src/packlets/base/normalize.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAU,aAAa,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAYhE;;;GAGG;AACH,MAAM,OAAO,UAAU;IACrB;;;;;OAKG;IACI,SAAS,CAAI,IAAO;QACzB,QAAQ,OAAO,IAAI,EAAE,CAAC;YACpB,KAAK,QAAQ,CAAC;YACd,KAAK,QAAQ,CAAC;YACd,KAAK,SAAS,CAAC;YACf,KAAK,QAAQ,CAAC;YACd,KAAK,QAAQ,CAAC;YACd,KAAK,WAAW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\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { mapResults } from './mapResults';\nimport { Result, captureResult, fail, succeed } from './result';\n\n/**\n * @internal\n */\nexport type Entry<T> = [string | number | symbol, T];\n\n/**\n * @internal\n */\nexport type ResultEntry<T> = [string | number | symbol, Result<T>];\n\n/**\n * Normalizes an arbitrary JSON object\n * @public\n */\nexport class Normalizer {\n /**\n * Normalizes the supplied value\n *\n * @param from - The value to be normalized\n * @returns A normalized version of the value\n */\n public normalize<T>(from: T): Result<T> {\n switch (typeof from) {\n case 'string':\n case 'bigint':\n case 'boolean':\n case 'number':\n case 'symbol':\n case 'undefined':\n return this.normalizeLiteral(from);\n case 'object':\n if (from === null || from instanceof Date || from instanceof RegExp) {\n return this.normalizeLiteral(from);\n } else if (Array.isArray(from)) {\n return this._normalizeArray(from) as unknown as Result<T>;\n } else if (from instanceof Map) {\n return succeed(new Map(this.normalizeEntries(from.entries())) as unknown as T);\n } else if (from instanceof Set) {\n return succeed(new Set(this.normalizeEntries(from.entries())) as unknown as T);\n }\n const obj: { [key in number | string | symbol]: unknown } = {};\n for (const e of this.normalizeEntries(Object.entries(from as unknown as object))) {\n obj[e[0]] = e[1];\n }\n return succeed(obj as T);\n }\n return fail(`normalize: Unexpected type - cannot normalize '${typeof from}'`);\n }\n\n /**\n * Produces a stable, byte-identical JSON string following RFC 8785\n * (JSON Canonicalization Scheme) key-ordering rules.\n *\n * Builds the output string directly rather than constructing an intermediate\n * JS object, so integer-string keys (`\"10\"`, `\"2\"`) retain lexicographic\n * order instead of being reordered numerically by the JS engine during\n * `JSON.stringify`.\n *\n * @param from - Any JSON-compatible value (string, number, boolean, null,\n * plain object, or array). Fails for non-JSON types (Map, Set, Date,\n * RegExp, function, symbol, bigint, undefined).\n * @returns `Result<string>` — the canonical JSON string, or a failure if\n * `from` contains non-serializable types.\n * @public\n */\n public canonicalize(from: unknown): Result<string> {\n return captureResult(() => this._canonicalizeRfc8785(from));\n }\n\n /**\n * Recursively builds a byte-identical RFC 8785 JSON string.\n * @throws For non-JSON-serializable types (non-finite numbers, Date, RegExp,\n * Map, Set, class instances, function, symbol, bigint, undefined).\n * Callers must wrap in captureResult.\n */\n protected _canonicalizeRfc8785(value: unknown): string {\n if (value === null) return 'null';\n if (typeof value === 'boolean') return value ? 'true' : 'false';\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new Error(`canonicalize: non-finite number (${value}) is not representable in JSON`);\n }\n return JSON.stringify(value);\n }\n if (typeof value === 'string') return JSON.stringify(value);\n if (Array.isArray(value)) {\n return '[' + value.map((item) => this._canonicalizeRfc8785(item)).join(',') + ']';\n }\n if (typeof value === 'object') {\n const proto = Object.getPrototypeOf(value as object) as unknown;\n if (proto !== Object.prototype && proto !== null) {\n throw new Error(\n `canonicalize: cannot serialize non-plain object (${Object.prototype.toString.call(value)})`\n );\n }\n const obj = value as Record<string, unknown>;\n const sortedKeys = Object.keys(obj).sort((k1, k2) => this._compareKeys(k1, k2));\n const pairs = sortedKeys.map((k) => JSON.stringify(k) + ':' + this._canonicalizeRfc8785(obj[k]));\n return '{' + pairs.join(',') + '}';\n }\n throw new Error(`canonicalize: cannot serialize value of type '${typeof value}'`);\n }\n\n /**\n * Compares two property names from some object being normalized.\n * @param k1 - First key to be compared.\n * @param k2 - Second key to be compared.\n * @returns `1` if `k1` is greater, `-1` if `k2` is greater and\n * `0` if they are equal.\n * @internal\n */\n protected _compareKeys(k1: unknown, k2: unknown): number {\n const cs1 = String(k1);\n const cs2 = String(k2);\n if (cs1 > cs2) {\n return 1;\n }\n if (cs2 > cs1) {\n return -1;\n }\n /* c8 ignore next 2 */\n return 0;\n }\n\n /**\n * Normalizes an array of object property entries (e.g. as returned by `Object.entries()`).\n * @remarks\n * Converts property names (entry key) to string and then sorts as string.\n * @param entries - The entries to be normalized.\n * @returns A normalized sorted array of entries.\n */\n public normalizeEntries<T = unknown>(entries: Iterable<Entry<T>>): Entry<T>[] {\n return Array.from(entries)\n .sort((e1, e2) => this._compareKeys(e1[0], e2[0]))\n .map((e) => [e[0], this.normalize(e[1])] as ResultEntry<T>)\n .filter((e) => e[1].isSuccess())\n .map((e) => [e[0], e[1].orThrow()]);\n }\n\n protected _normalizeArray(from: unknown[]): Result<unknown[]> {\n return mapResults(from.map((v) => this.normalize(v)));\n }\n\n /**\n * Normalizes the supplied literal value\n * @param from - The literal value to be normalized.\n * @returns A normalized value for the literal.\n */\n public normalizeLiteral<T>(from: T): Result<T> {\n // TODO: Apply configurable normalization rules\n switch (typeof from) {\n case 'string':\n return succeed(from);\n case 'bigint':\n case 'boolean':\n case 'number':\n case 'symbol':\n case 'undefined':\n return succeed(from);\n }\n if (from === null) {\n return succeed(from);\n }\n if (from instanceof Date) {\n return succeed(from);\n }\n if (from instanceof RegExp) {\n return succeed(from);\n }\n /* c8 ignore next 2 */\n return fail(`cannot normalize ${JSON.stringify(from)}`);\n }\n}\n"]}
@@ -19,6 +19,7 @@
19
19
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
20
  * SOFTWARE.
21
21
  */
22
+ import { _findShouldNotFailFrame, _formatShouldNotFailMessage } from './shouldNotFail';
22
23
  /**
23
24
  * Checks if a result is a deferred result.
24
25
  * @param result - The result to check.
@@ -28,6 +29,17 @@
28
29
  export function isDeferredResult(result) {
29
30
  return typeof result === 'function';
30
31
  }
32
+ // Untyped (literal-tuple-inferred) source of truth for allMessageLogLevels, kept separate from the
33
+ // widened public export below so the exhaustiveness check actually inspects the literal values instead
34
+ // of being widened away to `MessageLogLevel` before the check runs.
35
+ const messageLogLevelValues = ['quiet', 'detail', 'info', 'warning', 'error'];
36
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
37
+ const _messageLogLevelExhaustivenessCheck = true;
38
+ /**
39
+ * Exhaustive list of all {@link MessageLogLevel} values.
40
+ * @public
41
+ */
42
+ export const allMessageLogLevels = messageLogLevelValues;
31
43
  /**
32
44
  * Reports a successful {@link IResult | result} from some operation and the
33
45
  * corresponding value.
@@ -70,6 +82,12 @@ export class Success {
70
82
  orThrow(__logger) {
71
83
  return this._value;
72
84
  }
85
+ /**
86
+ * {@inheritDoc IResult.shouldNotFail}
87
+ */
88
+ shouldNotFail(__label, __frameDepth) {
89
+ return this._value;
90
+ }
73
91
  orDefault(dflt) {
74
92
  var _a;
75
93
  return (_a = this._value) !== null && _a !== void 0 ? _a : dflt;
@@ -101,6 +119,26 @@ export class Success {
101
119
  onFailure(__) {
102
120
  return this;
103
121
  }
122
+ /**
123
+ * {@inheritDoc IResult.thenOnSuccess}
124
+ */
125
+ thenOnSuccess(cb) {
126
+ try {
127
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
128
+ return new AsyncResult(cb(this._value));
129
+ }
130
+ catch (err) {
131
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
132
+ return AsyncResult.from(fail(_errorMessage(err)));
133
+ }
134
+ }
135
+ /**
136
+ * {@inheritDoc IResult.thenOnFailure}
137
+ */
138
+ thenOnFailure(__) {
139
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
140
+ return AsyncResult.from(this);
141
+ }
104
142
  /**
105
143
  * {@inheritDoc IResult.withErrorFormat}
106
144
  */
@@ -194,6 +232,32 @@ export class Failure {
194
232
  }
195
233
  throw new Error(this._message);
196
234
  }
235
+ /**
236
+ * {@inheritDoc IResult.shouldNotFail}
237
+ */
238
+ shouldNotFail(label, frameDepth = 1) {
239
+ // Parse a probe Error's stack to identify the caller frame for message
240
+ // composition. We must NOT reuse this probe as the thrown Error: in V8,
241
+ // `.stack` is materialized lazily on first access (which happens below in
242
+ // `_findShouldNotFailFrame`), and once materialized the cached stack
243
+ // header carries whatever message was set at that moment. Mutating
244
+ // `.message` afterwards does not refresh the cached `.stack` header.
245
+ const probe = new Error();
246
+ if (typeof Error.captureStackTrace === 'function') {
247
+ Error.captureStackTrace(probe, this.shouldNotFail);
248
+ }
249
+ const frame = _findShouldNotFailFrame(probe.stack, frameDepth);
250
+ const message = _formatShouldNotFailMessage(this._message, label, frame);
251
+ // Build the final Error with the formatted message and re-elide
252
+ // `shouldNotFail` from its stack, so the thrown error's `.stack` shows
253
+ // both the formatted message in its header and the caller as its top
254
+ // frame.
255
+ const err = new Error(message);
256
+ if (typeof Error.captureStackTrace === 'function') {
257
+ Error.captureStackTrace(err, this.shouldNotFail);
258
+ }
259
+ throw err;
260
+ }
197
261
  orDefault(dflt) {
198
262
  return dflt;
199
263
  }
@@ -226,6 +290,26 @@ export class Failure {
226
290
  onFailure(cb) {
227
291
  return cb(this._message);
228
292
  }
293
+ /**
294
+ * {@inheritDoc IResult.thenOnSuccess}
295
+ */
296
+ thenOnSuccess(__) {
297
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
298
+ return AsyncResult.from(fail(this._message));
299
+ }
300
+ /**
301
+ * {@inheritDoc IResult.thenOnFailure}
302
+ */
303
+ thenOnFailure(cb) {
304
+ try {
305
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
306
+ return new AsyncResult(cb(this._message));
307
+ }
308
+ catch (err) {
309
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
310
+ return AsyncResult.from(fail(_errorMessage(err)));
311
+ }
312
+ }
229
313
  /**
230
314
  * {@inheritDoc IResult.withErrorFormat}
231
315
  */
@@ -263,6 +347,45 @@ export class Failure {
263
347
  reporter === null || reporter === void 0 ? void 0 : reporter.reportFailure(level, message);
264
348
  return this;
265
349
  }
350
+ /**
351
+ * Re-types this {@link Failure | Failure<T>} as {@link Failure | Failure<U>} for
352
+ * propagation under a different success type.
353
+ * @remarks
354
+ * Supports the canonical Result early-return-after-`isFailure()` pattern when the
355
+ * outer function's success type differs from the inner Result's success type:
356
+ *
357
+ * ```ts
358
+ * const storeResult = await PromptStoreFixture.build(seed);
359
+ * if (storeResult.isFailure()) {
360
+ * return storeResult.withType<PromptLibrary>();
361
+ * }
362
+ * return PromptLibrary.create({ store: storeResult.value, ... });
363
+ * ```
364
+ *
365
+ * Without this helper, TypeScript rejects `return storeResult` because
366
+ * `Failure<IPromptStore>` is invariant in `T` and not assignable to
367
+ * `Result<PromptLibrary>`. The workaround `return fail<U>(r.message)` is
368
+ * semantically equivalent but allocates a new {@link Failure} instance;
369
+ * `withType` returns `this` and only retypes statically.
370
+ *
371
+ * This method is sound because a {@link Failure} variant carries no `T`-shaped
372
+ * data — only an error message — so re-typing it as `Failure<U>` cannot
373
+ * misrepresent any value. The same operation is NOT exposed on {@link Success}
374
+ * because `Success<T>` carries `T`-shaped data and re-typing would be a lie.
375
+ *
376
+ * For `DetailedResult` propagation that preserves a typed `detail`, consider
377
+ * propagating the {@link DetailedFailure} directly through `onSuccess` (which
378
+ * already re-types the success arm) rather than reaching for `withType`.
379
+ *
380
+ * @returns This same {@link Failure} instance, statically retyped as
381
+ * {@link Failure | Failure<U>}.
382
+ * @public
383
+ */
384
+ withType() {
385
+ // Safe by construction: Failure carries no T-shaped data, only a message.
386
+ // Re-typing the static T parameter cannot misrepresent any value.
387
+ return this;
388
+ }
266
389
  /**
267
390
  * Get a 'friendly' string representation of this object.
268
391
  * @remarks
@@ -591,13 +714,25 @@ export function propagateWithDetail(result, detail, successDetail) {
591
714
  ? succeedWithDetail(result.value, successDetail !== null && successDetail !== void 0 ? successDetail : detail)
592
715
  : failWithDetail(result.message, detail);
593
716
  }
717
+ /**
718
+ * Extracts a message string from an unknown thrown/rejected value.
719
+ * @param err - The caught error value.
720
+ * @returns The error message string.
721
+ * @internal
722
+ */
723
+ export function _errorMessage(err) {
724
+ if (err instanceof Error) {
725
+ return err.message;
726
+ }
727
+ return String(err);
728
+ }
594
729
  /**
595
730
  * Wraps a function which might throw to convert exception results
596
731
  * to {@link Failure}.
597
732
  * @param func - The function to be captured.
598
733
  * @returns Returns {@link Success} with a value of type `<T>` on
599
734
  * success , or {@link Failure} with the thrown error message if
600
- * `func` throws an `Error`.
735
+ * `func` throws an `Error` or string.
601
736
  * @public
602
737
  */
603
738
  export function captureResult(func) {
@@ -605,7 +740,196 @@ export function captureResult(func) {
605
740
  return succeed(func());
606
741
  }
607
742
  catch (err) {
608
- return fail(err.message);
743
+ return fail(_errorMessage(err));
744
+ }
745
+ }
746
+ /**
747
+ * Wraps a `Promise` of a {@link Result} to enable fluent chaining of both
748
+ * synchronous and asynchronous operations.
749
+ *
750
+ * @remarks
751
+ * `AsyncResult<T>` implements `PromiseLike` so it can be directly `await`ed.
752
+ * Use the `thenOnSuccess` and `thenOnFailure` methods on {@link Result} to bridge
753
+ * from synchronous to asynchronous result chains.
754
+ *
755
+ * @example
756
+ * ```typescript
757
+ * const result: Result<Final> = await parseInput(input)
758
+ * .thenOnSuccess(async (parsed) => fetchData(parsed))
759
+ * .onSuccess((data) => transform(data))
760
+ * .thenOnSuccess(async (transformed) => saveData(transformed))
761
+ * .withErrorFormat((msg) => `pipeline failed: ${msg}`);
762
+ * ```
763
+ *
764
+ * @public
765
+ */
766
+ export class AsyncResult {
767
+ /**
768
+ * Constructs an {@link AsyncResult} wrapping the supplied promise (or any
769
+ * `PromiseLike` that resolves to a {@link Result}, such as another
770
+ * {@link AsyncResult}).
771
+ * @remarks
772
+ * If the supplied promise rejects, the rejection is caught and converted
773
+ * to a {@link Failure}, ensuring that awaiting an {@link AsyncResult} always
774
+ * yields a {@link Result}.
775
+ * @param promise - A `Promise` (or `PromiseLike`) that resolves to a
776
+ * {@link Result}.
777
+ */
778
+ constructor(promise) {
779
+ this._promise = Promise.resolve(promise).catch((err) => fail(_errorMessage(err)));
780
+ }
781
+ /**
782
+ * Calls a supplied {@link SuccessContinuation | success continuation} if
783
+ * the wrapped result is successful.
784
+ * @param cb - The synchronous {@link SuccessContinuation | success continuation}
785
+ * to be called in the event of success.
786
+ * @returns A new {@link AsyncResult} wrapping the continuation result.
787
+ */
788
+ onSuccess(cb) {
789
+ return new AsyncResult(this._promise.then((r) => r.onSuccess(cb)));
790
+ }
791
+ /**
792
+ * Calls a supplied {@link AsyncSuccessContinuation | async success continuation} if
793
+ * the wrapped result is successful.
794
+ * @remarks
795
+ * Both synchronous throws and async rejections from the callback are caught
796
+ * and converted to a {@link Failure}.
797
+ * @param cb - The {@link AsyncSuccessContinuation | async success continuation}
798
+ * to be called in the event of success.
799
+ * @returns A new {@link AsyncResult} wrapping the async continuation result.
800
+ */
801
+ thenOnSuccess(cb) {
802
+ return new AsyncResult(this._promise.then(async (r) => {
803
+ if (r.isFailure()) {
804
+ return fail(r.message);
805
+ }
806
+ try {
807
+ return await cb(r.value);
808
+ }
809
+ catch (err) {
810
+ return fail(_errorMessage(err));
811
+ }
812
+ }));
813
+ }
814
+ /**
815
+ * Calls a supplied {@link FailureContinuation | failure continuation} if
816
+ * the wrapped result is a failure.
817
+ * @param cb - The synchronous {@link FailureContinuation | failure continuation}
818
+ * to be called in the event of failure.
819
+ * @returns A new {@link AsyncResult} wrapping the continuation result.
820
+ */
821
+ onFailure(cb) {
822
+ return new AsyncResult(this._promise.then((r) => r.onFailure(cb)));
823
+ }
824
+ /**
825
+ * Calls a supplied {@link AsyncFailureContinuation | async failure continuation} if
826
+ * the wrapped result is a failure.
827
+ * @remarks
828
+ * Both synchronous throws and async rejections from the callback are caught
829
+ * and converted to a {@link Failure}.
830
+ * @param cb - The {@link AsyncFailureContinuation | async failure continuation}
831
+ * to be called in the event of failure.
832
+ * @returns A new {@link AsyncResult} wrapping the async continuation result.
833
+ */
834
+ thenOnFailure(cb) {
835
+ return new AsyncResult(this._promise.then(async (r) => {
836
+ if (r.isSuccess()) {
837
+ return r;
838
+ }
839
+ try {
840
+ return await cb(r.message);
841
+ }
842
+ catch (err) {
843
+ return fail(_errorMessage(err));
844
+ }
845
+ }));
846
+ }
847
+ /**
848
+ * Calls a supplied {@link ErrorFormatter | error formatter} if
849
+ * the wrapped result is a failure.
850
+ * @param cb - The {@link ErrorFormatter | error formatter} to
851
+ * be called in the event of failure.
852
+ * @returns A new {@link AsyncResult} with the formatted error message,
853
+ * or the original success result.
854
+ */
855
+ withErrorFormat(cb) {
856
+ return new AsyncResult(this._promise.then((r) => r.withErrorFormat(cb)));
857
+ }
858
+ /**
859
+ * Propagates the wrapped result, appending any error message to the
860
+ * supplied errors aggregator.
861
+ * @param errors - {@link IMessageAggregator | Error aggregator} in which
862
+ * errors will be aggregated.
863
+ * @param formatter - An optional {@link ErrorFormatter | error formatter}
864
+ * to be used to format the error message.
865
+ * @returns A new {@link AsyncResult} wrapping the result after aggregation.
866
+ */
867
+ aggregateError(errors, formatter) {
868
+ return new AsyncResult(this._promise.then((r) => {
869
+ r.aggregateError(errors, formatter);
870
+ return r;
871
+ }));
872
+ }
873
+ /**
874
+ * Reports the wrapped result to the supplied reporter.
875
+ * @param reporter - The {@link IResultReporter | reporter} to which the result
876
+ * will be reported.
877
+ * @param options - The {@link IResultReportOptions | options} for reporting the result.
878
+ * @returns A new {@link AsyncResult} wrapping the result after reporting.
879
+ */
880
+ report(reporter, options) {
881
+ return new AsyncResult(this._promise.then((r) => {
882
+ r.report(reporter, options);
883
+ return r;
884
+ }));
885
+ }
886
+ /**
887
+ * Implementation of `PromiseLike.then` enabling `await` on {@link AsyncResult}.
888
+ * @param onfulfilled - Callback invoked when the promise resolves.
889
+ * @param onrejected - Callback invoked when the promise rejects.
890
+ * @returns A `Promise` resolving to the callback result.
891
+ */
892
+ /* eslint-disable @rushstack/no-new-null */
893
+ then(onfulfilled, onrejected) {
894
+ /* eslint-enable @rushstack/no-new-null */
895
+ return this._promise.then(onfulfilled, onrejected);
896
+ }
897
+ /**
898
+ * Creates an {@link AsyncResult} from a {@link Result}.
899
+ * @param result - The {@link Result} to wrap.
900
+ * @returns A new {@link AsyncResult} wrapping the supplied result.
901
+ */
902
+ static from(result) {
903
+ return new AsyncResult(Promise.resolve(result));
904
+ }
905
+ }
906
+ /**
907
+ * Wraps an async function which might throw to convert exception results
908
+ * to {@link Failure}.
909
+ * @remarks
910
+ * Returns an {@link AsyncResult} so callers can fluently chain
911
+ * (`.onSuccess` / `.thenOnSuccess` / `.withErrorFormat`) directly off the
912
+ * captured result. Because {@link AsyncResult} implements
913
+ * `PromiseLike<Result<T>>`, existing `await captureAsyncResult(...)` call
914
+ * sites continue to work unchanged and yield the same {@link Result}.
915
+ *
916
+ * Synchronous throws from `func` (before it returns its `Promise`), promise
917
+ * rejections, and successful resolutions are all funneled through the
918
+ * returned {@link AsyncResult}, which resolves to a {@link Failure} for the
919
+ * throw/reject cases and a {@link Success} wrapping the resolved value
920
+ * otherwise.
921
+ * @param func - The async function to be captured.
922
+ * @returns An {@link AsyncResult} resolving to {@link Success} with a value
923
+ * of type `<T>` on success, or {@link Failure} with the thrown error message
924
+ * if `func` throws or rejects.
925
+ * @public
926
+ */
927
+ export function captureAsyncResult(func) {
928
+ try {
929
+ return new AsyncResult(func().then((value) => succeed(value)));
930
+ }
931
+ catch (err) {
932
+ return AsyncResult.from(fail(_errorMessage(err)));
609
933
  }
610
934
  }
611
935
  //# sourceMappingURL=result.js.map