@fgv/ts-utils 5.1.0-3 → 5.1.0-31

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 (276) hide show
  1. package/README.md +21 -0
  2. package/dist/index.js.map +1 -0
  3. package/dist/packlets/base/brand.js.map +1 -0
  4. package/dist/packlets/base/index.js +2 -0
  5. package/dist/packlets/base/index.js.map +1 -0
  6. package/dist/packlets/base/mapResults.js.map +1 -0
  7. package/dist/packlets/base/messageAggregator.js.map +1 -0
  8. package/dist/packlets/base/normalize.js +54 -1
  9. package/dist/packlets/base/normalize.js.map +1 -0
  10. package/dist/packlets/base/result.js +299 -2
  11. package/dist/packlets/base/result.js.map +1 -0
  12. package/dist/packlets/base/shouldNotFail.js +123 -0
  13. package/dist/packlets/base/shouldNotFail.js.map +1 -0
  14. package/dist/packlets/base/utils.js.map +1 -0
  15. package/dist/packlets/base/uuid.js +55 -0
  16. package/dist/packlets/base/uuid.js.map +1 -0
  17. package/dist/packlets/collections/aggregatedResultMap.js.map +1 -0
  18. package/dist/packlets/collections/collectible.js.map +1 -0
  19. package/dist/packlets/collections/collector.js +23 -9
  20. package/dist/packlets/collections/collector.js.map +1 -0
  21. package/dist/packlets/collections/collectorValidator.js +6 -1
  22. package/dist/packlets/collections/collectorValidator.js.map +1 -0
  23. package/dist/packlets/collections/common.js.map +1 -0
  24. package/dist/packlets/collections/converters.js.map +1 -0
  25. package/dist/packlets/collections/convertingCollector.js.map +1 -0
  26. package/dist/packlets/collections/convertingCollectorValidator.js.map +1 -0
  27. package/dist/packlets/collections/convertingResultMap.js.map +1 -0
  28. package/dist/packlets/collections/index.js.map +1 -0
  29. package/dist/packlets/collections/keyValueConverters.js.map +1 -0
  30. package/dist/packlets/collections/readOnlyConvertingResultMap.js.map +1 -0
  31. package/dist/packlets/collections/readonlyResultMap.js.map +1 -0
  32. package/dist/packlets/collections/resultMap.js.map +1 -0
  33. package/dist/packlets/collections/resultMapValidator.js.map +1 -0
  34. package/dist/packlets/collections/utils.js.map +1 -0
  35. package/dist/packlets/collections/validatingCollector.js.map +1 -0
  36. package/dist/packlets/collections/validatingConvertingCollector.js.map +1 -0
  37. package/dist/packlets/collections/validatingConvertingResultMap.js.map +1 -0
  38. package/dist/packlets/collections/validatingResultMap.js.map +1 -0
  39. package/dist/packlets/conversion/advancedConverters.js.map +1 -0
  40. package/dist/packlets/conversion/baseConverter.js +102 -16
  41. package/dist/packlets/conversion/baseConverter.js.map +1 -0
  42. package/dist/packlets/conversion/basicConverters.js.map +1 -0
  43. package/dist/packlets/conversion/converter.js.map +1 -0
  44. package/dist/packlets/conversion/converters.js.map +1 -0
  45. package/dist/packlets/conversion/defaultingConverter.js.map +1 -0
  46. package/dist/packlets/conversion/index.js.map +1 -0
  47. package/dist/packlets/conversion/objectConverter.js.map +1 -0
  48. package/dist/packlets/conversion/stringConverter.js.map +1 -0
  49. package/dist/packlets/hash/crcNormalizer.js.map +1 -0
  50. package/dist/packlets/hash/hashingNormalizer.js.map +1 -0
  51. package/dist/packlets/hash/index.js.map +1 -0
  52. package/dist/packlets/logging/bootLogger.js.map +1 -0
  53. package/dist/packlets/logging/index.js +2 -0
  54. package/dist/packlets/logging/index.js.map +1 -0
  55. package/dist/packlets/logging/logReporter.js.map +1 -0
  56. package/dist/packlets/logging/logger.js +49 -8
  57. package/dist/packlets/logging/logger.js.map +1 -0
  58. package/dist/packlets/logging/multiLogger.js +104 -0
  59. package/dist/packlets/logging/multiLogger.js.map +1 -0
  60. package/dist/packlets/logging/retainingLogger.js +161 -0
  61. package/dist/packlets/logging/retainingLogger.js.map +1 -0
  62. package/dist/packlets/validation/array.js.map +1 -0
  63. package/dist/packlets/validation/boolean.js.map +1 -0
  64. package/dist/packlets/validation/classes.js.map +1 -0
  65. package/dist/packlets/validation/common.js.map +1 -0
  66. package/dist/packlets/validation/compositeId.js.map +1 -0
  67. package/dist/packlets/validation/field.js.map +1 -0
  68. package/dist/packlets/validation/genericValidator.js.map +1 -0
  69. package/dist/packlets/validation/index.js.map +1 -0
  70. package/dist/packlets/validation/number.js.map +1 -0
  71. package/dist/packlets/validation/object.js.map +1 -0
  72. package/dist/packlets/validation/oneOf.js.map +1 -0
  73. package/dist/packlets/validation/string.js.map +1 -0
  74. package/dist/packlets/validation/traits.js.map +1 -0
  75. package/dist/packlets/validation/typeGuard.js.map +1 -0
  76. package/dist/packlets/validation/validator.js.map +1 -0
  77. package/dist/packlets/validation/validatorBase.js.map +1 -0
  78. package/dist/packlets/validation/validators.js.map +1 -0
  79. package/dist/ts-utils.d.ts +861 -57
  80. package/dist/tsdoc-metadata.json +1 -1
  81. package/lib/index.d.ts.map +1 -0
  82. package/lib/index.js.map +1 -0
  83. package/lib/packlets/base/brand.d.ts.map +1 -0
  84. package/lib/packlets/base/brand.js.map +1 -0
  85. package/lib/packlets/base/index.d.ts +2 -0
  86. package/lib/packlets/base/index.d.ts.map +1 -0
  87. package/lib/packlets/base/index.js +2 -0
  88. package/lib/packlets/base/index.js.map +1 -0
  89. package/lib/packlets/base/mapResults.d.ts.map +1 -0
  90. package/lib/packlets/base/mapResults.js.map +1 -0
  91. package/lib/packlets/base/messageAggregator.d.ts.map +1 -0
  92. package/lib/packlets/base/messageAggregator.js.map +1 -0
  93. package/lib/packlets/base/normalize.d.ts +24 -0
  94. package/lib/packlets/base/normalize.d.ts.map +1 -0
  95. package/lib/packlets/base/normalize.js +53 -0
  96. package/lib/packlets/base/normalize.js.map +1 -0
  97. package/lib/packlets/base/result.d.ts +263 -1
  98. package/lib/packlets/base/result.d.ts.map +1 -0
  99. package/lib/packlets/base/result.js +303 -3
  100. package/lib/packlets/base/result.js.map +1 -0
  101. package/lib/packlets/base/shouldNotFail.d.ts +53 -0
  102. package/lib/packlets/base/shouldNotFail.d.ts.map +1 -0
  103. package/lib/packlets/base/shouldNotFail.js +129 -0
  104. package/lib/packlets/base/shouldNotFail.js.map +1 -0
  105. package/lib/packlets/base/utils.d.ts +12 -0
  106. package/lib/packlets/base/utils.d.ts.map +1 -0
  107. package/lib/packlets/base/utils.js.map +1 -0
  108. package/lib/packlets/base/uuid.d.ts +27 -0
  109. package/lib/packlets/base/uuid.d.ts.map +1 -0
  110. package/lib/packlets/base/uuid.js +59 -0
  111. package/lib/packlets/base/uuid.js.map +1 -0
  112. package/lib/packlets/collections/aggregatedResultMap.d.ts.map +1 -0
  113. package/lib/packlets/collections/aggregatedResultMap.js.map +1 -0
  114. package/lib/packlets/collections/collectible.d.ts.map +1 -0
  115. package/lib/packlets/collections/collectible.js.map +1 -0
  116. package/lib/packlets/collections/collector.d.ts +23 -9
  117. package/lib/packlets/collections/collector.d.ts.map +1 -0
  118. package/lib/packlets/collections/collector.js +23 -9
  119. package/lib/packlets/collections/collector.js.map +1 -0
  120. package/lib/packlets/collections/collectorValidator.d.ts +29 -5
  121. package/lib/packlets/collections/collectorValidator.d.ts.map +1 -0
  122. package/lib/packlets/collections/collectorValidator.js +6 -1
  123. package/lib/packlets/collections/collectorValidator.js.map +1 -0
  124. package/lib/packlets/collections/common.d.ts.map +1 -0
  125. package/lib/packlets/collections/common.js.map +1 -0
  126. package/lib/packlets/collections/converters.d.ts.map +1 -0
  127. package/lib/packlets/collections/converters.js.map +1 -0
  128. package/lib/packlets/collections/convertingCollector.d.ts +21 -3
  129. package/lib/packlets/collections/convertingCollector.d.ts.map +1 -0
  130. package/lib/packlets/collections/convertingCollector.js.map +1 -0
  131. package/lib/packlets/collections/convertingCollectorValidator.d.ts +22 -3
  132. package/lib/packlets/collections/convertingCollectorValidator.d.ts.map +1 -0
  133. package/lib/packlets/collections/convertingCollectorValidator.js.map +1 -0
  134. package/lib/packlets/collections/convertingResultMap.d.ts.map +1 -0
  135. package/lib/packlets/collections/convertingResultMap.js.map +1 -0
  136. package/lib/packlets/collections/index.d.ts.map +1 -0
  137. package/lib/packlets/collections/index.js.map +1 -0
  138. package/lib/packlets/collections/keyValueConverters.d.ts.map +1 -0
  139. package/lib/packlets/collections/keyValueConverters.js.map +1 -0
  140. package/lib/packlets/collections/readOnlyConvertingResultMap.d.ts.map +1 -0
  141. package/lib/packlets/collections/readOnlyConvertingResultMap.js.map +1 -0
  142. package/lib/packlets/collections/readonlyResultMap.d.ts +18 -7
  143. package/lib/packlets/collections/readonlyResultMap.d.ts.map +1 -0
  144. package/lib/packlets/collections/readonlyResultMap.js.map +1 -0
  145. package/lib/packlets/collections/resultMap.d.ts.map +1 -0
  146. package/lib/packlets/collections/resultMap.js.map +1 -0
  147. package/lib/packlets/collections/resultMapValidator.d.ts.map +1 -0
  148. package/lib/packlets/collections/resultMapValidator.js.map +1 -0
  149. package/lib/packlets/collections/utils.d.ts.map +1 -0
  150. package/lib/packlets/collections/utils.js.map +1 -0
  151. package/lib/packlets/collections/validatingCollector.d.ts +7 -3
  152. package/lib/packlets/collections/validatingCollector.d.ts.map +1 -0
  153. package/lib/packlets/collections/validatingCollector.js.map +1 -0
  154. package/lib/packlets/collections/validatingConvertingCollector.d.ts.map +1 -0
  155. package/lib/packlets/collections/validatingConvertingCollector.js.map +1 -0
  156. package/lib/packlets/collections/validatingConvertingResultMap.d.ts.map +1 -0
  157. package/lib/packlets/collections/validatingConvertingResultMap.js.map +1 -0
  158. package/lib/packlets/collections/validatingResultMap.d.ts +2 -1
  159. package/lib/packlets/collections/validatingResultMap.d.ts.map +1 -0
  160. package/lib/packlets/collections/validatingResultMap.js.map +1 -0
  161. package/lib/packlets/conversion/advancedConverters.d.ts.map +1 -0
  162. package/lib/packlets/conversion/advancedConverters.js.map +1 -0
  163. package/lib/packlets/conversion/baseConverter.d.ts +102 -16
  164. package/lib/packlets/conversion/baseConverter.d.ts.map +1 -0
  165. package/lib/packlets/conversion/baseConverter.js +102 -16
  166. package/lib/packlets/conversion/baseConverter.js.map +1 -0
  167. package/lib/packlets/conversion/basicConverters.d.ts.map +1 -0
  168. package/lib/packlets/conversion/basicConverters.js.map +1 -0
  169. package/lib/packlets/conversion/converter.d.ts.map +1 -0
  170. package/lib/packlets/conversion/converter.js.map +1 -0
  171. package/lib/packlets/conversion/converters.d.ts.map +1 -0
  172. package/lib/packlets/conversion/converters.js.map +1 -0
  173. package/lib/packlets/conversion/defaultingConverter.d.ts.map +1 -0
  174. package/lib/packlets/conversion/defaultingConverter.js.map +1 -0
  175. package/lib/packlets/conversion/index.d.ts.map +1 -0
  176. package/lib/packlets/conversion/index.js.map +1 -0
  177. package/lib/packlets/conversion/objectConverter.d.ts.map +1 -0
  178. package/lib/packlets/conversion/objectConverter.js.map +1 -0
  179. package/lib/packlets/conversion/stringConverter.d.ts.map +1 -0
  180. package/lib/packlets/conversion/stringConverter.js.map +1 -0
  181. package/lib/packlets/hash/crcNormalizer.d.ts.map +1 -0
  182. package/lib/packlets/hash/crcNormalizer.js.map +1 -0
  183. package/lib/packlets/hash/hashingNormalizer.d.ts.map +1 -0
  184. package/lib/packlets/hash/hashingNormalizer.js.map +1 -0
  185. package/lib/packlets/hash/index.d.ts.map +1 -0
  186. package/lib/packlets/hash/index.js.map +1 -0
  187. package/lib/packlets/logging/bootLogger.d.ts.map +1 -0
  188. package/lib/packlets/logging/bootLogger.js.map +1 -0
  189. package/lib/packlets/logging/index.d.ts +2 -0
  190. package/lib/packlets/logging/index.d.ts.map +1 -0
  191. package/lib/packlets/logging/index.js +2 -0
  192. package/lib/packlets/logging/index.js.map +1 -0
  193. package/lib/packlets/logging/logReporter.d.ts.map +1 -0
  194. package/lib/packlets/logging/logReporter.js.map +1 -0
  195. package/lib/packlets/logging/logger.d.ts +46 -8
  196. package/lib/packlets/logging/logger.d.ts.map +1 -0
  197. package/lib/packlets/logging/logger.js +49 -8
  198. package/lib/packlets/logging/logger.js.map +1 -0
  199. package/lib/packlets/logging/multiLogger.d.ts +54 -0
  200. package/lib/packlets/logging/multiLogger.d.ts.map +1 -0
  201. package/lib/packlets/logging/multiLogger.js +108 -0
  202. package/lib/packlets/logging/multiLogger.js.map +1 -0
  203. package/lib/packlets/logging/retainingLogger.d.ts +143 -0
  204. package/lib/packlets/logging/retainingLogger.d.ts.map +1 -0
  205. package/lib/packlets/logging/retainingLogger.js +165 -0
  206. package/lib/packlets/logging/retainingLogger.js.map +1 -0
  207. package/lib/packlets/validation/array.d.ts.map +1 -0
  208. package/lib/packlets/validation/array.js.map +1 -0
  209. package/lib/packlets/validation/boolean.d.ts.map +1 -0
  210. package/lib/packlets/validation/boolean.js.map +1 -0
  211. package/lib/packlets/validation/classes.d.ts.map +1 -0
  212. package/lib/packlets/validation/classes.js.map +1 -0
  213. package/lib/packlets/validation/common.d.ts.map +1 -0
  214. package/lib/packlets/validation/common.js.map +1 -0
  215. package/lib/packlets/validation/compositeId.d.ts.map +1 -0
  216. package/lib/packlets/validation/compositeId.js.map +1 -0
  217. package/lib/packlets/validation/field.d.ts.map +1 -0
  218. package/lib/packlets/validation/field.js.map +1 -0
  219. package/lib/packlets/validation/genericValidator.d.ts.map +1 -0
  220. package/lib/packlets/validation/genericValidator.js.map +1 -0
  221. package/lib/packlets/validation/index.d.ts.map +1 -0
  222. package/lib/packlets/validation/index.js.map +1 -0
  223. package/lib/packlets/validation/number.d.ts.map +1 -0
  224. package/lib/packlets/validation/number.js.map +1 -0
  225. package/lib/packlets/validation/object.d.ts.map +1 -0
  226. package/lib/packlets/validation/object.js.map +1 -0
  227. package/lib/packlets/validation/oneOf.d.ts.map +1 -0
  228. package/lib/packlets/validation/oneOf.js.map +1 -0
  229. package/lib/packlets/validation/string.d.ts.map +1 -0
  230. package/lib/packlets/validation/string.js.map +1 -0
  231. package/lib/packlets/validation/traits.d.ts.map +1 -0
  232. package/lib/packlets/validation/traits.js.map +1 -0
  233. package/lib/packlets/validation/typeGuard.d.ts.map +1 -0
  234. package/lib/packlets/validation/typeGuard.js.map +1 -0
  235. package/lib/packlets/validation/validator.d.ts.map +1 -0
  236. package/lib/packlets/validation/validator.js.map +1 -0
  237. package/lib/packlets/validation/validatorBase.d.ts +2 -1
  238. package/lib/packlets/validation/validatorBase.d.ts.map +1 -0
  239. package/lib/packlets/validation/validatorBase.js.map +1 -0
  240. package/lib/packlets/validation/validators.d.ts.map +1 -0
  241. package/lib/packlets/validation/validators.js.map +1 -0
  242. package/package.json +6 -4
  243. package/dist/test/helpers/jest/helpers/fsHelpers.js +0 -139
  244. package/dist/test/helpers/jest/helpers/index.js +0 -2
  245. package/dist/test/helpers/jest/index.js +0 -17
  246. package/dist/test/helpers/jest/matchers/index.js +0 -14
  247. package/dist/test/helpers/jest/matchers/toFail/index.js +0 -23
  248. package/dist/test/helpers/jest/matchers/toFail/predicate.js +0 -5
  249. package/dist/test/helpers/jest/matchers/toFailTest/index.js +0 -28
  250. package/dist/test/helpers/jest/matchers/toFailTest/predicate.js +0 -8
  251. package/dist/test/helpers/jest/matchers/toFailTestAndMatchSnapshot/index.js +0 -24
  252. package/dist/test/helpers/jest/matchers/toFailTestAndMatchSnapshot/predicate.js +0 -11
  253. package/dist/test/helpers/jest/matchers/toFailTestWith/index.js +0 -29
  254. package/dist/test/helpers/jest/matchers/toFailTestWith/predicate.js +0 -26
  255. package/dist/test/helpers/jest/matchers/toFailWith/index.js +0 -27
  256. package/dist/test/helpers/jest/matchers/toFailWith/predicate.js +0 -16
  257. package/dist/test/helpers/jest/matchers/toFailWithDetail/index.js +0 -27
  258. package/dist/test/helpers/jest/matchers/toFailWithDetail/predicate.js +0 -22
  259. package/dist/test/helpers/jest/matchers/toSucceed/index.js +0 -23
  260. package/dist/test/helpers/jest/matchers/toSucceed/predicate.js +0 -5
  261. package/dist/test/helpers/jest/matchers/toSucceedAndMatchInlineSnapshot/index.js +0 -24
  262. package/dist/test/helpers/jest/matchers/toSucceedAndMatchSnapshot/index.js +0 -24
  263. package/dist/test/helpers/jest/matchers/toSucceedAndSatisfy/index.js +0 -53
  264. package/dist/test/helpers/jest/matchers/toSucceedAndSatisfy/predicate.js +0 -17
  265. package/dist/test/helpers/jest/matchers/toSucceedWith/index.js +0 -27
  266. package/dist/test/helpers/jest/matchers/toSucceedWith/predicate.js +0 -12
  267. package/dist/test/helpers/jest/matchers/toSucceedWithDetail/index.js +0 -27
  268. package/dist/test/helpers/jest/matchers/toSucceedWithDetail/predicate.js +0 -17
  269. package/dist/test/helpers/jest/resolvers/cli.js +0 -10
  270. package/dist/test/helpers/jest/resolvers/ide.js +0 -10
  271. package/dist/test/helpers/jest/ts-utils.js +0 -2
  272. package/dist/test/helpers/jest/types/index.js +0 -3
  273. package/dist/test/helpers/jest/utils/matcherHelpers.js +0 -47
  274. package/dist/test/helpers/jest/utils/snapshotResolver.js +0 -11
  275. package/dist/test/unit/collections/helpers.js +0 -106
  276. 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
