@fgv/ts-utils 5.0.1-9 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/index.js +32 -0
  2. package/dist/packlets/base/brand.js +23 -0
  3. package/dist/packlets/base/index.js +28 -0
  4. package/dist/packlets/base/mapResults.js +217 -0
  5. package/dist/packlets/base/messageAggregator.js +110 -0
  6. package/dist/packlets/base/normalize.js +132 -0
  7. package/dist/packlets/base/result.js +611 -0
  8. package/dist/packlets/base/utils.js +185 -0
  9. package/dist/packlets/collections/collectible.js +82 -0
  10. package/dist/packlets/collections/collector.js +189 -0
  11. package/dist/packlets/collections/collectorValidator.js +94 -0
  12. package/dist/packlets/collections/common.js +23 -0
  13. package/dist/packlets/collections/convertingCollector.js +118 -0
  14. package/dist/packlets/collections/convertingCollectorValidator.js +95 -0
  15. package/dist/packlets/collections/index.js +37 -0
  16. package/dist/packlets/collections/keyValueConverters.js +100 -0
  17. package/dist/packlets/collections/readonlyResultMap.js +23 -0
  18. package/dist/packlets/collections/resultMap.js +214 -0
  19. package/dist/packlets/collections/resultMapValidator.js +122 -0
  20. package/dist/packlets/collections/utils.js +31 -0
  21. package/dist/packlets/collections/validatingCollector.js +63 -0
  22. package/dist/packlets/collections/validatingConvertingCollector.js +64 -0
  23. package/dist/packlets/collections/validatingResultMap.js +57 -0
  24. package/dist/packlets/conversion/baseConverter.js +242 -0
  25. package/dist/packlets/conversion/converter.js +2 -0
  26. package/dist/packlets/conversion/converters.js +637 -0
  27. package/dist/packlets/conversion/defaultingConverter.js +149 -0
  28. package/dist/packlets/conversion/index.js +29 -0
  29. package/dist/packlets/conversion/objectConverter.js +141 -0
  30. package/dist/packlets/conversion/stringConverter.js +93 -0
  31. package/dist/packlets/hash/crcNormalizer.js +114 -0
  32. package/dist/packlets/hash/hashingNormalizer.js +92 -0
  33. package/dist/packlets/hash/index.js +24 -0
  34. package/dist/packlets/logging/index.js +24 -0
  35. package/dist/packlets/logging/logReporter.js +114 -0
  36. package/dist/packlets/logging/logger.js +258 -0
  37. package/dist/packlets/validation/array.js +64 -0
  38. package/dist/packlets/validation/boolean.js +52 -0
  39. package/dist/packlets/validation/classes.js +31 -0
  40. package/dist/packlets/validation/common.js +23 -0
  41. package/dist/packlets/validation/field.js +67 -0
  42. package/dist/packlets/validation/genericValidator.js +160 -0
  43. package/dist/packlets/validation/index.js +29 -0
  44. package/dist/packlets/validation/number.js +52 -0
  45. package/dist/packlets/validation/object.js +134 -0
  46. package/dist/packlets/validation/oneOf.js +58 -0
  47. package/dist/packlets/validation/string.js +52 -0
  48. package/dist/packlets/validation/traits.js +56 -0
  49. package/dist/packlets/validation/typeGuard.js +59 -0
  50. package/dist/packlets/validation/validator.js +23 -0
  51. package/dist/packlets/validation/validatorBase.js +37 -0
  52. package/dist/packlets/validation/validators.js +191 -0
  53. package/dist/test/helpers/jest/helpers/fsHelpers.js +139 -0
  54. package/dist/test/helpers/jest/helpers/index.js +2 -0
  55. package/dist/test/helpers/jest/index.js +17 -0
  56. package/dist/test/helpers/jest/matchers/index.js +14 -0
  57. package/dist/test/helpers/jest/matchers/toFail/index.js +23 -0
  58. package/dist/test/helpers/jest/matchers/toFail/predicate.js +5 -0
  59. package/dist/test/helpers/jest/matchers/toFailTest/index.js +28 -0
  60. package/dist/test/helpers/jest/matchers/toFailTest/predicate.js +8 -0
  61. package/dist/test/helpers/jest/matchers/toFailTestAndMatchSnapshot/index.js +24 -0
  62. package/dist/test/helpers/jest/matchers/toFailTestAndMatchSnapshot/predicate.js +11 -0
  63. package/dist/test/helpers/jest/matchers/toFailTestWith/index.js +29 -0
  64. package/dist/test/helpers/jest/matchers/toFailTestWith/predicate.js +26 -0
  65. package/dist/test/helpers/jest/matchers/toFailWith/index.js +27 -0
  66. package/dist/test/helpers/jest/matchers/toFailWith/predicate.js +16 -0
  67. package/dist/test/helpers/jest/matchers/toFailWithDetail/index.js +27 -0
  68. package/dist/test/helpers/jest/matchers/toFailWithDetail/predicate.js +22 -0
  69. package/dist/test/helpers/jest/matchers/toSucceed/index.js +23 -0
  70. package/dist/test/helpers/jest/matchers/toSucceed/predicate.js +5 -0
  71. package/dist/test/helpers/jest/matchers/toSucceedAndMatchInlineSnapshot/index.js +24 -0
  72. package/dist/test/helpers/jest/matchers/toSucceedAndMatchSnapshot/index.js +24 -0
  73. package/dist/test/helpers/jest/matchers/toSucceedAndSatisfy/index.js +53 -0
  74. package/dist/test/helpers/jest/matchers/toSucceedAndSatisfy/predicate.js +17 -0
  75. package/dist/test/helpers/jest/matchers/toSucceedWith/index.js +27 -0
  76. package/dist/test/helpers/jest/matchers/toSucceedWith/predicate.js +12 -0
  77. package/dist/test/helpers/jest/matchers/toSucceedWithDetail/index.js +27 -0
  78. package/dist/test/helpers/jest/matchers/toSucceedWithDetail/predicate.js +17 -0
  79. package/dist/test/helpers/jest/resolvers/cli.js +10 -0
  80. package/dist/test/helpers/jest/resolvers/ide.js +10 -0
  81. package/dist/test/helpers/jest/ts-utils.js +2 -0
  82. package/dist/test/helpers/jest/types/index.js +3 -0
  83. package/dist/test/helpers/jest/utils/matcherHelpers.js +47 -0
  84. package/dist/test/helpers/jest/utils/snapshotResolver.js +11 -0
  85. package/dist/test/unit/collections/helpers.js +106 -0
  86. package/dist/test/unit/hashTextEncodeCompat.js +23 -0
  87. package/dist/tsdoc-metadata.json +1 -1
  88. package/lib/packlets/hash/crcNormalizer.js +42 -2
  89. package/package.json +12 -2
