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