@fgv/ts-utils 5.0.2 → 5.1.0-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +152 -84
  2. package/dist/index.js +2 -2
  3. package/dist/packlets/base/messageAggregator.js +6 -6
  4. package/dist/packlets/base/result.js +39 -39
  5. package/dist/packlets/base/utils.js +47 -0
  6. package/dist/packlets/collections/aggregatedResultMap.js +722 -0
  7. package/dist/packlets/collections/collector.js +9 -9
  8. package/dist/packlets/collections/collectorValidator.js +4 -4
  9. package/dist/packlets/collections/converters.js +39 -0
  10. package/dist/packlets/collections/convertingCollectorValidator.js +3 -3
  11. package/dist/packlets/collections/convertingResultMap.js +208 -0
  12. package/dist/packlets/collections/index.js +4 -0
  13. package/dist/packlets/collections/keyValueConverters.js +1 -4
  14. package/dist/packlets/collections/readOnlyConvertingResultMap.js +193 -0
  15. package/dist/packlets/collections/resultMapValidator.js +50 -6
  16. package/dist/packlets/collections/validatingConvertingResultMap.js +78 -0
  17. package/dist/packlets/conversion/advancedConverters.js +249 -0
  18. package/dist/packlets/conversion/baseConverter.js +23 -16
  19. package/dist/packlets/conversion/basicConverters.js +571 -0
  20. package/dist/packlets/conversion/converters.js +3 -617
  21. package/dist/packlets/conversion/defaultingConverter.js +21 -15
  22. package/dist/packlets/logging/bootLogger.js +122 -0
  23. package/dist/packlets/logging/index.js +1 -0
  24. package/dist/packlets/logging/logReporter.js +32 -1
  25. package/dist/packlets/logging/logger.js +25 -5
  26. package/dist/packlets/validation/classes.js +1 -0
  27. package/dist/packlets/validation/compositeId.js +60 -0
  28. package/dist/packlets/validation/field.js +1 -1
  29. package/dist/packlets/validation/genericValidator.js +24 -10
  30. package/dist/packlets/validation/object.js +3 -6
  31. package/dist/packlets/validation/validators.js +12 -0
  32. package/dist/ts-utils.d.ts +1633 -200
  33. package/dist/tsdoc-metadata.json +1 -1
  34. package/lib/index.d.ts +2 -2
  35. package/lib/index.js +2 -1
  36. package/lib/packlets/base/mapResults.d.ts +3 -3
  37. package/lib/packlets/base/messageAggregator.d.ts +6 -6
  38. package/lib/packlets/base/messageAggregator.js +6 -6
  39. package/lib/packlets/base/result.d.ts +74 -51
  40. package/lib/packlets/base/result.js +39 -39
  41. package/lib/packlets/base/utils.d.ts +42 -0
  42. package/lib/packlets/base/utils.js +52 -0
  43. package/lib/packlets/collections/aggregatedResultMap.d.ts +433 -0
  44. package/lib/packlets/collections/aggregatedResultMap.js +728 -0
  45. package/lib/packlets/collections/collector.d.ts +11 -10
  46. package/lib/packlets/collections/collector.js +9 -9
  47. package/lib/packlets/collections/collectorValidator.d.ts +12 -10
  48. package/lib/packlets/collections/collectorValidator.js +4 -4
  49. package/lib/packlets/collections/converters.d.ts +18 -0
  50. package/lib/packlets/collections/converters.js +42 -0
  51. package/lib/packlets/collections/convertingCollector.d.ts +4 -4
  52. package/lib/packlets/collections/convertingCollectorValidator.d.ts +10 -7
  53. package/lib/packlets/collections/convertingCollectorValidator.js +3 -3
  54. package/lib/packlets/collections/convertingResultMap.d.ts +176 -0
  55. package/lib/packlets/collections/convertingResultMap.js +213 -0
  56. package/lib/packlets/collections/index.d.ts +4 -0
  57. package/lib/packlets/collections/index.js +4 -0
  58. package/lib/packlets/collections/keyValueConverters.d.ts +1 -4
  59. package/lib/packlets/collections/keyValueConverters.js +1 -4
  60. package/lib/packlets/collections/readOnlyConvertingResultMap.d.ts +153 -0
  61. package/lib/packlets/collections/readOnlyConvertingResultMap.js +197 -0
  62. package/lib/packlets/collections/readonlyResultMap.d.ts +7 -7
  63. package/lib/packlets/collections/resultMap.d.ts +108 -2
  64. package/lib/packlets/collections/resultMapValidator.d.ts +45 -11
  65. package/lib/packlets/collections/resultMapValidator.js +52 -7
  66. package/lib/packlets/collections/validatingCollector.d.ts +5 -5
  67. package/lib/packlets/collections/validatingConvertingCollector.d.ts +3 -3
  68. package/lib/packlets/collections/validatingConvertingResultMap.d.ts +102 -0
  69. package/lib/packlets/collections/validatingConvertingResultMap.js +83 -0
  70. package/lib/packlets/collections/validatingResultMap.d.ts +1 -1
  71. package/lib/packlets/conversion/advancedConverters.d.ts +170 -0
  72. package/lib/packlets/conversion/advancedConverters.js +258 -0
  73. package/lib/packlets/conversion/baseConverter.d.ts +39 -23
  74. package/lib/packlets/conversion/baseConverter.js +23 -16
  75. package/lib/packlets/conversion/basicConverters.d.ts +470 -0
  76. package/lib/packlets/conversion/basicConverters.js +595 -0
  77. package/lib/packlets/conversion/converter.d.ts +7 -0
  78. package/lib/packlets/conversion/converters.d.ts +2 -535
  79. package/lib/packlets/conversion/converters.js +17 -639
  80. package/lib/packlets/conversion/defaultingConverter.d.ts +20 -16
  81. package/lib/packlets/conversion/defaultingConverter.js +21 -15
  82. package/lib/packlets/logging/bootLogger.d.ts +84 -0
  83. package/lib/packlets/logging/bootLogger.js +126 -0
  84. package/lib/packlets/logging/index.d.ts +1 -0
  85. package/lib/packlets/logging/index.js +1 -0
  86. package/lib/packlets/logging/logReporter.d.ts +18 -3
  87. package/lib/packlets/logging/logReporter.js +31 -0
  88. package/lib/packlets/logging/logger.d.ts +39 -6
  89. package/lib/packlets/logging/logger.js +26 -5
  90. package/lib/packlets/validation/classes.d.ts +1 -0
  91. package/lib/packlets/validation/classes.js +3 -1
  92. package/lib/packlets/validation/compositeId.d.ts +29 -0
  93. package/lib/packlets/validation/compositeId.js +64 -0
  94. package/lib/packlets/validation/field.d.ts +1 -1
  95. package/lib/packlets/validation/field.js +1 -1
  96. package/lib/packlets/validation/genericValidator.d.ts +15 -11
  97. package/lib/packlets/validation/genericValidator.js +24 -10
  98. package/lib/packlets/validation/object.d.ts +3 -6
  99. package/lib/packlets/validation/object.js +3 -6
  100. package/lib/packlets/validation/traits.d.ts +3 -3
  101. package/lib/packlets/validation/validator.d.ts +7 -0
  102. package/lib/packlets/validation/validators.d.ts +10 -0
  103. package/lib/packlets/validation/validators.js +13 -0
  104. package/package.json +14 -14