@@ -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,EAEnB,SAAS,EACT,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,EACP,eAAe,EACf,SAAS,EACT,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 ResultMap,\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 ObjectConverter,\n ResultMap,\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;;;;;;;;;GASG;AACH,MAAM,UAAU,UAAU,CACxB,OAA4B,EAC5B,gBAAqC;IAErC,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,MAAM,QAAQ,GAAQ,EAAE,CAAC;IAEzB,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,MAAM,CAAC,SAAS,EAAE,EAAE,CAAC;YACvB,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAC9B,CAAC;aAAM,CAAC;YACN,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAC9B,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,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O,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;;OA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AAI,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;gBACd,OAAO,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC;YACrC,KAAK,QAAQ;gBACX,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,YAAY,IAAI,IAAI,IAAI,YAAY,MAAM,EAAE,CAAC;oBACpE,OAAO,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC;gBACrC,CAAC;qBAAM,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;oBAC/B,OAAO,IAAI,CAAC,eAAe,CAAC,IAAI,CAAyB,CAAC;gBAC5D,CAAC;qBAAM,IAAI,IAAI,YAAY,GAAG,EAAE,CAAC;oBAC/B,OAAO,OAAO,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAiB,CAAC,CAAC;gBACjF,CAAC;qBAAM,IAAI,IAAI,YAAY,GAAG,EAAE,CAAC;oBAC/B,OAAO,OAAO,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AAC,CAAC;YACvB,KAAK,QAAQ,CAAC;YACd,KAAK,SAAS,CAAC;YACf,KAAK,QAAQ,CAAC;YACd,KAAK,QAAQ,CAAC;YACd,KAAK,WAAW;gBACd,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC;QACzB,CAAC;QACD,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;YAClB,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC;QACvB,CAAC;QACD,IAAI,IAAI,YAAY,IAAI,EAAE,CAAC;YACzB,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC;QACvB,CAAC;QACD,IAAI,IAAI,YAAY,MAAM,EAAE,CAAC;YAC3B,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC;QACvB,CAAC;QACD,sBAAsB;QACtB,OAAO,IAAI,CAAC,oBAAoB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC1D,CAAC;CACF","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\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.
@@ -70,6 +71,12 @@ export class Success {
70
71
  orThrow(__logger) {
71
72
  return this._value;
72
73
  }
74
+ /**
75
+ * {@inheritDoc IResult.shouldNotFail}
76
+ */
77
+ shouldNotFail(__label, __frameDepth) {
78
+ return this._value;
79
+ }
73
80
  orDefault(dflt) {
74
81
  var _a;
75
82
  return (_a = this._value) !== null && _a !== void 0 ? _a : dflt;
@@ -101,6 +108,26 @@ export class Success {
101
108
  onFailure(__) {
102
109
  return this;
103
110
  }
111
+ /**
112
+ * {@inheritDoc IResult.thenOnSuccess}
113
+ */
114
+ thenOnSuccess(cb) {
115
+ try {
116
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
117
+ return new AsyncResult(cb(this._value));
118
+ }
119
+ catch (err) {
120
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
121
+ return AsyncResult.from(fail(_errorMessage(err)));
122
+ }
123
+ }
124
+ /**
125
+ * {@inheritDoc IResult.thenOnFailure}
126
+ */
127
+ thenOnFailure(__) {
128
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
129
+ return AsyncResult.from(this);
130
+ }
104
131
  /**
105
132
  * {@inheritDoc IResult.withErrorFormat}
106
133
  */
@@ -194,6 +221,32 @@ export class Failure {
194
221
  }
195
222
  throw new Error(this._message);
196
223
  }
224
+ /**
225
+ * {@inheritDoc IResult.shouldNotFail}
226
+ */
227
+ shouldNotFail(label, frameDepth = 1) {
228
+ // Parse a probe Error's stack to identify the caller frame for message
229
+ // composition. We must NOT reuse this probe as the thrown Error: in V8,
230
+ // `.stack` is materialized lazily on first access (which happens below in
231
+ // `_findShouldNotFailFrame`), and once materialized the cached stack
232
+ // header carries whatever message was set at that moment. Mutating
233
+ // `.message` afterwards does not refresh the cached `.stack` header.
234
+ const probe = new Error();
235
+ if (typeof Error.captureStackTrace === 'function') {
236
+ Error.captureStackTrace(probe, this.shouldNotFail);
237
+ }
238
+ const frame = _findShouldNotFailFrame(probe.stack, frameDepth);
239
+ const message = _formatShouldNotFailMessage(this._message, label, frame);
240
+ // Build the final Error with the formatted message and re-elide
241
+ // `shouldNotFail` from its stack, so the thrown error's `.stack` shows
242
+ // both the formatted message in its header and the caller as its top
243
+ // frame.
244
+ const err = new Error(message);
245
+ if (typeof Error.captureStackTrace === 'function') {
246
+ Error.captureStackTrace(err, this.shouldNotFail);
247
+ }
248
+ throw err;
249
+ }
197
250
  orDefault(dflt) {
198
251
  return dflt;
199
252
  }
@@ -226,6 +279,26 @@ export class Failure {
226
279
  onFailure(cb) {
227
280
  return cb(this._message);
228
281
  }
282
+ /**
283
+ * {@inheritDoc IResult.thenOnSuccess}
284
+ */
285
+ thenOnSuccess(__) {
286
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
287
+ return AsyncResult.from(fail(this._message));
288
+ }
289
+ /**
290
+ * {@inheritDoc IResult.thenOnFailure}
291
+ */
292
+ thenOnFailure(cb) {
293
+ try {
294
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
295
+ return new AsyncResult(cb(this._message));
296
+ }
297
+ catch (err) {
298
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
299
+ return AsyncResult.from(fail(_errorMessage(err)));
300
+ }
301
+ }
229
302
  /**
230
303
  * {@inheritDoc IResult.withErrorFormat}
231
304
  */
@@ -263,6 +336,45 @@ export class Failure {
263
336
  reporter === null || reporter === void 0 ? void 0 : reporter.reportFailure(level, message);
264
337
  return this;
265
338
  }
339
+ /**
340
+ * Re-types this {@link Failure | Failure<T>} as {@link Failure | Failure<U>} for
341
+ * propagation under a different success type.
342
+ * @remarks
343
+ * Supports the canonical Result early-return-after-`isFailure()` pattern when the
344
+ * outer function's success type differs from the inner Result's success type:
345
+ *
346
+ * ```ts
347
+ * const storeResult = await PromptStoreFixture.build(seed);
348
+ * if (storeResult.isFailure()) {
349
+ * return storeResult.withType<PromptLibrary>();
350
+ * }
351
+ * return PromptLibrary.create({ store: storeResult.value, ... });
352
+ * ```
353
+ *
354
+ * Without this helper, TypeScript rejects `return storeResult` because
355
+ * `Failure<IPromptStore>` is invariant in `T` and not assignable to
356
+ * `Result<PromptLibrary>`. The workaround `return fail<U>(r.message)` is
357
+ * semantically equivalent but allocates a new {@link Failure} instance;
358
+ * `withType` returns `this` and only retypes statically.
359
+ *
360
+ * This method is sound because a {@link Failure} variant carries no `T`-shaped
361
+ * data — only an error message — so re-typing it as `Failure<U>` cannot
362
+ * misrepresent any value. The same operation is NOT exposed on {@link Success}
363
+ * because `Success<T>` carries `T`-shaped data and re-typing would be a lie.
364
+ *
365
+ * For `DetailedResult` propagation that preserves a typed `detail`, consider
366
+ * propagating the {@link DetailedFailure} directly through `onSuccess` (which
367
+ * already re-types the success arm) rather than reaching for `withType`.
368
+ *
369
+ * @returns This same {@link Failure} instance, statically retyped as
370
+ * {@link Failure | Failure<U>}.
371
+ * @public
372
+ */
373
+ withType() {
374
+ // Safe by construction: Failure carries no T-shaped data, only a message.
375
+ // Re-typing the static T parameter cannot misrepresent any value.
376
+ return this;
377
+ }
266
378
  /**
267
379
  * Get a 'friendly' string representation of this object.
268
380
  * @remarks
@@ -591,13 +703,25 @@ export function propagateWithDetail(result, detail, successDetail) {
591
703
  ? succeedWithDetail(result.value, successDetail !== null && successDetail !== void 0 ? successDetail : detail)
592
704
  : failWithDetail(result.message, detail);
593
705
  }
706
+ /**
707
+ * Extracts a message string from an unknown thrown/rejected value.
708
+ * @param err - The caught error value.
709
+ * @returns The error message string.
710
+ * @internal
711
+ */
712
+ export function _errorMessage(err) {
713
+ if (err instanceof Error) {
714
+ return err.message;
715
+ }
716
+ return String(err);
717
+ }
594
718
  /**
595
719
  * Wraps a function which might throw to convert exception results
596
720
  * to {@link Failure}.
597
721
  * @param func - The function to be captured.
598
722
  * @returns Returns {@link Success} with a value of type `<T>` on
599
723
  * success , or {@link Failure} with the thrown error message if
600
- * `func` throws an `Error`.
724
+ * `func` throws an `Error` or string.
601
725
  * @public
602
726
  */
603
727
  export function captureResult(func) {
@@ -605,7 +729,180 @@ export function captureResult(func) {
605
729
  return succeed(func());
606
730
  }
607
731
  catch (err) {
608
- return fail(err.message);
732
+ return fail(_errorMessage(err));
733
+ }
734
+ }
735
+ /**
736
+ * Wraps a `Promise` of a {@link Result} to enable fluent chaining of both
737
+ * synchronous and asynchronous operations.
738
+ *
739
+ * @remarks
740
+ * `AsyncResult<T>` implements `PromiseLike` so it can be directly `await`ed.
741
+ * Use the `thenOnSuccess` and `thenOnFailure` methods on {@link Result} to bridge
742
+ * from synchronous to asynchronous result chains.
743
+ *
744
+ * @example
745
+ * ```typescript
746
+ * const result: Result<Final> = await parseInput(input)
747
+ * .thenOnSuccess(async (parsed) => fetchData(parsed))
748
+ * .onSuccess((data) => transform(data))
749
+ * .thenOnSuccess(async (transformed) => saveData(transformed))
750
+ * .withErrorFormat((msg) => `pipeline failed: ${msg}`);
751
+ * ```
752
+ *
753
+ * @public
754
+ */
755
+ export class AsyncResult {
756
+ /**
757
+ * Constructs an {@link AsyncResult} wrapping the supplied promise.
758
+ * @remarks
759
+ * If the supplied promise rejects, the rejection is caught and converted
760
+ * to a {@link Failure}, ensuring that awaiting an {@link AsyncResult} always
761
+ * yields a {@link Result}.
762
+ * @param promise - A `Promise` that resolves to a {@link Result}.
763
+ */
764
+ constructor(promise) {
765
+ this._promise = promise.catch((err) => fail(_errorMessage(err)));
766
+ }
767
+ /**
768
+ * Calls a supplied {@link SuccessContinuation | success continuation} if
769
+ * the wrapped result is successful.
770
+ * @param cb - The synchronous {@link SuccessContinuation | success continuation}
771
+ * to be called in the event of success.
772
+ * @returns A new {@link AsyncResult} wrapping the continuation result.
773
+ */
774
+ onSuccess(cb) {
775
+ return new AsyncResult(this._promise.then((r) => r.onSuccess(cb)));
776
+ }
777
+ /**
778
+ * Calls a supplied {@link AsyncSuccessContinuation | async success continuation} if
779
+ * the wrapped result is successful.
780
+ * @remarks
781
+ * Both synchronous throws and async rejections from the callback are caught
782
+ * and converted to a {@link Failure}.
783
+ * @param cb - The {@link AsyncSuccessContinuation | async success continuation}
784
+ * to be called in the event of success.
785
+ * @returns A new {@link AsyncResult} wrapping the async continuation result.
786
+ */
787
+ thenOnSuccess(cb) {
788
+ return new AsyncResult(this._promise.then(async (r) => {
789
+ if (r.isFailure()) {
790
+ return fail(r.message);
791
+ }
792
+ try {
793
+ return await cb(r.value);
794
+ }
795
+ catch (err) {
796
+ return fail(_errorMessage(err));
797
+ }
798
+ }));
799
+ }
800
+ /**
801
+ * Calls a supplied {@link FailureContinuation | failure continuation} if
802
+ * the wrapped result is a failure.
803
+ * @param cb - The synchronous {@link FailureContinuation | failure continuation}
804
+ * to be called in the event of failure.
805
+ * @returns A new {@link AsyncResult} wrapping the continuation result.
806
+ */
807
+ onFailure(cb) {
808
+ return new AsyncResult(this._promise.then((r) => r.onFailure(cb)));
809
+ }
810
+ /**
811
+ * Calls a supplied {@link AsyncFailureContinuation | async failure continuation} if
812
+ * the wrapped result is a failure.
813
+ * @remarks
814
+ * Both synchronous throws and async rejections from the callback are caught
815
+ * and converted to a {@link Failure}.
816
+ * @param cb - The {@link AsyncFailureContinuation | async failure continuation}
817
+ * to be called in the event of failure.
818
+ * @returns A new {@link AsyncResult} wrapping the async continuation result.
819
+ */
820
+ thenOnFailure(cb) {
821
+ return new AsyncResult(this._promise.then(async (r) => {
822
+ if (r.isSuccess()) {
823
+ return r;
824
+ }
825
+ try {
826
+ return await cb(r.message);
827
+ }
828
+ catch (err) {
829
+ return fail(_errorMessage(err));
830
+ }
831
+ }));
832
+ }
833
+ /**
834
+ * Calls a supplied {@link ErrorFormatter | error formatter} if
835
+ * the wrapped result is a failure.
836
+ * @param cb - The {@link ErrorFormatter | error formatter} to
837
+ * be called in the event of failure.
838
+ * @returns A new {@link AsyncResult} with the formatted error message,
839
+ * or the original success result.
840
+ */
841
+ withErrorFormat(cb) {
842
+ return new AsyncResult(this._promise.then((r) => r.withErrorFormat(cb)));
843
+ }
844
+ /**
845
+ * Propagates the wrapped result, appending any error message to the
846
+ * supplied errors aggregator.
847
+ * @param errors - {@link IMessageAggregator | Error aggregator} in which
848
+ * errors will be aggregated.
849
+ * @param formatter - An optional {@link ErrorFormatter | error formatter}
850
+ * to be used to format the error message.
851
+ * @returns A new {@link AsyncResult} wrapping the result after aggregation.
852
+ */
853
+ aggregateError(errors, formatter) {
854
+ return new AsyncResult(this._promise.then((r) => {
855
+ r.aggregateError(errors, formatter);
856
+ return r;
857
+ }));
858
+ }
859
+ /**
860
+ * Reports the wrapped result to the supplied reporter.
861
+ * @param reporter - The {@link IResultReporter | reporter} to which the result
862
+ * will be reported.
863
+ * @param options - The {@link IResultReportOptions | options} for reporting the result.
864
+ * @returns A new {@link AsyncResult} wrapping the result after reporting.
865
+ */
866
+ report(reporter, options) {
867
+ return new AsyncResult(this._promise.then((r) => {
868
+ r.report(reporter, options);
869
+ return r;
870
+ }));
871
+ }
872
+ /**
873
+ * Implementation of `PromiseLike.then` enabling `await` on {@link AsyncResult}.
874
+ * @param onfulfilled - Callback invoked when the promise resolves.
875
+ * @param onrejected - Callback invoked when the promise rejects.
876
+ * @returns A `Promise` resolving to the callback result.
877
+ */
878
+ /* eslint-disable @rushstack/no-new-null */
879
+ then(onfulfilled, onrejected) {
880
+ /* eslint-enable @rushstack/no-new-null */
881
+ return this._promise.then(onfulfilled, onrejected);
882
+ }
883
+ /**
884
+ * Creates an {@link AsyncResult} from a {@link Result}.
885
+ * @param result - The {@link Result} to wrap.
886
+ * @returns A new {@link AsyncResult} wrapping the supplied result.
887
+ */
888
+ static from(result) {
889
+ return new AsyncResult(Promise.resolve(result));
890
+ }
891
+ }
892
+ /**
893
+ * Wraps an async function which might throw to convert exception results
894
+ * to {@link Failure}.
895
+ * @param func - The async function to be captured.
896
+ * @returns Returns a `Promise` of {@link Success} with a value of type `<T>` on
897
+ * success, or {@link Failure} with the thrown error message if `func` throws or rejects.
898
+ * @public
899
+ */
900
+ export async function captureAsyncResult(func) {
901
+ try {
902
+ return succeed(await func());
903
+ }
904
+ catch (err) {
905
+ return fail(_errorMessage(err));
609
906
  }
610
907
  }
611
908
  //# sourceMappingURL=result.js.map