@@ -0,0 +1,637 @@
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 { BaseConverter } from './baseConverter';
24
+ import { ObjectConverter } from './objectConverter';
25
+ import { StringConverter } from './stringConverter';
26
+ /**
27
+ * A converter to convert unknown to string. Values of type
28
+ * string succeed. Anything else fails.
29
+ * @public
30
+ */
31
+ export const string = new StringConverter();
32
+ /**
33
+ * Helper function to create a {@link Converter | Converter} which converts `unknown` to one of a set of supplied
34
+ * enumerated values. Anything else fails.
35
+ *
36
+ * @remarks
37
+ * Allowed enumerated values can also be supplied as context at conversion time.
38
+ * @param values - Array of allowed values.
39
+ * @returns A new {@link Converter | Converter} returning `<T>`.
40
+ * @public
41
+ */
42
+ export function enumeratedValue(values) {
43
+ return new BaseConverter((from, __self, context) => {
44
+ const v = context !== null && context !== void 0 ? context : values;
45
+ const index = v.indexOf(from);
46
+ return index >= 0 ? succeed(v[index]) : fail(`Invalid enumerated value ${JSON.stringify(from)}`);
47
+ });
48
+ }
49
+ /**
50
+ * Helper function to create a {@link Converter | Converter} which converts `unknown` to one of a set of supplied enumerated
51
+ * values, mapping any of multiple supplied values to the enumeration.
52
+ * @remarks
53
+ * Enables mapping of multiple input values to a consistent internal representation (so e.g. `'y'`, `'yes'`,
54
+ * `'true'`, `1` and `true` can all map to boolean `true`)
55
+ * @param map - An array of tuples describing the mapping. The first element of each tuple is the result
56
+ * value, the second is the set of values that map to the result. Tuples are evaluated in the order
57
+ * supplied and are not checked for duplicates.
58
+ * @param message - An optional error message.
59
+ * @returns A {@link Converter | Converter} which applies the mapping and yields `<T>` on success.
60
+ * @public
61
+ */
62
+ export function mappedEnumeratedValue(map, message) {
63
+ return new BaseConverter((from, __self, __context) => {
64
+ for (const item of map) {
65
+ if (item[1].includes(from)) {
66
+ return succeed(item[0]);
67
+ }
68
+ }
69
+ return fail(message
70
+ ? `${JSON.stringify(from)}: ${message}`
71
+ : `Cannot map '${JSON.stringify(from)}' to a supported value`);
72
+ });
73
+ }
74
+ /**
75
+ * Helper function to create a {@link Converter | Converter} which converts `unknown` to some supplied literal value. Succeeds with
76
+ * the supplied value if an identity comparison succeeds, fails otherwise.
77
+ * @param value - The value to be compared.
78
+ * @returns A {@link Converter | Converter} which returns the supplied value on success.
79
+ * @public
80
+ */
81
+ export function literal(value) {
82
+ return new BaseConverter((from, __self, __context) => {
83
+ return from === value
84
+ ? succeed(value)
85
+ : fail(`${JSON.stringify(from)}: does not match ${JSON.stringify(value)}`);
86
+ });
87
+ }
88
+ /**
89
+ * Deprecated alias for @see literal
90
+ * @param value - The value to be compared.
91
+ * @deprecated Use {@link Converters.literal} instead.
92
+ * @internal
93
+ */
94
+ // eslint-disable-next-line @rushstack/typedef-var
95
+ export const value = literal;
96
+ /**
97
+ * A {@link Converter | Converter} which converts `unknown` to a `number`.
98
+ * @remarks
99
+ * Numbers and strings with a numeric format succeed. Anything else fails.
100
+ * @public
101
+ */
102
+ export const number = new BaseConverter((from) => {
103
+ if (typeof from !== 'number') {
104
+ const num = typeof from === 'string' ? Number(from) : NaN;
105
+ return isNaN(num) ? fail(`Not a number: ${JSON.stringify(from)}`) : succeed(num);
106
+ }
107
+ return succeed(from);
108
+ });
109
+ /**
110
+ * A {@link Converter | Converter} which converts `unknown` to `boolean`.
111
+ * @remarks
112
+ * Boolean values or the case-insensitive strings `'true'` and `'false'` succeed.
113
+ * Anything else fails.
114
+ * @public
115
+ */
116
+ export const boolean = new BaseConverter((from) => {
117
+ if (typeof from === 'boolean') {
118
+ return succeed(from);
119
+ }
120
+ else if (typeof from === 'string') {
121
+ switch (from.toLowerCase()) {
122
+ case 'true':
123
+ return succeed(true);
124
+ case 'false':
125
+ return succeed(false);
126
+ }
127
+ }
128
+ return fail(`Not a boolean: ${JSON.stringify(from)}`);
129
+ });
130
+ /**
131
+ * A {@link Converter | Converter} which converts an optional `string` value. Values of type
132
+ * `string` are returned. Anything else returns {@link Success | Success} with value `undefined`.
133
+ * @public
134
+ */
135
+ export const optionalString = string.optional();
136
+ /**
137
+ * Helper function to create a {@link Converter | Converter} which converts any `string` into an
138
+ * array of `string`, by separating at a supplied delimiter.
139
+ * @remarks
140
+ * Delimiter may also be supplied as context at conversion time.
141
+ * @param delimiter - The delimiter at which to split.
142
+ * @returns A new {@link Converter | Converter} returning `string[]`.
143
+ * @public
144
+ */
145
+ export function delimitedString(delimiter, options = 'filtered') {
146
+ return new BaseConverter((from, __self, context) => {
147
+ const result = string.convert(from);
148
+ if (result.isSuccess()) {
149
+ let strings = result.value.split(context !== null && context !== void 0 ? context : delimiter);
150
+ if (options !== 'all') {
151
+ strings = strings.filter((s) => s.trim().length > 0);
152
+ }
153
+ return succeed(strings);
154
+ }
155
+ return fail(result.message);
156
+ });
157
+ }
158
+ /**
159
+ * Helper function to create a {@link Converter | Converter} from any {@link Validation.Validator}
160
+ * @param validator - the validator to be wrapped
161
+ * @returns A {@link Converter | Converter} which uses the supplied validator.
162
+ * @public
163
+ */
164
+ export function validated(validator) {
165
+ return new BaseConverter((from, __self, context) => {
166
+ return validator.validate(from, context);
167
+ });
168
+ }
169
+ /**
170
+ * Helper function to create a {@link Converter | Converter} from a supplied {@link Conversion.ConverterFunc | ConverterFunc}.
171
+ * @param convert - the function to be wrapped
172
+ * @returns A {@link Converter | Converter} which uses the supplied function.
173
+ * @public
174
+ */
175
+ export function generic(convert) {
176
+ return new BaseConverter(convert);
177
+ }
178
+ /**
179
+ * Helper function to create a {@link Converter | Converter} from a supplied type guard function.
180
+ * @param description - a description of the thing to be validated for use in error messages
181
+ * @param guard - a {@link Validation.TypeGuardWithContext} which performs the validation.
182
+ * @returns A new {@link Converter | Converter} which validates the values using the supplied type guard
183
+ * and returns them in place.
184
+ * @public
185
+ */
186
+ export function isA(description, guard) {
187
+ return new BaseConverter((from, __self, context) => {
188
+ if (guard(from, context)) {
189
+ return succeed(from);
190
+ }
191
+ return fail(`invalid ${description} (${JSON.stringify(from)})`);
192
+ });
193
+ }
194
+ /**
195
+ * A {@link Converter | Converter} which converts an optional `number` value.
196
+ * @remarks
197
+ * Values of type `number` or numeric strings are converted and returned.
198
+ * Anything else returns {@link Success | Success} with value `undefined`.
199
+ * @public
200
+ */
201
+ export const optionalNumber = number.optional();
202
+ /**
203
+ * A {@link Converter | Converter} to convert an optional `boolean` value.
204
+ * @remarks
205
+ * Values of type `boolean` or strings that match (case-insensitive) `'true'`
206
+ * or `'false'` are converted and returned. Anything else returns {@link Success | Success}
207
+ * with value `undefined`.
208
+ * @public
209
+ */
210
+ export const optionalBoolean = boolean.optional();
211
+ /**
212
+ * A helper function to create a {@link Converter | Converter} for polymorphic values.
213
+ * Returns a converter which invokes the wrapped converters in sequence, returning the
214
+ * first successful result. Returns an error if none of the supplied converters can
215
+ * convert the value.
216
+ * @remarks
217
+ * If `onError` is `ignoreErrors` (default), then errors from any of the
218
+ * converters are ignored provided that some converter succeeds. If
219
+ * onError is `failOnError`, then an error from any converter fails the entire
220
+ * conversion.
221
+ *
222
+ * @param converters - An ordered list of {@link Converter | converters} or {@link Validator | validators}
223
+ * to be considered.
224
+ * @param onError - Specifies treatment of unconvertible elements.
225
+ * @returns A new {@link Converter | Converter} which yields a value from the union of the types returned
226
+ * by the wrapped converters.
227
+ * @public
228
+ */
229
+ export function oneOf(converters, onError = 'ignoreErrors') {
230
+ return new BaseConverter((from, __self, context) => {
231
+ const errors = [];
232
+ for (const converter of converters) {
233
+ const result = converter.convert(from, context);
234
+ if (result.isSuccess() && result.value !== undefined) {
235
+ return result;
236
+ }
237
+ if (result.isFailure()) {
238
+ if (onError === 'failOnError') {
239
+ return result;
240
+ }
241
+ errors.push(result.message);
242
+ }
243
+ }
244
+ return fail(`No matching converter for ${JSON.stringify(from)}: ${errors.join('\n')}`);
245
+ });
246
+ }
247
+ /**
248
+ * A helper function to create a {@link Converter | Converter} which converts `unknown` to an array of `<T>`.
249
+ * @remarks
250
+ * If `onError` is `'failOnError'` (default), then the entire conversion fails if any element cannot
251
+ * be converted. If `onError` is `'ignoreErrors'`, then failing elements are silently ignored.
252
+ * @param converter - {@link Converter | Converter} or {@link Validator | Validator} used to convert each
253
+ * item in the array.
254
+ * @param ignoreErrors - Specifies treatment of unconvertible elements.
255
+ * @returns A {@link Converter | Converter} which returns an array of `<T>`.
256
+ * @public
257
+ */
258
+ export function arrayOf(converter, onError = 'failOnError') {
259
+ return new BaseConverter((from, __self, context) => {
260
+ if (!Array.isArray(from)) {
261
+ return fail(`Not an array: ${JSON.stringify(from)}`);
262
+ }
263
+ const successes = [];
264
+ const errors = [];
265
+ for (const item of from) {
266
+ const result = converter.convert(item, context);
267
+ if (result.isSuccess() && result.value !== undefined) {
268
+ successes.push(result.value);
269
+ }
270
+ else if (result.isFailure()) {
271
+ errors.push(result.message);
272
+ }
273
+ }
274
+ return errors.length === 0 || onError === 'ignoreErrors' ? succeed(successes) : fail(errors.join('\n'));
275
+ });
276
+ }
277
+ /**
278
+ * {@link Converter | Converter} to convert an `unknown` to an array of `string`.
279
+ * @remarks
280
+ * Returns {@link Success | Success} with the the supplied value if it as an array
281
+ * of strings, returns {@link Failure | Failure} with an error message otherwise.
282
+ * @public
283
+ */
284
+ export const stringArray = arrayOf(string);
285
+ /**
286
+ * {@link Converter | Converter} to convert an `unknown` to an array of `number`.
287
+ * @remarks
288
+ * Returns {@link Success | Success} with the the supplied value if it as an array
289
+ * of numbers, returns {@link Failure | Failure} with an error message otherwise.
290
+ * @public
291
+ */
292
+ export const numberArray = arrayOf(number);
293
+ /**
294
+ * Concrete implementation of {@link Converters.(recordOf:1) | Converters.recordOf(Converter<T, TC>)},
295
+ * {@link Converters.(recordOf:2) | Converters.recordOf(Converter<T, TC>, 'fail' or 'ignore')}, and
296
+ * {@link Converters.(recordOf:3) | Converters.recordOf(Converter<T, TC>, KeyedConverterOptions)}.
297
+ * @internal
298
+ */
299
+ export function recordOf(converter, option = 'fail') {
300
+ const options = typeof option === 'string' ? { onError: option } : Object.assign({ onError: 'fail' }, option);
301
+ return new BaseConverter((from, __self, context) => {
302
+ var _a, _b;
303
+ if (typeof from !== 'object' || from === null || Array.isArray(from)) {
304
+ return fail(`Not a string-keyed object: ${JSON.stringify(from)}`);
305
+ }
306
+ const record = {};
307
+ const errors = [];
308
+ for (const key in from) {
309
+ if (isKeyOf(key, from)) {
310
+ const writeKeyResult = (_b = (_a = options.keyConverter) === null || _a === void 0 ? void 0 : _a.convert(key, context)) !== null && _b !== void 0 ? _b : succeed(key);
311
+ writeKeyResult
312
+ .onSuccess((writeKey) => {
313
+ return converter.convert(from[key], context).onSuccess((value) => {
314
+ record[writeKey] = value;
315
+ return succeed(true);
316
+ });
317
+ })
318
+ .onFailure((message) => {
319
+ errors.push(message);
320
+ return fail(message);
321
+ });
322
+ }
323
+ }
324
+ return errors.length === 0 || options.onError === 'ignore' ? succeed(record) : fail(errors.join('\n'));
325
+ });
326
+ }
327
+ /**
328
+ * Concrete implementation of {@link Converters.(mapOf:1) | Converters.mapOf(Converter<T, TC>)},
329
+ * {@link Converters.(mapOf:2) | Converters.mapOf(Converter<T, TC>, 'fail' or 'ignore')}, and
330
+ * {@link Converters.(mapOf:3) | Converters.mapOf(Converter<T, TC>, KeyedConverterOptions)}.
331
+ * @internal
332
+ */
333
+ export function mapOf(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 map = new Map();
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
+ map.set(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(map) : fail(errors.join('\n'));
359
+ });
360
+ }
361
+ /**
362
+ * Helper function to create a {@link Converter | Converter} which validates that a supplied value is
363
+ * of a type validated by a supplied validator function and returns it.
364
+ * @remarks
365
+ * If `validator` succeeds, this {@link Converter | Converter} returns {@link Success | Success} with the supplied
366
+ * value of `from` coerced to type `<T>`. Returns a {@link Failure | Failure} with additional
367
+ * information otherwise.
368
+ * @param validator - A validator function to determine if the converted value is valid.
369
+ * @param description - A description of the validated type for use in error messages.
370
+ * @returns A new {@link Converter | Converter<T, TC>} which applies the supplied validation.
371
+ * @public
372
+ */
373
+ export function validateWith(validator, description) {
374
+ return new BaseConverter((from, __self, __context) => {
375
+ if (validator(from)) {
376
+ return succeed(from);
377
+ }
378
+ return fail(`${JSON.stringify(from)}: invalid ${description !== null && description !== void 0 ? description : 'value'}`);
379
+ });
380
+ }
381
+ /**
382
+ * A helper function to create a {@link Converter | Converter} which extracts and converts an element from an array.
383
+ * @remarks
384
+ * The returned {@link Converter | Converter} returns {@link Success | Success} with the converted value if the element exists
385
+ * in the supplied array and can be converted. Returns {@link Failure | Failure} with an error message otherwise.
386
+ * @param index - The index of the element to be extracted.
387
+ * @param converter - A {@link Converter | Converter} or {@link Validator | Validator} for the extracted element.
388
+ * @returns A {@link Converter | Converter<T, TC>} which extracts the specified element from an array.
389
+ * @public
390
+ */
391
+ export function element(index, converter) {
392
+ return new BaseConverter((from, __self, context) => {
393
+ if (index < 0) {
394
+ return fail(`${index}: cannot convert for a negative element index`);
395
+ }
396
+ else if (!Array.isArray(from)) {
397
+ return fail('element converter: source is not an array');
398
+ }
399
+ else if (index >= from.length) {
400
+ return fail(`${index}: element converter index out of range (0..${from.length - 1})`);
401
+ }
402
+ return converter.convert(from[index], context);
403
+ });
404
+ }
405
+ /**
406
+ * A helper function to create a {@link Converter | Converter} which extracts and converts an optional element from an array.
407
+ * @remarks
408
+ * The resulting {@link Converter | Converter} returns {@link Success | Success} with the converted value if the element exists
409
+ * in the supplied array and can be converted. Returns {@link Success | Success} with value `undefined` if the parameter
410
+ * is an array but the index is out of range. Returns {@link Failure | Failure} with a message if the supplied parameter
411
+ * is not an array, if the requested index is negative, or if the element cannot be converted.
412
+ * @param index - The index of the element to be extracted.
413
+ * @param converter - A {@link Converter | Converter} or {@link Validator | Validator} used for the extracted element.
414
+ * @returns A {@link Converter | Converter<T, TC>} which extracts the specified element from an array.
415
+ * @public
416
+ */
417
+ export function optionalElement(index, converter) {
418
+ return new BaseConverter((from, __self, context) => {
419
+ if (index < 0) {
420
+ return fail(`${index}: cannot convert for a negative element index`);
421
+ }
422
+ else if (!Array.isArray(from)) {
423
+ return fail('element converter: source is not an array');
424
+ }
425
+ else if (index >= from.length) {
426
+ return succeed(undefined);
427
+ }
428
+ return converter.convert(from[index], context);
429
+ });
430
+ }
431
+ /**
432
+ * A helper function to create a {@link Converter | Converter} which extracts and convert a property specified
433
+ * by name from an object.
434
+ * @remarks
435
+ * The resulting {@link Converter | Converter} returns {@link Success | Success} with the converted value of the corresponding
436
+ * object property if the field exists and can be converted. Returns {@link Failure | Failure} with an error message
437
+ * otherwise.
438
+ * @param name - The name of the field to be extracted.
439
+ * @param converter - {@link Converter | Converter} or {@link Validator | Validator} to use for the extracted
440
+ * field.
441
+ * @public
442
+ */
443
+ export function field(name, converter) {
444
+ return new BaseConverter((from, __self, context) => {
445
+ if (typeof from === 'object' && !Array.isArray(from) && from !== null) {
446
+ if (isKeyOf(name, from)) {
447
+ return converter.convert(from[name], context).onFailure((message) => {
448
+ return fail(`Field ${name}: ${message}`);
449
+ });
450
+ }
451
+ return fail(`Field ${name} not found in: ${JSON.stringify(from)}`);
452
+ }
453
+ return fail(`Cannot convert field "${name}" from non-object ${JSON.stringify(from)}`);
454
+ });
455
+ }
456
+ /**
457
+ * A helper function to create a {@link Converter | Converter} which extracts and convert a property specified
458
+ * by name from an object.
459
+ * @remarks
460
+ * The resulting {@link Converter | Converter} returns {@link Success | Success} with the converted value of
461
+ * the corresponding object property if the field exists and can be converted. Returns {@link Success | Success}
462
+ * with `undefined` if the supplied parameter is an object but the named field is not present.
463
+ * Returns {@link Failure | Failure} with an error message otherwise.
464
+ * @param name - The name of the field to be extracted.
465
+ * @param converter - {@link Converter | Converter} or {@link Validator | Validator} to use for the extracted field.
466
+ * @public
467
+ */
468
+ export function optionalField(name, converter) {
469
+ return new BaseConverter((from, __self, context) => {
470
+ if (typeof from === 'object' && !Array.isArray(from) && from !== null) {
471
+ if (isKeyOf(name, from)) {
472
+ const result = converter.convert(from[name], context).onFailure((message) => {
473
+ return fail(`${name}: ${message}`);
474
+ });
475
+ // if conversion was successful or input was undefined we
476
+ // succeed with 'undefined', but we propagate actual
477
+ // failures.
478
+ if (result.isSuccess() || from[name] !== undefined) {
479
+ return result;
480
+ }
481
+ }
482
+ return succeed(undefined);
483
+ }
484
+ return fail(`Cannot convert field "${name}" from non-object ${JSON.stringify(from)}`);
485
+ }, undefined, { isOptional: true });
486
+ }
487
+ /**
488
+ * Concrete implementation of {@link Converters.(object:1) | Converters.object(fields, options)}
489
+ * and {@link Converters.(object:2) | Converters.objects(fields, optionalKeys)}.
490
+ * @internal
491
+ */
492
+ export function object(properties, options) {
493
+ return new ObjectConverter(properties, options);
494
+ }
495
+ /**
496
+ * Concrete implementation for {@link Converters.(strictObject:1) | Converters.strictObject(fields, options)}
497
+ * and {@link Converters.strictObject | Converters.strictObject(fields, optional)}.
498
+ * @internal
499
+ */
500
+ export function strictObject(properties, opt) {
501
+ /* c8 ignore next 2 */
502
+ const options = opt && Array.isArray(opt) ? { strict: true, optionalFields: opt } : Object.assign(Object.assign({}, (opt !== null && opt !== void 0 ? opt : {})), { strict: true });
503
+ return new ObjectConverter(properties, options);
504
+ }
505
+ /**
506
+ * Helper to create a {@link Converter | Converter} which converts a discriminated object without changing shape.
507
+ * @remarks
508
+ * Takes the name of the discriminator property and a
509
+ * {@link Converters.DiscriminatedObjectConverters | string-keyed Record of converters and validators}. During conversion,
510
+ * the resulting {@link Converter | Converter} invokes the converter from `converters` that corresponds to the value of
511
+ * the discriminator property in the source object.
512
+ *
513
+ * If the source is not an object, the discriminator property is missing, or the discriminator has
514
+ * a value not present in the converters, conversion fails and returns {@link Failure | Failure} with more information.
515
+ * @param discriminatorProp - Name of the property used to discriminate types.
516
+ * @param converters - {@link Converters.DiscriminatedObjectConverters | String-keyed record of converters and validators}
517
+ * to invoke, where each key corresponds to a value of the discriminator property.
518
+ * @returns A {@link Converter | Converter} which converts the corresponding discriminated object.
519
+ * @public
520
+ */
521
+ export function discriminatedObject(discriminatorProp, converters) {
522
+ return new BaseConverter((from) => {
523
+ if (typeof from !== 'object' || Array.isArray(from) || from === null) {
524
+ return fail(`Not a discriminated object: "${JSON.stringify(from)}"`);
525
+ }
526
+ if (!isKeyOf(discriminatorProp, from) || !from[discriminatorProp]) {
527
+ return fail(`Discriminator property ${discriminatorProp} not present in "${JSON.stringify(from)}"`);
528
+ }
529
+ const discriminatorValue = from[discriminatorProp];
530
+ const converter = converters[discriminatorValue];
531
+ if (converter === undefined) {
532
+ return fail(`No converter for discriminator ${discriminatorProp}="${discriminatorValue}"`);
533
+ }
534
+ return converter.convert(from);
535
+ });
536
+ }
537
+ /**
538
+ * Helper to create a {@link Converter | Converter} which converts a source object to a new object with a
539
+ * different shape.
540
+ *
541
+ * @remarks
542
+ * On successful conversion, the resulting {@link Converter | Converter} returns {@link Success | Success} with a new
543
+ * object, which contains the converted values under the key names specified at initialization time.
544
+ * It returns {@link Failure | Failure} with an error message if any fields to be extracted do not exist
545
+ * or cannot be converted.
546
+ *
547
+ * Fields that succeed but convert to undefined are omitted from the result object but do not
548
+ * fail the conversion.
549
+ *
550
+ * @param properties - An object with key names that correspond to the target object and an
551
+ * appropriate {@link Conversion.FieldConverters | FieldConverter} which extracts and converts
552
+ * a single filed from the source object.
553
+ * @returns A {@link Converter | Converter} with the specified conversion behavior.
554
+ * @public
555
+ */
556
+ export function transform(properties) {
557
+ return new BaseConverter((from, __self, context) => {
558
+ // eslint bug thinks key is used before defined
559
+ const converted = {};
560
+ const errors = [];
561
+ for (const key in properties) {
562
+ if (properties[key]) {
563
+ const result = properties[key].convert(from, context);
564
+ if (result.isSuccess() && result.value !== undefined) {
565
+ converted[key] = result.value;
566
+ }
567
+ else if (result.isFailure()) {
568
+ errors.push(result.message);
569
+ }
570
+ }
571
+ }
572
+ return errors.length === 0 ? succeed(converted) : fail(errors.join('\n'));
573
+ });
574
+ }
575
+ /**
576
+ * Helper to create a strongly-typed {@link Converter | Converter} which converts a source object to a
577
+ * new object with a different shape.
578
+ *
579
+ * @remarks
580
+ * On successful conversion, the resulting {@link Converter | Converter} returns {@link Success | Success} with a new
581
+ * object, which contains the converted values under the key names specified at initialization time.
582
+ *
583
+ * It returns {@link Failure | Failure} with an error message if any fields to be extracted do not exist
584
+ * or cannot be converted.
585
+ *
586
+ * @param destinationFields - An object with key names that correspond to the target object and an
587
+ * appropriate {@link Converters.FieldTransformers | FieldTransformers} which specifies the name
588
+ * of the corresponding property in the source object, the converter or validator used for each source
589
+ * property and any other configuration to guide the conversion.
590
+ * @param options - Options which affect the transformation.
591
+ *
592
+ * @returns A {@link Converter | Converter} with the specified conversion behavior.
593
+ * @public
594
+ */
595
+ export function transformObject(destinationFields, options) {
596
+ return new BaseConverter((from, __self, context) => {
597
+ // eslint bug thinks key is used before defined
598
+ const converted = {};
599
+ const errors = [];
600
+ const used = new Set(options === null || options === void 0 ? void 0 : options.ignore);
601
+ if (typeof from === 'object' && !Array.isArray(from) && from !== null) {
602
+ for (const destinationKey in destinationFields) {
603
+ if (destinationFields[destinationKey]) {
604
+ const srcKey = destinationFields[destinationKey].from;
605
+ const converter = destinationFields[destinationKey].converter;
606
+ if (isKeyOf(srcKey, from)) {
607
+ const result = converter.convert(from[srcKey], context);
608
+ if (result.isSuccess() && result.value !== undefined) {
609
+ converted[destinationKey] = result.value;
610
+ }
611
+ else if (result.isFailure()) {
612
+ errors.push(`${srcKey}->${destinationKey}: ${result.message}`);
613
+ }
614
+ used.add(srcKey);
615
+ }
616
+ else if (destinationFields[destinationKey].optional !== true) {
617
+ errors.push(`${String(srcKey)}: required property missing in source object.`);
618
+ }
619
+ }
620
+ }
621
+ if ((options === null || options === void 0 ? void 0 : options.strict) === true) {
622
+ for (const key in from) {
623
+ if (isKeyOf(key, from) && !used.has(key)) {
624
+ errors.push(`${key}: unexpected property in source object`);
625
+ }
626
+ }
627
+ }
628
+ }
629
+ else {
630
+ errors.push('source is not an object');
631
+ }
632
+ return errors.length === 0
633
+ ? succeed(converted)
634
+ : fail((options === null || options === void 0 ? void 0 : options.description) ? `${options.description}:\n ${errors.join('\n ')}` : errors.join('\n'));
635
+ });
636
+ }
637
+ //# sourceMappingURL=converters.js.map