@@ -0,0 +1,571 @@
1
+ /*
2
+ * Copyright (c) 2020 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+ import { fail, isKeyOf, succeed } from '../base';
23
+ import { Base as ValidationBase } from '../validation';
24
+ import { BaseConverter } from './baseConverter';
25
+ import { ObjectConverter } from './objectConverter';
26
+ import { StringConverter } from './stringConverter';
27
+ /**
28
+ * A converter to convert unknown to string. Values of type
29
+ * string succeed. Anything else fails.
30
+ * @public
31
+ */
32
+ export const string = new StringConverter();
33
+ /**
34
+ * Helper function to create a {@link Converter | Converter} which converts `unknown` to one of a set of supplied
35
+ * enumerated values. Anything else fails.
36
+ *
37
+ * @remarks
38
+ * Allowed enumerated values can also be supplied as context at conversion time.
39
+ * @param values - Array of allowed values.
40
+ * @returns A new {@link Converter | Converter} returning `<T>`.
41
+ * @public
42
+ */
43
+ export function enumeratedValue(values) {
44
+ return new BaseConverter((from, __self, context) => {
45
+ const v = context !== null && context !== void 0 ? context : values;
46
+ const index = v.indexOf(from);
47
+ return index >= 0 ? succeed(v[index]) : fail(`Invalid enumerated value ${JSON.stringify(from)}`);
48
+ });
49
+ }
50
+ /**
51
+ * Helper function to create a {@link Converter | Converter} which converts `unknown` to one of a set of supplied enumerated
52
+ * values, mapping any of multiple supplied values to the enumeration.
53
+ * @remarks
54
+ * Enables mapping of multiple input values to a consistent internal representation (so e.g. `'y'`, `'yes'`,
55
+ * `'true'`, `1` and `true` can all map to boolean `true`)
56
+ * @param map - An array of tuples describing the mapping. The first element of each tuple is the result
57
+ * value, the second is the set of values that map to the result. Tuples are evaluated in the order
58
+ * supplied and are not checked for duplicates.
59
+ * @param message - An optional error message.
60
+ * @returns A {@link Converter | Converter} which applies the mapping and yields `<T>` on success.
61
+ * @public
62
+ */
63
+ export function mappedEnumeratedValue(map, message) {
64
+ return new BaseConverter((from, __self, __context) => {
65
+ for (const item of map) {
66
+ if (item[1].includes(from)) {
67
+ return succeed(item[0]);
68
+ }
69
+ }
70
+ return fail(message
71
+ ? `${JSON.stringify(from)}: ${message}`
72
+ : `Cannot map '${JSON.stringify(from)}' to a supported value`);
73
+ });
74
+ }
75
+ /**
76
+ * Helper function to create a {@link Converter | Converter} which converts `unknown` to some supplied literal value. Succeeds with
77
+ * the supplied value if an identity comparison succeeds, fails otherwise.
78
+ * @param value - The value to be compared.
79
+ * @returns A {@link Converter | Converter} which returns the supplied value on success.
80
+ * @public
81
+ */
82
+ export function literal(value) {
83
+ return new BaseConverter((from, __self, __context) => {
84
+ return from === value
85
+ ? succeed(value)
86
+ : fail(`${JSON.stringify(from)}: does not match ${JSON.stringify(value)}`);
87
+ });
88
+ }
89
+ /**
90
+ * Deprecated alias for @see literal
91
+ * @param value - The value to be compared.
92
+ * @deprecated Use {@link Converters.literal} instead.
93
+ * @internal
94
+ */
95
+ // eslint-disable-next-line @rushstack/typedef-var
96
+ export const value = literal;
97
+ /**
98
+ * A {@link Converter | Converter} which converts `unknown` to a `number`.
99
+ * @remarks
100
+ * Numbers and strings with a numeric format succeed. Anything else fails.
101
+ * @public
102
+ */
103
+ export const number = new BaseConverter((from) => {
104
+ if (typeof from !== 'number') {
105
+ const num = typeof from === 'string' ? Number(from) : NaN;
106
+ return isNaN(num) ? fail(`Not a number: ${JSON.stringify(from)}`) : succeed(num);
107
+ }
108
+ return succeed(from);
109
+ });
110
+ const booleanConverter = new BaseConverter((from) => {
111
+ if (typeof from === 'boolean') {
112
+ return succeed(from);
113
+ }
114
+ else if (typeof from === 'string') {
115
+ switch (from.toLowerCase()) {
116
+ case 'true':
117
+ return succeed(true);
118
+ case 'false':
119
+ return succeed(false);
120
+ }
121
+ }
122
+ return fail(`Not a boolean: ${JSON.stringify(from)}`);
123
+ });
124
+ /**
125
+ * A {@link Converter | Converter} which converts `unknown` to `boolean`.
126
+ * @remarks
127
+ * Boolean values or the case-insensitive strings `'true'` and `'false'` succeed.
128
+ * Anything else fails.
129
+ * @public
130
+ */
131
+ export const boolean = booleanConverter;
132
+ /**
133
+ * A {@link Converter | Converter} which converts an optional `string` value. Values of type
134
+ * `string` are returned. Anything else returns {@link Success | Success} with value `undefined`.
135
+ * @public
136
+ */
137
+ export const optionalString = string.optional();
138
+ /**
139
+ * Helper function to create a {@link Converter | Converter} which converts any `string` into an
140
+ * array of `string`, by separating at a supplied delimiter.
141
+ * @remarks
142
+ * Delimiter may also be supplied as context at conversion time.
143
+ * @param delimiter - The delimiter at which to split.
144
+ * @returns A new {@link Converter | Converter} returning `string[]`.
145
+ * @public
146
+ */
147
+ export function delimitedString(delimiter, options = 'filtered') {
148
+ return new BaseConverter((from, __self, context) => {
149
+ const result = string.convert(from);
150
+ if (result.isSuccess()) {
151
+ let strings = result.value.split(context !== null && context !== void 0 ? context : delimiter);
152
+ if (options !== 'all') {
153
+ strings = strings.filter((s) => s.trim().length > 0);
154
+ }
155
+ return succeed(strings);
156
+ }
157
+ return fail(result.message);
158
+ });
159
+ }
160
+ /**
161
+ * Determines if a supplied {@link Conversion.Converter | Converter} or {@link Validation.Validator | Validator} is
162
+ * a {@link Validation.Validator | Validator}.
163
+ * @param converterOrValidator - The {@link Conversion.Converter | Converter} or {@link Validation.Validator | Validator} to be tested.
164
+ * @returns `true` if `converterOrValidator` is a {@link Validation.Validator | Validator}, `false` otherwise.
165
+ * @public
166
+ */
167
+ export function isValidator(converterOrValidator) {
168
+ return 'validate' in converterOrValidator;
169
+ }
170
+ /**
171
+ * Helper function to create a {@link Converter | Converter} from any {@link Validation.Validator}
172
+ * @param converterOrValidator - the {@link Validation.Validator} to be wrapped or {@link Converter | Converter}
173
+ * to be used directly.
174
+ * @returns A {@link Converter | Converter} which uses the supplied validator.
175
+ * @public
176
+ */
177
+ export function validated(converterOrValidator) {
178
+ if (!isValidator(converterOrValidator)) {
179
+ return converterOrValidator;
180
+ }
181
+ return new BaseConverter((from, __self, context) => {
182
+ return converterOrValidator.validate(from, context);
183
+ });
184
+ }
185
+ /**
186
+ * Helper function to create a {@link Validation.Validator | Validator} from any {@link Conversion.Converter | Converter}
187
+ * or {@link Validation.Validator | Validator}.
188
+ * @param converterOrValidator - the {@link Conversion.Converter | Converter} to be wrappped or {@link Validation.Validator | Validator} to be used directly.
189
+ * @returns A {@link Validation.Validator | Validator} which uses the supplied converter or validator.
190
+ * @public
191
+ */
192
+ export function asValidator(converterOrValidator) {
193
+ if (isValidator(converterOrValidator)) {
194
+ return converterOrValidator;
195
+ }
196
+ return new ValidationBase.GenericValidator({
197
+ validator: (from, context) => {
198
+ const result = converterOrValidator.convert(from, context);
199
+ return result.isSuccess() ? true : fail(result.message);
200
+ }
201
+ });
202
+ }
203
+ /**
204
+ * Helper function to create a {@link Converter | Converter} from a supplied {@link Conversion.ConverterFunc | ConverterFunc}.
205
+ * @param convert - the function to be wrapped
206
+ * @returns A {@link Converter | Converter} which uses the supplied function.
207
+ * @public
208
+ */
209
+ export function generic(convert) {
210
+ return new BaseConverter(convert);
211
+ }
212
+ /**
213
+ * Helper function to create a {@link Converter | Converter} from a supplied type guard function.
214
+ * @param description - a description of the thing to be validated for use in error messages
215
+ * @param guard - a {@link Validation.TypeGuardWithContext} which performs the validation.
216
+ * @returns A new {@link Converter | Converter} which validates the values using the supplied type guard
217
+ * and returns them in place.
218
+ * @public
219
+ */
220
+ export function isA(description, guard) {
221
+ return new BaseConverter((from, __self, context) => {
222
+ if (guard(from, context)) {
223
+ return succeed(from);
224
+ }
225
+ return fail(`invalid ${description} (${JSON.stringify(from)})`);
226
+ });
227
+ }
228
+ /**
229
+ * A {@link Converter | Converter} which converts an optional `number` value.
230
+ * @remarks
231
+ * Values of type `number` or numeric strings are converted and returned.
232
+ * Anything else returns {@link Success | Success} with value `undefined`.
233
+ * @public
234
+ */
235
+ export const optionalNumber = number.optional();
236
+ /**
237
+ * A {@link Converter | Converter} to convert an optional `boolean` value.
238
+ * @remarks
239
+ * Values of type `boolean` or strings that match (case-insensitive) `'true'`
240
+ * or `'false'` are converted and returned. Anything else returns {@link Success | Success}
241
+ * with value `undefined`.
242
+ * @public
243
+ */
244
+ export const optionalBoolean = booleanConverter.optional();
245
+ /**
246
+ * A helper function to create a {@link Converter | Converter} for polymorphic values.
247
+ * Returns a converter which invokes the wrapped converters in sequence, returning the
248
+ * first successful result. Returns an error if none of the supplied converters can
249
+ * convert the value.
250
+ * @remarks
251
+ * If `onError` is `ignoreErrors` (default), then errors from any of the
252
+ * converters are ignored provided that some converter succeeds. If
253
+ * onError is `failOnError`, then an error from any converter fails the entire
254
+ * conversion.
255
+ *
256
+ * @param converters - An ordered list of {@link Converter | converters} or {@link Validator | validators}
257
+ * to be considered.
258
+ * @param onError - Specifies treatment of unconvertible elements.
259
+ * @returns A new {@link Converter | Converter} which yields a value from the union of the types returned
260
+ * by the wrapped converters.
261
+ * @public
262
+ */
263
+ export function oneOf(converters, onError = 'ignoreErrors') {
264
+ return new BaseConverter((from, __self, context) => {
265
+ const errors = [];
266
+ for (const converter of converters) {
267
+ const result = converter.convert(from, context);
268
+ if (result.isSuccess() && result.value !== undefined) {
269
+ return result;
270
+ }
271
+ if (result.isFailure()) {
272
+ if (onError === 'failOnError') {
273
+ return result;
274
+ }
275
+ errors.push(result.message);
276
+ }
277
+ }
278
+ return fail(`No matching converter for ${JSON.stringify(from)}: ${errors.join('\n')}`);
279
+ });
280
+ }
281
+ /**
282
+ * A helper function to create a {@link Converter | Converter} which converts `unknown` to an array of `<T>`.
283
+ * @remarks
284
+ * If `onError` is `'failOnError'` (default), then the entire conversion fails if any element cannot
285
+ * be converted. If `onError` is `'ignoreErrors'`, then failing elements are silently ignored.
286
+ * @param converter - {@link Converter | Converter} or {@link Validator | Validator} used to convert each
287
+ * item in the array.
288
+ * @param onError - Specifies treatment of unconvertible elements.
289
+ * @returns A {@link Converter | Converter} which returns an array of `<T>`.
290
+ * @public
291
+ */
292
+ export function arrayOf(converter, onError = 'failOnError') {
293
+ return new BaseConverter((from, __self, context) => {
294
+ if (!Array.isArray(from)) {
295
+ return fail(`Not an array: ${JSON.stringify(from)}`);
296
+ }
297
+ const successes = [];
298
+ const errors = [];
299
+ for (const item of from) {
300
+ const result = converter.convert(item, context);
301
+ if (result.isSuccess() && result.value !== undefined) {
302
+ successes.push(result.value);
303
+ }
304
+ else if (result.isFailure()) {
305
+ errors.push(result.message);
306
+ }
307
+ }
308
+ return errors.length === 0 || onError === 'ignoreErrors' ? succeed(successes) : fail(errors.join('\n'));
309
+ });
310
+ }
311
+ /**
312
+ * {@link Converter | Converter} to convert an `unknown` to an array of `string`.
313
+ * @remarks
314
+ * Returns {@link Success | Success} with the the supplied value if it as an array
315
+ * of strings, returns {@link Failure | Failure} with an error message otherwise.
316
+ * @public
317
+ */
318
+ export const stringArray = arrayOf(string);
319
+ /**
320
+ * {@link Converter | Converter} to convert an `unknown` to an array of `number`.
321
+ * @remarks
322
+ * Returns {@link Success | Success} with the the supplied value if it as an array
323
+ * of numbers, returns {@link Failure | Failure} with an error message otherwise.
324
+ * @public
325
+ */
326
+ export const numberArray = arrayOf(number);
327
+ /**
328
+ * Concrete implementation of {@link Converters.(recordOf:1) | Converters.recordOf(Converter<T, TC>)},
329
+ * {@link Converters.(recordOf:2) | Converters.recordOf(Converter<T, TC>, 'fail' or 'ignore')}, and
330
+ * {@link Converters.recordOf | Converters.recordOf(Converter<T, TC>, KeyedConverterOptions)}.
331
+ * @internal
332
+ */
333
+ export function recordOf(converter, option = 'fail') {
334
+ const options = typeof option === 'string' ? { onError: option } : Object.assign({ onError: 'fail' }, option);
335
+ return new BaseConverter((from, __self, context) => {
336
+ var _a, _b;
337
+ if (typeof from !== 'object' || from === null || Array.isArray(from)) {
338
+ return fail(`Not a string-keyed object: ${JSON.stringify(from)}`);
339
+ }
340
+ const record = {};
341
+ const errors = [];
342
+ for (const key in from) {
343
+ if (isKeyOf(key, from)) {
344
+ const writeKeyResult = (_b = (_a = options.keyConverter) === null || _a === void 0 ? void 0 : _a.convert(key, context)) !== null && _b !== void 0 ? _b : succeed(key);
345
+ writeKeyResult
346
+ .onSuccess((writeKey) => {
347
+ return converter.convert(from[key], context).onSuccess((value) => {
348
+ record[writeKey] = value;
349
+ return succeed(true);
350
+ });
351
+ })
352
+ .onFailure((message) => {
353
+ errors.push(message);
354
+ return fail(message);
355
+ });
356
+ }
357
+ }
358
+ return errors.length === 0 || options.onError === 'ignore' ? succeed(record) : fail(errors.join('\n'));
359
+ });
360
+ }
361
+ /**
362
+ * Concrete implementation of {@link Converters.(mapOf:1) | Converters.mapOf(Converter<T, TC>)},
363
+ * {@link Converters.(mapOf:2) | Converters.mapOf(Converter<T, TC>, 'fail' or 'ignore')}, and
364
+ * {@link Converters.mapOf | Converters.mapOf(Converter<T, TC>, KeyedConverterOptions)}.
365
+ * @internal
366
+ */
367
+ export function mapOf(converter, option = 'fail') {
368
+ const options = typeof option === 'string' ? { onError: option } : Object.assign({ onError: 'fail' }, option);
369
+ return new BaseConverter((from, __self, context) => {
370
+ var _a, _b;
371
+ if (typeof from !== 'object' || from === null || Array.isArray(from)) {
372
+ return fail(`Not a string-keyed object: ${JSON.stringify(from)}`);
373
+ }
374
+ const map = new Map();
375
+ const errors = [];
376
+ for (const key in from) {
377
+ if (isKeyOf(key, from)) {
378
+ const writeKeyResult = (_b = (_a = options.keyConverter) === null || _a === void 0 ? void 0 : _a.convert(key, context)) !== null && _b !== void 0 ? _b : succeed(key);
379
+ writeKeyResult
380
+ .onSuccess((writeKey) => {
381
+ return converter.convert(from[key], context).onSuccess((value) => {
382
+ map.set(writeKey, value);
383
+ return succeed(true);
384
+ });
385
+ })
386
+ .onFailure((message) => {
387
+ errors.push(message);
388
+ return fail(message);
389
+ });
390
+ }
391
+ }
392
+ return errors.length === 0 || options.onError === 'ignore' ? succeed(map) : fail(errors.join('\n'));
393
+ });
394
+ }
395
+ /**
396
+ * Helper function to create a {@link Converter | Converter} which validates that a supplied value is
397
+ * of a type validated by a supplied validator function and returns it.
398
+ * @remarks
399
+ * If `validator` succeeds, this {@link Converter | Converter} returns {@link Success | Success} with the supplied
400
+ * value of `from` coerced to type `<T>`. Returns a {@link Failure | Failure} with additional
401
+ * information otherwise.
402
+ * @param validator - A validator function to determine if the converted value is valid.
403
+ * @param description - A description of the validated type for use in error messages.
404
+ * @returns A new {@link Converter | Converter<T, TC>} which applies the supplied validation.
405
+ * @public
406
+ */
407
+ export function validateWith(validator, description) {
408
+ return new BaseConverter((from, __self, __context) => {
409
+ if (validator(from)) {
410
+ return succeed(from);
411
+ }
412
+ return fail(`${JSON.stringify(from)}: invalid ${description !== null && description !== void 0 ? description : 'value'}`);
413
+ });
414
+ }
415
+ /**
416
+ * A helper function to create a {@link Converter | Converter} which extracts and converts an element from an array.
417
+ * @remarks
418
+ * The returned {@link Converter | Converter} returns {@link Success | Success} with the converted value if the element exists
419
+ * in the supplied array and can be converted. Returns {@link Failure | Failure} with an error message otherwise.
420
+ * @param index - The index of the element to be extracted.
421
+ * @param converter - A {@link Converter | Converter} or {@link Validator | Validator} for the extracted element.
422
+ * @returns A {@link Converter | Converter<T, TC>} which extracts the specified element from an array.
423
+ * @public
424
+ */
425
+ export function element(index, converter) {
426
+ return new BaseConverter((from, __self, context) => {
427
+ if (index < 0) {
428
+ return fail(`${index}: cannot convert for a negative element index`);
429
+ }
430
+ else if (!Array.isArray(from)) {
431
+ return fail('element converter: source is not an array');
432
+ }
433
+ else if (index >= from.length) {
434
+ return fail(`${index}: element converter index out of range (0..${from.length - 1})`);
435
+ }
436
+ return converter.convert(from[index], context);
437
+ });
438
+ }
439
+ /**
440
+ * A helper function to create a {@link Converter | Converter} which extracts and converts an optional element from an array.
441
+ * @remarks
442
+ * The resulting {@link Converter | Converter} returns {@link Success | Success} with the converted value if the element exists
443
+ * in the supplied array and can be converted. Returns {@link Success | Success} with value `undefined` if the parameter
444
+ * is an array but the index is out of range. Returns {@link Failure | Failure} with a message if the supplied parameter
445
+ * is not an array, if the requested index is negative, or if the element cannot be converted.
446
+ * @param index - The index of the element to be extracted.
447
+ * @param converter - A {@link Converter | Converter} or {@link Validator | Validator} used for the extracted element.
448
+ * @returns A {@link Converter | Converter<T, TC>} which extracts the specified element from an array.
449
+ * @public
450
+ */
451
+ export function optionalElement(index, converter) {
452
+ return new BaseConverter((from, __self, context) => {
453
+ if (index < 0) {
454
+ return fail(`${index}: cannot convert for a negative element index`);
455
+ }
456
+ else if (!Array.isArray(from)) {
457
+ return fail('element converter: source is not an array');
458
+ }
459
+ else if (index >= from.length) {
460
+ return succeed(undefined);
461
+ }
462
+ return converter.convert(from[index], context);
463
+ });
464
+ }
465
+ /**
466
+ * A helper function to create a {@link Converter | Converter} which extracts and convert a property specified
467
+ * by name from an object.
468
+ * @remarks
469
+ * The resulting {@link Converter | Converter} returns {@link Success | Success} with the converted value of the corresponding
470
+ * object property if the field exists and can be converted. Returns {@link Failure | Failure} with an error message
471
+ * otherwise.
472
+ * @param name - The name of the field to be extracted.
473
+ * @param converter - {@link Converter | Converter} or {@link Validator | Validator} to use for the extracted
474
+ * field.
475
+ * @public
476
+ */
477
+ export function field(name, converter) {
478
+ return new BaseConverter((from, __self, context) => {
479
+ if (typeof from === 'object' && !Array.isArray(from) && from !== null) {
480
+ if (isKeyOf(name, from)) {
481
+ return converter.convert(from[name], context).onFailure((message) => {
482
+ return fail(`Field ${name}: ${message}`);
483
+ });
484
+ }
485
+ return fail(`Field ${name} not found in: ${JSON.stringify(from)}`);
486
+ }
487
+ return fail(`Cannot convert field "${name}" from non-object ${JSON.stringify(from)}`);
488
+ });
489
+ }
490
+ /**
491
+ * A helper function to create a {@link Converter | Converter} which extracts and convert a property specified
492
+ * by name from an object.
493
+ * @remarks
494
+ * The resulting {@link Converter | Converter} returns {@link Success | Success} with the converted value of
495
+ * the corresponding object property if the field exists and can be converted. Returns {@link Success | Success}
496
+ * with `undefined` if the supplied parameter is an object but the named field is not present.
497
+ * Returns {@link Failure | Failure} with an error message otherwise.
498
+ * @param name - The name of the field to be extracted.
499
+ * @param converter - {@link Converter | Converter} or {@link Validator | Validator} to use for the extracted field.
500
+ * @public
501
+ */
502
+ export function optionalField(name, converter) {
503
+ return new BaseConverter((from, __self, context) => {
504
+ if (typeof from === 'object' && !Array.isArray(from) && from !== null) {
505
+ if (isKeyOf(name, from)) {
506
+ const result = converter.convert(from[name], context).onFailure((message) => {
507
+ return fail(`${name}: ${message}`);
508
+ });
509
+ // if conversion was successful or input was undefined we
510
+ // succeed with 'undefined', but we propagate actual
511
+ // failures.
512
+ if (result.isSuccess() || from[name] !== undefined) {
513
+ return result;
514
+ }
515
+ }
516
+ return succeed(undefined);
517
+ }
518
+ return fail(`Cannot convert field "${name}" from non-object ${JSON.stringify(from)}`);
519
+ }, undefined, { isOptional: true });
520
+ }
521
+ /**
522
+ * Concrete implementation of {@link Converters.(object:1) | Converters.object(fields, options)}
523
+ * and {@link Converters.(object:2) | Converters.objects(fields, optionalKeys)}.
524
+ * @internal
525
+ */
526
+ export function object(properties, options) {
527
+ return new ObjectConverter(properties, options);
528
+ }
529
+ /**
530
+ * Concrete implementation for {@link Converters.strictObject | Converters.strictObject(fields, options)}
531
+ * and {@link Converters.strictObject | Converters.strictObject(fields, optional)}.
532
+ * @internal
533
+ */
534
+ export function strictObject(properties, opt) {
535
+ /* c8 ignore next 2 */
536
+ const options = opt && Array.isArray(opt) ? { strict: true, optionalFields: opt } : Object.assign(Object.assign({}, (opt !== null && opt !== void 0 ? opt : {})), { strict: true });
537
+ return new ObjectConverter(properties, options);
538
+ }
539
+ /**
540
+ * Helper to create a {@link Converter | Converter} which converts a discriminated object without changing shape.
541
+ * @remarks
542
+ * Takes the name of the discriminator property and a
543
+ * {@link Converters.DiscriminatedObjectConverters | string-keyed Record of converters and validators}. During conversion,
544
+ * the resulting {@link Converter | Converter} invokes the converter from `converters` that corresponds to the value of
545
+ * the discriminator property in the source object.
546
+ *
547
+ * If the source is not an object, the discriminator property is missing, or the discriminator has
548
+ * a value not present in the converters, conversion fails and returns {@link Failure | Failure} with more information.
549
+ * @param discriminatorProp - Name of the property used to discriminate types.
550
+ * @param converters - {@link Converters.DiscriminatedObjectConverters | String-keyed record of converters and validators}
551
+ * to invoke, where each key corresponds to a value of the discriminator property.
552
+ * @returns A {@link Converter | Converter} which converts the corresponding discriminated object.
553
+ * @public
554
+ */
555
+ export function discriminatedObject(discriminatorProp, converters) {
556
+ return new BaseConverter((from) => {
557
+ if (typeof from !== 'object' || Array.isArray(from) || from === null) {
558
+ return fail(`Not a discriminated object: "${JSON.stringify(from)}"`);
559
+ }
560
+ if (!isKeyOf(discriminatorProp, from) || !from[discriminatorProp]) {
561
+ return fail(`Discriminator property ${discriminatorProp} not present in "${JSON.stringify(from)}"`);
562
+ }
563
+ const discriminatorValue = from[discriminatorProp];
564
+ const converter = converters[discriminatorValue];
565
+ if (converter === undefined) {
566
+ return fail(`No converter for discriminator ${discriminatorProp}="${discriminatorValue}"`);
567
+ }
568
+ return converter.convert(from);
569
+ });
570
+ }
571
+ //# sourceMappingURL=basicConverters.js.map