@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
@@ -1,5 +1,5 @@
1
1
  /*
2
- * Copyright (c) 2020 Erik Fortune
2
+ * Copyright (c) 2026 Erik Fortune
3
3
  *
4
4
  * Permission is hereby granted, free of charge, to any person obtaining a copy
5
5
  * of this software and associated documentation files (the "Software"), to deal
@@ -19,620 +19,6 @@
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 { 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
- const booleanConverter = new BaseConverter((from) => {
110
- if (typeof from === 'boolean') {
111
- return succeed(from);
112
- }
113
- else if (typeof from === 'string') {
114
- switch (from.toLowerCase()) {
115
- case 'true':
116
- return succeed(true);
117
- case 'false':
118
- return succeed(false);
119
- }
120
- }
121
- return fail(`Not a boolean: ${JSON.stringify(from)}`);
122
- });
123
- /**
124
- * A {@link Converter | Converter} which converts `unknown` to `boolean`.
125
- * @remarks
126
- * Boolean values or the case-insensitive strings `'true'` and `'false'` succeed.
127
- * Anything else fails.
128
- * @public
129
- */
130
- export const boolean = booleanConverter;
131
- /**
132
- * A {@link Converter | Converter} which converts an optional `string` value. Values of type
133
- * `string` are returned. Anything else returns {@link Success | Success} with value `undefined`.
134
- * @public
135
- */
136
- export const optionalString = string.optional();
137
- /**
138
- * Helper function to create a {@link Converter | Converter} which converts any `string` into an
139
- * array of `string`, by separating at a supplied delimiter.
140
- * @remarks
141
- * Delimiter may also be supplied as context at conversion time.
142
- * @param delimiter - The delimiter at which to split.
143
- * @returns A new {@link Converter | Converter} returning `string[]`.
144
- * @public
145
- */
146
- export function delimitedString(delimiter, options = 'filtered') {
147
- return new BaseConverter((from, __self, context) => {
148
- const result = string.convert(from);
149
- if (result.isSuccess()) {
150
- let strings = result.value.split(context !== null && context !== void 0 ? context : delimiter);
151
- if (options !== 'all') {
152
- strings = strings.filter((s) => s.trim().length > 0);
153
- }
154
- return succeed(strings);
155
- }
156
- return fail(result.message);
157
- });
158
- }
159
- /**
160
- * Helper function to create a {@link Converter | Converter} from any {@link Validation.Validator}
161
- * @param validator - the validator to be wrapped
162
- * @returns A {@link Converter | Converter} which uses the supplied validator.
163
- * @public
164
- */
165
- export function validated(validator) {
166
- return new BaseConverter((from, __self, context) => {
167
- return validator.validate(from, context);
168
- });
169
- }
170
- /**
171
- * Helper function to create a {@link Converter | Converter} from a supplied {@link Conversion.ConverterFunc | ConverterFunc}.
172
- * @param convert - the function to be wrapped
173
- * @returns A {@link Converter | Converter} which uses the supplied function.
174
- * @public
175
- */
176
- export function generic(convert) {
177
- return new BaseConverter(convert);
178
- }
179
- /**
180
- * Helper function to create a {@link Converter | Converter} from a supplied type guard function.
181
- * @param description - a description of the thing to be validated for use in error messages
182
- * @param guard - a {@link Validation.TypeGuardWithContext} which performs the validation.
183
- * @returns A new {@link Converter | Converter} which validates the values using the supplied type guard
184
- * and returns them in place.
185
- * @public
186
- */
187
- export function isA(description, guard) {
188
- return new BaseConverter((from, __self, context) => {
189
- if (guard(from, context)) {
190
- return succeed(from);
191
- }
192
- return fail(`invalid ${description} (${JSON.stringify(from)})`);
193
- });
194
- }
195
- /**
196
- * A {@link Converter | Converter} which converts an optional `number` value.
197
- * @remarks
198
- * Values of type `number` or numeric strings are converted and returned.
199
- * Anything else returns {@link Success | Success} with value `undefined`.
200
- * @public
201
- */
202
- export const optionalNumber = number.optional();
203
- /**
204
- * A {@link Converter | Converter} to convert an optional `boolean` value.
205
- * @remarks
206
- * Values of type `boolean` or strings that match (case-insensitive) `'true'`
207
- * or `'false'` are converted and returned. Anything else returns {@link Success | Success}
208
- * with value `undefined`.
209
- * @public
210
- */
211
- export const optionalBoolean = booleanConverter.optional();
212
- /**
213
- * A helper function to create a {@link Converter | Converter} for polymorphic values.
214
- * Returns a converter which invokes the wrapped converters in sequence, returning the
215
- * first successful result. Returns an error if none of the supplied converters can
216
- * convert the value.
217
- * @remarks
218
- * If `onError` is `ignoreErrors` (default), then errors from any of the
219
- * converters are ignored provided that some converter succeeds. If
220
- * onError is `failOnError`, then an error from any converter fails the entire
221
- * conversion.
222
- *
223
- * @param converters - An ordered list of {@link Converter | converters} or {@link Validator | validators}
224
- * to be considered.
225
- * @param onError - Specifies treatment of unconvertible elements.
226
- * @returns A new {@link Converter | Converter} which yields a value from the union of the types returned
227
- * by the wrapped converters.
228
- * @public
229
- */
230
- export function oneOf(converters, onError = 'ignoreErrors') {
231
- return new BaseConverter((from, __self, context) => {
232
- const errors = [];
233
- for (const converter of converters) {
234
- const result = converter.convert(from, context);
235
- if (result.isSuccess() && result.value !== undefined) {
236
- return result;
237
- }
238
- if (result.isFailure()) {
239
- if (onError === 'failOnError') {
240
- return result;
241
- }
242
- errors.push(result.message);
243
- }
244
- }
245
- return fail(`No matching converter for ${JSON.stringify(from)}: ${errors.join('\n')}`);
246
- });
247
- }
248
- /**
249
- * A helper function to create a {@link Converter | Converter} which converts `unknown` to an array of `<T>`.
250
- * @remarks
251
- * If `onError` is `'failOnError'` (default), then the entire conversion fails if any element cannot
252
- * be converted. If `onError` is `'ignoreErrors'`, then failing elements are silently ignored.
253
- * @param converter - {@link Converter | Converter} or {@link Validator | Validator} used to convert each
254
- * item in the array.
255
- * @param ignoreErrors - Specifies treatment of unconvertible elements.
256
- * @returns A {@link Converter | Converter} which returns an array of `<T>`.
257
- * @public
258
- */
259
- export function arrayOf(converter, onError = 'failOnError') {
260
- return new BaseConverter((from, __self, context) => {
261
- if (!Array.isArray(from)) {
262
- return fail(`Not an array: ${JSON.stringify(from)}`);
263
- }
264
- const successes = [];
265
- const errors = [];
266
- for (const item of from) {
267
- const result = converter.convert(item, context);
268
- if (result.isSuccess() && result.value !== undefined) {
269
- successes.push(result.value);
270
- }
271
- else if (result.isFailure()) {
272
- errors.push(result.message);
273
- }
274
- }
275
- return errors.length === 0 || onError === 'ignoreErrors' ? succeed(successes) : fail(errors.join('\n'));
276
- });
277
- }
278
- /**
279
- * {@link Converter | Converter} to convert an `unknown` to an array of `string`.
280
- * @remarks
281
- * Returns {@link Success | Success} with the the supplied value if it as an array
282
- * of strings, returns {@link Failure | Failure} with an error message otherwise.
283
- * @public
284
- */
285
- export const stringArray = arrayOf(string);
286
- /**
287
- * {@link Converter | Converter} to convert an `unknown` to an array of `number`.
288
- * @remarks
289
- * Returns {@link Success | Success} with the the supplied value if it as an array
290
- * of numbers, returns {@link Failure | Failure} with an error message otherwise.
291
- * @public
292
- */
293
- export const numberArray = arrayOf(number);
294
- /**
295
- * Concrete implementation of {@link Converters.(recordOf:1) | Converters.recordOf(Converter<T, TC>)},
296
- * {@link Converters.(recordOf:2) | Converters.recordOf(Converter<T, TC>, 'fail' or 'ignore')}, and
297
- * {@link Converters.(recordOf:3) | Converters.recordOf(Converter<T, TC>, KeyedConverterOptions)}.
298
- * @internal
299
- */
300
- export function recordOf(converter, option = 'fail') {
301
- const options = typeof option === 'string' ? { onError: option } : Object.assign({ onError: 'fail' }, option);
302
- return new BaseConverter((from, __self, context) => {
303
- var _a, _b;
304
- if (typeof from !== 'object' || from === null || Array.isArray(from)) {
305
- return fail(`Not a string-keyed object: ${JSON.stringify(from)}`);
306
- }
307
- const record = {};
308
- const errors = [];
309
- for (const key in from) {
310
- if (isKeyOf(key, from)) {
311
- const writeKeyResult = (_b = (_a = options.keyConverter) === null || _a === void 0 ? void 0 : _a.convert(key, context)) !== null && _b !== void 0 ? _b : succeed(key);
312
- writeKeyResult
313
- .onSuccess((writeKey) => {
314
- return converter.convert(from[key], context).onSuccess((value) => {
315
- record[writeKey] = value;
316
- return succeed(true);
317
- });
318
- })
319
- .onFailure((message) => {
320
- errors.push(message);
321
- return fail(message);
322
- });
323
- }
324
- }
325
- return errors.length === 0 || options.onError === 'ignore' ? succeed(record) : fail(errors.join('\n'));
326
- });
327
- }
328
- /**
329
- * Concrete implementation of {@link Converters.(mapOf:1) | Converters.mapOf(Converter<T, TC>)},
330
- * {@link Converters.(mapOf:2) | Converters.mapOf(Converter<T, TC>, 'fail' or 'ignore')}, and
331
- * {@link Converters.(mapOf:3) | Converters.mapOf(Converter<T, TC>, KeyedConverterOptions)}.
332
- * @internal
333
- */
334
- export function mapOf(converter, option = 'fail') {
335
- const options = typeof option === 'string' ? { onError: option } : Object.assign({ onError: 'fail' }, option);
336
- return new BaseConverter((from, __self, context) => {
337
- var _a, _b;
338
- if (typeof from !== 'object' || from === null || Array.isArray(from)) {
339
- return fail(`Not a string-keyed object: ${JSON.stringify(from)}`);
340
- }
341
- const map = new Map();
342
- const errors = [];
343
- for (const key in from) {
344
- if (isKeyOf(key, from)) {
345
- const writeKeyResult = (_b = (_a = options.keyConverter) === null || _a === void 0 ? void 0 : _a.convert(key, context)) !== null && _b !== void 0 ? _b : succeed(key);
346
- writeKeyResult
347
- .onSuccess((writeKey) => {
348
- return converter.convert(from[key], context).onSuccess((value) => {
349
- map.set(writeKey, value);
350
- return succeed(true);
351
- });
352
- })
353
- .onFailure((message) => {
354
- errors.push(message);
355
- return fail(message);
356
- });
357
- }
358
- }
359
- return errors.length === 0 || options.onError === 'ignore' ? succeed(map) : fail(errors.join('\n'));
360
- });
361
- }
362
- /**
363
- * Helper function to create a {@link Converter | Converter} which validates that a supplied value is
364
- * of a type validated by a supplied validator function and returns it.
365
- * @remarks
366
- * If `validator` succeeds, this {@link Converter | Converter} returns {@link Success | Success} with the supplied
367
- * value of `from` coerced to type `<T>`. Returns a {@link Failure | Failure} with additional
368
- * information otherwise.
369
- * @param validator - A validator function to determine if the converted value is valid.
370
- * @param description - A description of the validated type for use in error messages.
371
- * @returns A new {@link Converter | Converter<T, TC>} which applies the supplied validation.
372
- * @public
373
- */
374
- export function validateWith(validator, description) {
375
- return new BaseConverter((from, __self, __context) => {
376
- if (validator(from)) {
377
- return succeed(from);
378
- }
379
- return fail(`${JSON.stringify(from)}: invalid ${description !== null && description !== void 0 ? description : 'value'}`);
380
- });
381
- }
382
- /**
383
- * A helper function to create a {@link Converter | Converter} which extracts and converts an element from an array.
384
- * @remarks
385
- * The returned {@link Converter | Converter} returns {@link Success | Success} with the converted value if the element exists
386
- * in the supplied array and can be converted. Returns {@link Failure | Failure} with an error message otherwise.
387
- * @param index - The index of the element to be extracted.
388
- * @param converter - A {@link Converter | Converter} or {@link Validator | Validator} for the extracted element.
389
- * @returns A {@link Converter | Converter<T, TC>} which extracts the specified element from an array.
390
- * @public
391
- */
392
- export function element(index, converter) {
393
- return new BaseConverter((from, __self, context) => {
394
- if (index < 0) {
395
- return fail(`${index}: cannot convert for a negative element index`);
396
- }
397
- else if (!Array.isArray(from)) {
398
- return fail('element converter: source is not an array');
399
- }
400
- else if (index >= from.length) {
401
- return fail(`${index}: element converter index out of range (0..${from.length - 1})`);
402
- }
403
- return converter.convert(from[index], context);
404
- });
405
- }
406
- /**
407
- * A helper function to create a {@link Converter | Converter} which extracts and converts an optional element from an array.
408
- * @remarks
409
- * The resulting {@link Converter | Converter} returns {@link Success | Success} with the converted value if the element exists
410
- * in the supplied array and can be converted. Returns {@link Success | Success} with value `undefined` if the parameter
411
- * is an array but the index is out of range. Returns {@link Failure | Failure} with a message if the supplied parameter
412
- * is not an array, if the requested index is negative, or if the element cannot be converted.
413
- * @param index - The index of the element to be extracted.
414
- * @param converter - A {@link Converter | Converter} or {@link Validator | Validator} used for the extracted element.
415
- * @returns A {@link Converter | Converter<T, TC>} which extracts the specified element from an array.
416
- * @public
417
- */
418
- export function optionalElement(index, converter) {
419
- return new BaseConverter((from, __self, context) => {
420
- if (index < 0) {
421
- return fail(`${index}: cannot convert for a negative element index`);
422
- }
423
- else if (!Array.isArray(from)) {
424
- return fail('element converter: source is not an array');
425
- }
426
- else if (index >= from.length) {
427
- return succeed(undefined);
428
- }
429
- return converter.convert(from[index], context);
430
- });
431
- }
432
- /**
433
- * A helper function to create a {@link Converter | Converter} which extracts and convert a property specified
434
- * by name from an object.
435
- * @remarks
436
- * The resulting {@link Converter | Converter} returns {@link Success | Success} with the converted value of the corresponding
437
- * object property if the field exists and can be converted. Returns {@link Failure | Failure} with an error message
438
- * otherwise.
439
- * @param name - The name of the field to be extracted.
440
- * @param converter - {@link Converter | Converter} or {@link Validator | Validator} to use for the extracted
441
- * field.
442
- * @public
443
- */
444
- export function field(name, converter) {
445
- return new BaseConverter((from, __self, context) => {
446
- if (typeof from === 'object' && !Array.isArray(from) && from !== null) {
447
- if (isKeyOf(name, from)) {
448
- return converter.convert(from[name], context).onFailure((message) => {
449
- return fail(`Field ${name}: ${message}`);
450
- });
451
- }
452
- return fail(`Field ${name} not found in: ${JSON.stringify(from)}`);
453
- }
454
- return fail(`Cannot convert field "${name}" from non-object ${JSON.stringify(from)}`);
455
- });
456
- }
457
- /**
458
- * A helper function to create a {@link Converter | Converter} which extracts and convert a property specified
459
- * by name from an object.
460
- * @remarks
461
- * The resulting {@link Converter | Converter} returns {@link Success | Success} with the converted value of
462
- * the corresponding object property if the field exists and can be converted. Returns {@link Success | Success}
463
- * with `undefined` if the supplied parameter is an object but the named field is not present.
464
- * Returns {@link Failure | Failure} with an error message otherwise.
465
- * @param name - The name of the field to be extracted.
466
- * @param converter - {@link Converter | Converter} or {@link Validator | Validator} to use for the extracted field.
467
- * @public
468
- */
469
- export function optionalField(name, converter) {
470
- return new BaseConverter((from, __self, context) => {
471
- if (typeof from === 'object' && !Array.isArray(from) && from !== null) {
472
- if (isKeyOf(name, from)) {
473
- const result = converter.convert(from[name], context).onFailure((message) => {
474
- return fail(`${name}: ${message}`);
475
- });
476
- // if conversion was successful or input was undefined we
477
- // succeed with 'undefined', but we propagate actual
478
- // failures.
479
- if (result.isSuccess() || from[name] !== undefined) {
480
- return result;
481
- }
482
- }
483
- return succeed(undefined);
484
- }
485
- return fail(`Cannot convert field "${name}" from non-object ${JSON.stringify(from)}`);
486
- }, undefined, { isOptional: true });
487
- }
488
- /**
489
- * Concrete implementation of {@link Converters.(object:1) | Converters.object(fields, options)}
490
- * and {@link Converters.(object:2) | Converters.objects(fields, optionalKeys)}.
491
- * @internal
492
- */
493
- export function object(properties, options) {
494
- return new ObjectConverter(properties, options);
495
- }
496
- /**
497
- * Concrete implementation for {@link Converters.(strictObject:1) | Converters.strictObject(fields, options)}
498
- * and {@link Converters.strictObject | Converters.strictObject(fields, optional)}.
499
- * @internal
500
- */
501
- export function strictObject(properties, opt) {
502
- /* c8 ignore next 2 */
503
- const options = opt && Array.isArray(opt) ? { strict: true, optionalFields: opt } : Object.assign(Object.assign({}, (opt !== null && opt !== void 0 ? opt : {})), { strict: true });
504
- return new ObjectConverter(properties, options);
505
- }
506
- /**
507
- * Helper to create a {@link Converter | Converter} which converts a discriminated object without changing shape.
508
- * @remarks
509
- * Takes the name of the discriminator property and a
510
- * {@link Converters.DiscriminatedObjectConverters | string-keyed Record of converters and validators}. During conversion,
511
- * the resulting {@link Converter | Converter} invokes the converter from `converters` that corresponds to the value of
512
- * the discriminator property in the source object.
513
- *
514
- * If the source is not an object, the discriminator property is missing, or the discriminator has
515
- * a value not present in the converters, conversion fails and returns {@link Failure | Failure} with more information.
516
- * @param discriminatorProp - Name of the property used to discriminate types.
517
- * @param converters - {@link Converters.DiscriminatedObjectConverters | String-keyed record of converters and validators}
518
- * to invoke, where each key corresponds to a value of the discriminator property.
519
- * @returns A {@link Converter | Converter} which converts the corresponding discriminated object.
520
- * @public
521
- */
522
- export function discriminatedObject(discriminatorProp, converters) {
523
- return new BaseConverter((from) => {
524
- if (typeof from !== 'object' || Array.isArray(from) || from === null) {
525
- return fail(`Not a discriminated object: "${JSON.stringify(from)}"`);
526
- }
527
- if (!isKeyOf(discriminatorProp, from) || !from[discriminatorProp]) {
528
- return fail(`Discriminator property ${discriminatorProp} not present in "${JSON.stringify(from)}"`);
529
- }
530
- const discriminatorValue = from[discriminatorProp];
531
- const converter = converters[discriminatorValue];
532
- if (converter === undefined) {
533
- return fail(`No converter for discriminator ${discriminatorProp}="${discriminatorValue}"`);
534
- }
535
- return converter.convert(from);
536
- });
537
- }
538
- /**
539
- * Helper to create a {@link Converter | Converter} which converts a source object to a new object with a
540
- * different shape.
541
- *
542
- * @remarks
543
- * On successful conversion, the resulting {@link Converter | Converter} returns {@link Success | Success} with a new
544
- * object, which contains the converted values under the key names specified at initialization time.
545
- * It returns {@link Failure | Failure} with an error message if any fields to be extracted do not exist
546
- * or cannot be converted.
547
- *
548
- * Fields that succeed but convert to undefined are omitted from the result object but do not
549
- * fail the conversion.
550
- *
551
- * @param properties - An object with key names that correspond to the target object and an
552
- * appropriate {@link Conversion.FieldConverters | FieldConverter} which extracts and converts
553
- * a single filed from the source object.
554
- * @returns A {@link Converter | Converter} with the specified conversion behavior.
555
- * @public
556
- */
557
- export function transform(properties) {
558
- return new BaseConverter((from, __self, context) => {
559
- // eslint bug thinks key is used before defined
560
- const converted = {};
561
- const errors = [];
562
- for (const key in properties) {
563
- if (properties[key]) {
564
- const result = properties[key].convert(from, context);
565
- if (result.isSuccess() && result.value !== undefined) {
566
- converted[key] = result.value;
567
- }
568
- else if (result.isFailure()) {
569
- errors.push(result.message);
570
- }
571
- }
572
- }
573
- return errors.length === 0 ? succeed(converted) : fail(errors.join('\n'));
574
- });
575
- }
576
- /**
577
- * Helper to create a strongly-typed {@link Converter | Converter} which converts a source object to a
578
- * new object with a different shape.
579
- *
580
- * @remarks
581
- * On successful conversion, the resulting {@link Converter | Converter} returns {@link Success | Success} with a new
582
- * object, which contains the converted values under the key names specified at initialization time.
583
- *
584
- * It returns {@link Failure | Failure} with an error message if any fields to be extracted do not exist
585
- * or cannot be converted.
586
- *
587
- * @param destinationFields - An object with key names that correspond to the target object and an
588
- * appropriate {@link Converters.FieldTransformers | FieldTransformers} which specifies the name
589
- * of the corresponding property in the source object, the converter or validator used for each source
590
- * property and any other configuration to guide the conversion.
591
- * @param options - Options which affect the transformation.
592
- *
593
- * @returns A {@link Converter | Converter} with the specified conversion behavior.
594
- * @public
595
- */
596
- export function transformObject(destinationFields, options) {
597
- return new BaseConverter((from, __self, context) => {
598
- // eslint bug thinks key is used before defined
599
- const converted = {};
600
- const errors = [];
601
- const used = new Set(options === null || options === void 0 ? void 0 : options.ignore);
602
- if (typeof from === 'object' && !Array.isArray(from) && from !== null) {
603
- for (const destinationKey in destinationFields) {
604
- if (destinationFields[destinationKey]) {
605
- const srcKey = destinationFields[destinationKey].from;
606
- const converter = destinationFields[destinationKey].converter;
607
- if (isKeyOf(srcKey, from)) {
608
- const result = converter.convert(from[srcKey], context);
609
- if (result.isSuccess() && result.value !== undefined) {
610
- converted[destinationKey] = result.value;
611
- }
612
- else if (result.isFailure()) {
613
- errors.push(`${srcKey}->${destinationKey}: ${result.message}`);
614
- }
615
- used.add(srcKey);
616
- }
617
- else if (destinationFields[destinationKey].optional !== true) {
618
- errors.push(`${String(srcKey)}: required property missing in source object.`);
619
- }
620
- }
621
- }
622
- if ((options === null || options === void 0 ? void 0 : options.strict) === true) {
623
- for (const key in from) {
624
- if (isKeyOf(key, from) && !used.has(key)) {
625
- errors.push(`${key}: unexpected property in source object`);
626
- }
627
- }
628
- }
629
- }
630
- else {
631
- errors.push('source is not an object');
632
- }
633
- return errors.length === 0
634
- ? succeed(converted)
635
- : fail((options === null || options === void 0 ? void 0 : options.description) ? `${options.description}:\n ${errors.join('\n ')}` : errors.join('\n'));
636
- });
637
- }
22
+ export * from './basicConverters';
23
+ export * from './advancedConverters';
638
24
  //# sourceMappingURL=converters.js.map