read-excel-file 8.0.3 → 9.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.
@@ -1,17 +1,18 @@
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
3
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
1
4
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2
5
  function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
3
6
  function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
4
7
  function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
5
8
  function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
6
- function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
7
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
8
- function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
9
9
  function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest(); }
10
10
  function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
11
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
12
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
13
11
  function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
14
12
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
13
+ function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
14
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
15
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
15
16
  import NumberType from './types/Number.js';
16
17
  import StringType from './types/String.js';
17
18
  import BooleanType from './types/Boolean.js';
@@ -30,7 +31,7 @@ import DateType from './types/Date.js';
30
31
  * // * `shouldSkipRequiredValidationWhenColumnIsMissing: (column: string, { object }) => boolean` — By default, it does apply `required` validation to `schema` properties for which columns are missing in the input `data`. One could pass a custom `shouldSkipRequiredValidationWhenColumnIsMissing(column, { object })` to disable `required` validation for missing columns in some or all cases.
31
32
  * * `transformEmptyObject(object, { path? })` — By default, it returns `null` for "empty" objects. One could override that value using `transformEmptyObject(object, { path })` parameter. The value applies to both top-level object and any nested sub-objects in case of a nested schema, hence the additional (optional) `path?: string` parameter.
32
33
  * * `transformEmptyArray(array, { path })` — By default, it returns `null` for an "empty" array value. One could override that value using `transformEmptyArray(array, { path })` parameter.
33
- * * `arrayValueSeparator` — By default, it splits array-type cell values by a comma character.
34
+ * * `separatorCharacter` — By default, it splits array-type cell values by a comma character.
34
35
  *
35
36
  * When parsing a property value, in case of an error, the value of that property is gonna be `undefined`.
36
37
  *
@@ -42,301 +43,398 @@ import DateType from './types/Date.js';
42
43
  * // @param {boolean} [options.shouldSkipRequiredValidationWhenColumnIsMissing(column: string, { object })] — By default, it does apply `required` validation to `schema` properties for which columns are missing in the input `data`. One could pass a custom `shouldSkipRequiredValidationWhenColumnIsMissing(column, { object })` to disable `required` validation for missing columns in some or all cases.
43
44
  * @param {function} [options.transformEmptyObject(object, { path })] — By default, it returns `null` for an "empty" resulting object. One could override that value using `transformEmptyObject(object, { path })` parameter. The value applies to both top-level object and any nested sub-objects in case of a nested schema, hence the additional `path?: string` parameter.
44
45
  * @param {function} [options.transformEmptyArray(array, { path })] — By default, it returns `null` for an "empty" array value. One could override that value using `transformEmptyArray(array, { path })` parameter.
45
- * @param {string} [options.arrayValueSeparator] — When specified, string values will be split by this separator to get the array.
46
- * @return {object[]} — An array of objects of shape `{ object, errors }`. Either `object` or `errors` is going to be `undefined`.
46
+ * @param {string} [options.separatorCharacter] — When specified, string values will be split by this separator to get the array.
47
+ * @return {object} — An object of shape `{ objects, errors }`. Either `objects` or `errors` is going to be `undefined`.
47
48
  */
48
49
  export default function parseData(data, schema, optionsCustom) {
50
+ var objects = [];
51
+ var errors = [];
52
+ var parsedRows = parseDataWithPerRowErrors(data, schema, optionsCustom);
53
+ for (var _iterator = _createForOfIteratorHelperLoose(parsedRows), _step; !(_step = _iterator()).done;) {
54
+ var _step$value = _step.value,
55
+ object = _step$value.object,
56
+ rowErrors = _step$value.errors;
57
+ if (rowErrors) {
58
+ errors = errors.concat(rowErrors);
59
+ } else {
60
+ objects.push(object);
61
+ }
62
+ }
63
+ if (errors.length > 0) {
64
+ return {
65
+ errors: errors
66
+ };
67
+ }
68
+ return {
69
+ objects: objects
70
+ };
71
+ }
72
+
73
+ // This one is only used in tests.
74
+ export function parseDataWithPerRowErrors(data, schema, optionsCustom) {
49
75
  validateSchema(schema);
50
76
  var options = applyDefaultOptions(optionsCustom);
51
77
  var _data = _toArray(data),
52
78
  columns = _data[0],
53
79
  dataRows = _data.slice(1);
54
- return dataRows.map(function (dataRow) {
55
- return parseDataRow(dataRow, schema, undefined, columns, options);
80
+ return dataRows.map(function (row) {
81
+ return parseDataRow(row, schema, columns, options);
56
82
  });
57
83
  }
58
- function parseDataRow(row, schema, path, columns, options) {
84
+ function parseDataRow(dataRow, schema, columns, options) {
85
+ // Create a `schemaEntry` for the top-level object.
86
+ var schemaEntry = {
87
+ schema: schema
88
+ };
89
+
90
+ // Parse the values in the given data row into an object.
91
+ var _parseProperty = parseProperty(dataRow, schemaEntry, undefined, columns, options),
92
+ value = _parseProperty.value,
93
+ isEmptyValue = _parseProperty.isEmptyValue,
94
+ errors = _parseProperty.errors,
95
+ children = _parseProperty.children;
96
+
97
+ // Simulate a "dummy" parent object for the top-level object.
98
+ // It will be used when running `required` validations.
99
+ var dummyParentObject = {
100
+ // The "dummy" parent object has a "dummy" value.
101
+ // This value is irrelevant because it won't be read anywhere.
102
+ value: PARSED_OBJECT_TREE_START,
103
+ // The "dummy" parent object is empty if the parsed row is empty.
104
+ isEmptyValue: isEmptyValue,
105
+ // The "dummy" object has the same errors as the parsed row.
106
+ errors: errors,
107
+ // The parsed object by default is not required to have any data
108
+ // so the "dummy" object is not required.
109
+ isRequired: undefined
110
+ };
111
+
112
+ // Run any `required` validations.
113
+ //
114
+ // `required` validations should be run after the entire data row has been parsed,
115
+ // i.e. when the entire object structure has been parsed.
116
+ // The reason is that a `required` validation could be either a simple boolean or a "complex" function.
117
+ // In the latter case, the result of a `required()` function may depend on any other property of the object,
118
+ // hence the actual `required` flag value could only be obtained after the entire data row has been parsed.
119
+ //
120
+ // For example, consider a top-level object:
121
+ //
122
+ // {
123
+ // firstName: string,
124
+ // lastName: string,
125
+ // pet?: { name: string }
126
+ // }
127
+ //
128
+ // A corresponding schema would be:
129
+ //
130
+ // {
131
+ // firstName: {
132
+ // required: true
133
+ // },
134
+ // lastName: {
135
+ // required: true
136
+ // },
137
+ // pet: {
138
+ // required: false,
139
+ // schema: {
140
+ // name: {
141
+ // required: true
142
+ // }
143
+ // }
144
+ // }
145
+ // }
146
+ //
147
+ // I.e. when a `pet` exists, it must have a `name`.
148
+ //
149
+ // In such case, the `required: true` check of the `pet`'s `name` property
150
+ // should not be performed if the `pet` is not present, because the `pet` nested object
151
+ // is marked as `required: false`, meaning that `pet` data is not required to be present.
152
+ //
153
+ var requiredErrors = runPendingRequiredValidations(schemaEntry, value, isEmptyValue, errors, children,
154
+ // Simulate a "dummy" parent object for the top-level object.
155
+ dummyParentObject.isRequired, dummyParentObject.value, dummyParentObject.isEmptyValue, dummyParentObject.errors);
156
+
157
+ // If there were any errors, whether caused by `required`
158
+ // or occured while parsing the values, return those errors.
159
+ if (errors || requiredErrors) {
160
+ return {
161
+ errors: (errors || []).concat(requiredErrors || [])
162
+ };
163
+ }
164
+
165
+ // Return the parsed object.
166
+ return {
167
+ object: transformValue(value, isEmptyValue, undefined, options)
168
+ };
169
+ }
170
+ function parseObject(row, schema, path, columns, options) {
59
171
  var object = {};
60
- var errors = [];
61
172
  var isEmptyObject = true;
62
- var pendingRequiredValidations = [];
173
+ var errors = [];
174
+ var children = [];
63
175
 
64
176
  // For each property of the object.
65
177
  for (var _i = 0, _Object$keys = Object.keys(schema); _i < _Object$keys.length; _i++) {
66
178
  var key = _Object$keys[_i];
67
- var _parseProperty = parseProperty(key, row, path, schema, columns, options),
68
- propertyErrors = _parseProperty.errors,
69
- pendingRequiredValidation = _parseProperty.pendingRequiredValidation,
70
- value = _parseProperty.value;
71
- if (propertyErrors) {
72
- errors = errors.concat(propertyErrors);
179
+ var child = parseProperty(row, schema[key], getPropertyPath(key, path), columns, options);
180
+ if (child.errors) {
181
+ errors = errors.concat(child.errors);
73
182
  } else {
74
- object[key] = value;
75
- // Will perform `required` validation later, when all properties have been parsed.
76
- if (pendingRequiredValidation) {
77
- pendingRequiredValidations.push(pendingRequiredValidation);
78
- }
183
+ object[key] = transformValue(child.value, child.isEmptyValue, getPropertyPath(key, path), options);
79
184
  // Potentially unmark the object as "empty".
80
- if (isEmptyObject && !isEmptyValue(value)) {
185
+ if (isEmptyObject && !child.isEmptyValue) {
81
186
  isEmptyObject = false;
82
187
  }
83
188
  }
84
- }
85
-
86
- // Perform basic `required` validations (i.e. when `required` property is a boolean).
87
- for (var _i2 = 0, _pendingRequiredValid = pendingRequiredValidations; _i2 < _pendingRequiredValid.length; _i2++) {
88
- var _pendingRequiredValid2 = _pendingRequiredValid[_i2],
89
- required = _pendingRequiredValid2.required,
90
- schemaEntry = _pendingRequiredValid2.schemaEntry,
91
- _value = _pendingRequiredValid2.value;
92
- if (required === true) {
93
- errors.push(createError({
94
- error: 'required',
95
- schemaEntry: schemaEntry,
96
- value: _value
97
- }));
98
- }
189
+ children.push(_objectSpread(_objectSpread({}, child), {}, {
190
+ // `schemaEntry` will be used when running `required` validation of this property (later),
191
+ schemaEntry: schema[key]
192
+ }));
99
193
  }
100
194
 
101
195
  // If there were any errors, return them.
102
196
  if (errors.length > 0) {
103
197
  return {
104
- errors: errors
105
- };
106
- }
107
-
108
- // Perform "complex" `required` validations (i.e. when `required` property is a function).
109
- // These "complex" `required` validations should only be performed when all properties
110
- // of an object have been parsed correctly because these validations rely on the values
111
- // of other properties.
112
- for (var _i3 = 0, _pendingRequiredValid3 = pendingRequiredValidations; _i3 < _pendingRequiredValid3.length; _i3++) {
113
- var _pendingRequiredValid4 = _pendingRequiredValid3[_i3],
114
- _required = _pendingRequiredValid4.required,
115
- _schemaEntry = _pendingRequiredValid4.schemaEntry,
116
- _value2 = _pendingRequiredValid4.value;
117
- if (typeof _required !== 'boolean' && _required(object)) {
118
- errors.push(createError({
119
- error: 'required',
120
- schemaEntry: _schemaEntry,
121
- value: _value2
122
- }));
123
- }
124
- }
125
-
126
- // If there were any "complex" `required` errors, return them.
127
- if (errors.length > 0) {
128
- return {
129
- errors: errors
130
- };
131
- }
132
-
133
- // Return `null` for an "empty" mapped object.
134
- if (isEmptyObject) {
135
- return {
136
- object: options.transformEmptyObject(object, {
137
- path: path
138
- })
198
+ // Return the errors.
199
+ errors: errors,
200
+ // Return the `children` because `required` validations still have to be run (later).
201
+ children: children
139
202
  };
140
203
  }
141
204
  return {
142
- object: object
205
+ value: object,
206
+ isEmptyValue: isEmptyObject,
207
+ // Return the `children` because `required` validations still have to be run (later).
208
+ children: children
143
209
  };
144
210
  }
145
- function parseProperty(key, row, path, schema, columns, options) {
146
- var schemaEntry = schema[key];
211
+ function parseProperty(row, schemaEntry, path, columns, options) {
147
212
  var columnIndex = schemaEntry.column ? columns.indexOf(schemaEntry.column) : undefined;
148
- var isMissingColumn = columnIndex < 0;
149
-
150
- // The path of this property inside the top-level object.
151
- var propertyPath = "".concat(path ? path + '.' : '').concat(key);
152
- var _ref = schemaEntry.schema ? parseNestedObject(row, schemaEntry.schema, propertyPath, columns, options) : isMissingColumn ? {
153
- value: options.propertyValueWhenColumnIsMissing
154
- } : parseDataCellValue(row[columnIndex], schemaEntry, propertyPath, options),
213
+ var isMissingColumn = schemaEntry.column ? columnIndex < 0 : undefined;
214
+ var _ref = schemaEntry.column ? isMissingColumn ? {
215
+ value: options.propertyValueWhenColumnIsMissing,
216
+ isEmptyValue: true
217
+ } : parseCellValueWithPossibleErrors(row[columnIndex], schemaEntry, options) : parseObject(row, schemaEntry.schema, path, columns, options),
218
+ value = _ref.value,
219
+ isEmptyValue = _ref.isEmptyValue,
155
220
  errors = _ref.errors,
156
- value = _ref.value;
221
+ children = _ref.children;
222
+
223
+ // If there were any errors, return them.
157
224
  if (errors) {
158
225
  return {
159
- errors: errors
160
- };
161
- }
162
-
163
- // Should apply `required` validation if the value is "empty".
164
- var pendingRequiredValidation;
165
- if (schemaEntry.required && isEmptyValue(value)) {
166
- // // Can optionally skip `required` validation for certain missing columns.
167
- // const skipRequiredValidation = isMissingColumn && options.shouldSkipRequiredValidationWhenColumnIsMissing(schemaEntry.column, { object: ... })
168
- // if (!skipRequiredValidation) { ... }
169
-
170
- // Will perform `required` validation in the end,
171
- // when all properties of the object have been parsed.
172
- // This is because `required` could also be a function of `object`.
173
- pendingRequiredValidation = {
174
- required: schemaEntry.required,
175
- schemaEntry: schemaEntry,
176
- value: value
226
+ // Return the errors.
227
+ errors: errors,
228
+ // Return the `children` because `required` validations still have to be run (later).
229
+ children: children
177
230
  };
178
231
  }
179
232
  return {
180
233
  value: value,
181
- pendingRequiredValidation: pendingRequiredValidation
182
- };
183
- }
184
- function parseNestedObject(row, schema, propertyPath, columns, options) {
185
- var _parseDataRow = parseDataRow(row, schema, propertyPath, columns, options),
186
- object = _parseDataRow.object,
187
- errors = _parseDataRow.errors;
188
- return {
189
- value: object,
190
- errors: errors
234
+ isEmptyValue: isEmptyValue,
235
+ // Return the `children` because `required` validations still have to be run (later).
236
+ children: children
191
237
  };
192
238
  }
193
- function parseDataCellValue(cellValue, schemaEntry, propertyPath, options) {
194
- var _parseDataCellValue_ = parseDataCellValue_(cellValue, schemaEntry, propertyPath, options),
195
- propertyValue = _parseDataCellValue_.value,
196
- errorMessage = _parseDataCellValue_.error,
197
- reason = _parseDataCellValue_.reason;
239
+ function parseCellValueWithPossibleErrors(cellValue, schemaEntry, options) {
240
+ var _parseCellValue = parseCellValue(cellValue, schemaEntry, options),
241
+ value = _parseCellValue.value,
242
+ isEmptyValue = _parseCellValue.isEmptyValue,
243
+ errorMessage = _parseCellValue.error,
244
+ errorReason = _parseCellValue.reason;
198
245
  if (errorMessage) {
199
246
  var error = createError({
200
- schemaEntry: schemaEntry,
201
- value: cellValue,
202
247
  error: errorMessage,
203
- reason: reason
248
+ reason: errorReason,
249
+ column: schemaEntry.column,
250
+ valueType: schemaEntry.type,
251
+ value: cellValue
204
252
  });
205
253
  return {
206
254
  errors: [error]
207
255
  };
208
- } else {
209
- return {
210
- value: propertyValue
211
- };
212
256
  }
257
+ return {
258
+ value: value,
259
+ isEmptyValue: isEmptyValue
260
+ };
213
261
  }
214
262
 
215
263
  /**
216
264
  * Converts a cell value value to a javascript typed value.
217
- * @param {any} value
265
+ * @param {any} cellValue
218
266
  * @param {object} schemaEntry
219
267
  * @param {string} propertyPath
220
268
  * @param {object} options
221
- * @return {{ value?: any, error?: string, reason?: string }}
269
+ * @return {{ value?: any, isEmptyValue: boolean } | { error: string, reason?: string }}
222
270
  */
223
- function parseDataCellValue_(cellValue, schemaEntry, propertyPath, options) {
271
+ function parseCellValue(cellValue, schemaEntry, options) {
224
272
  if (cellValue === undefined) {
225
273
  // This isn't supposed to be possible when reading spreadsheet data:
226
274
  // cell values are always read as `null` when those cells are empty.
227
275
  // It's currently impossible for `read-excel-file` to return `undefined` cell value.
228
276
  // Here it uses some "sensible default" fallback by treating `undefined` as "column missing".
229
277
  return {
230
- value: options.propertyValueWhenColumnIsMissing
278
+ value: options.propertyValueWhenColumnIsMissing,
279
+ isEmptyValue: true
231
280
  };
232
281
  }
233
282
  if (cellValue === null) {
234
283
  return {
235
- value: options.propertyValueWhenCellIsEmpty
284
+ value: options.propertyValueWhenCellIsEmpty,
285
+ isEmptyValue: true
236
286
  };
237
287
  }
288
+
289
+ // Parse comma-separated cell value.
238
290
  if (Array.isArray(schemaEntry.type)) {
239
- var errors = [];
240
- var reasons = [];
241
- var values = parseSeparatedSubstrings(cellValue, options.arrayValueSeparator).map(function (substring) {
242
- // If any substring was already detected to be invalid
243
- // don't attempt to parse any other substrings.
244
- if (errors.length > 0) {
245
- return;
246
- }
247
- // If an empty substring was extracted, it means that there was an out-of-place separator.
248
- if (!substring) {
249
- errors.push('invalid');
250
- reasons.push('syntax');
251
- return;
252
- }
253
- var _parseValue = parseValue(substring, schemaEntry, options),
254
- value = _parseValue.value,
255
- error = _parseValue.error,
256
- reason = _parseValue.reason;
257
- if (error) {
258
- errors.push(error);
259
- reasons.push(reason);
260
- return;
261
- }
262
- return value;
263
- });
291
+ return parseArrayValue(cellValue, schemaEntry, options);
292
+ }
293
+ return parseValue(cellValue, schemaEntry, options);
294
+ }
295
+
296
+ /**
297
+ * Converts textual value to a javascript typed array value.
298
+ * @param {any} value
299
+ * @param {object} schemaEntry
300
+ * @param {object} options
301
+ * @return {{ value?: any, isEmptyValue: boolean } | { error: string, reason?: string }}
302
+ */
303
+ function parseArrayValue(value, schemaEntry, options) {
304
+ // If the cell value is not a string — i.e. a number, a boolean, a Date —
305
+ // then throw an error.
306
+ if (typeof value !== 'string') {
307
+ return {
308
+ error: 'not_a_string'
309
+ };
310
+ }
311
+ var isEmptyArray = true;
312
+ var errors = [];
313
+ var reasons = [];
314
+ var values = parseSeparatedSubstrings(value, options.separatorCharacter).map(function (substring) {
315
+ // If any substring was already detected to be invalid
316
+ // don't attempt to parse any other substrings.
264
317
  if (errors.length > 0) {
265
- return {
266
- error: errors[0],
267
- reason: reasons[0]
268
- };
318
+ return;
269
319
  }
270
- var isEmpty = values.every(isEmptyValue);
271
- if (isEmpty) {
272
- return {
273
- value: options.transformEmptyArray(values, {
274
- path: propertyPath
275
- })
276
- };
320
+
321
+ // If an empty substring was extracted, it means that there was an out-of-place separator.
322
+ if (!substring) {
323
+ errors.push('invalid');
324
+ reasons.push('syntax');
325
+ return;
326
+ }
327
+ var _parseValue = parseValue(substring, schemaEntry, options),
328
+ value = _parseValue.value,
329
+ isEmptyValue = _parseValue.isEmptyValue,
330
+ error = _parseValue.error,
331
+ reason = _parseValue.reason;
332
+ if (error) {
333
+ errors.push(error);
334
+ reasons.push(reason);
335
+ return;
336
+ }
337
+ if (isEmptyArray && !isEmptyValue) {
338
+ isEmptyArray = false;
277
339
  }
340
+ return value;
341
+ });
342
+ if (errors.length > 0) {
278
343
  return {
279
- value: values
344
+ error: errors[0],
345
+ reason: reasons[0]
280
346
  };
281
347
  }
282
- return parseValue(cellValue, schemaEntry, options);
348
+ return {
349
+ value: values,
350
+ isEmptyValue: isEmptyArray
351
+ };
283
352
  }
284
353
 
285
354
  /**
286
355
  * Converts textual value to a javascript typed value.
287
356
  * @param {any} value
288
357
  * @param {object} schemaEntry
289
- * @return {{ value: any, error: string }}
358
+ * @param {object} options
359
+ * @return {{ value?: any, isEmptyValue: boolean } | { error: string }}
290
360
  */
291
361
  export function parseValue(value, schemaEntry, options) {
362
+ // `null` values (i.e. empty cells) don't get parsed.
292
363
  if (value === null) {
293
364
  return {
294
- value: null
365
+ value: null,
366
+ isEmptyValue: true
295
367
  };
296
368
  }
369
+
370
+ // Parse the value according to the `type` that is specified in the schema entry.
297
371
  var result;
298
372
  if (schemaEntry.type) {
299
373
  result = parseValueOfType(value,
300
- // Supports parsing array types.
301
- // See `parseSeparatedSubstrings()` function for more details.
374
+ // Get the type of the value.
375
+ //
376
+ // Handle the case if it's a comma-separated value.
302
377
  // Example `type`: String[]
303
- // Input: 'Barack Obama, "String, with, colons", Donald Trump'
304
- // Output: ['Barack Obama', 'String, with, colons', 'Donald Trump']
378
+ // Example Input Value: 'Barack Obama, "String, with, colons", Donald Trump'
379
+ // Example Parsed Value: ['Barack Obama', 'String, with, colons', 'Donald Trump']
380
+ //
305
381
  Array.isArray(schemaEntry.type) ? schemaEntry.type[0] : schemaEntry.type, options);
306
382
  } else {
307
- // The default `type` is `String`.
383
+ // If the `type` is not specified for a given schema entry, the default one is `String`.
308
384
  result = {
309
385
  value: value
310
386
  };
311
387
  // throw new Error('Invalid schema entry: no `type` specified:\n\n' + JSON.stringify(schemaEntry, null, 2))
312
388
  }
313
389
 
314
- // If errored then return the error.
390
+ // If there was an error when parsing the value then return the error.
315
391
  if (result.error) {
316
392
  return result;
317
393
  }
318
394
 
319
- // Validate the value.
320
- if (result.value !== null) {
321
- // Perform `oneOf` validation.
322
- if (schemaEntry.oneOf && schemaEntry.oneOf.indexOf(result.value) < 0) {
395
+ // If the parsed value is empty, return it.
396
+ if (value === null) {
397
+ return {
398
+ value: null,
399
+ isEmptyValue: true
400
+ };
401
+ }
402
+
403
+ // Value is not empty.
404
+ // Validate it and return.
405
+
406
+ // Perform `oneOf` validation.
407
+ if (schemaEntry.oneOf) {
408
+ var errorAndReason = validateOneOf(result.value, schemaEntry.oneOf);
409
+ if (errorAndReason) {
410
+ return errorAndReason;
411
+ }
412
+ }
413
+
414
+ // Perform `validate()` validation.
415
+ if (schemaEntry.validate) {
416
+ try {
417
+ schemaEntry.validate(result.value);
418
+ } catch (error) {
323
419
  return {
324
- error: 'invalid',
325
- reason: 'unknown'
420
+ error: error.message
326
421
  };
327
422
  }
328
- // Perform `validate()` validation.
329
- if (schemaEntry.validate) {
330
- try {
331
- schemaEntry.validate(result.value);
332
- } catch (error) {
333
- return {
334
- error: error.message
335
- };
336
- }
337
- }
338
423
  }
339
- return result;
424
+
425
+ // Return the value.
426
+ return {
427
+ value: result.value,
428
+ isEmptyValue: isEmptyValue(result.value)
429
+ };
430
+ }
431
+ function validateOneOf(value, oneOf) {
432
+ if (oneOf.indexOf(value) < 0) {
433
+ return {
434
+ error: 'invalid',
435
+ reason: 'unknown'
436
+ };
437
+ }
340
438
  }
341
439
 
342
440
  /**
@@ -386,18 +484,22 @@ function parseValueUsingTypeParser(value, type) {
386
484
  var result = {
387
485
  error: error.message
388
486
  };
487
+ // Built-in types such as `Number` or `Date` may also report
488
+ // a specific `reason` of the error.
389
489
  if (error.reason) {
390
490
  result.reason = error.reason;
391
491
  }
392
492
  return result;
393
493
  }
394
494
  }
395
- export function getNextSubstring(string, endCharacter, startIndex) {
495
+
496
+ // Extracts a substring from a string.
497
+ export function getNextSubstring(string, separatorCharacter, startIndex) {
396
498
  var i = 0;
397
499
  var substring = '';
398
500
  while (startIndex + i < string.length) {
399
501
  var character = string[startIndex + i];
400
- if (character === endCharacter) {
502
+ if (character === separatorCharacter) {
401
503
  return [substring, i];
402
504
  }
403
505
  // Previously, it used to treat `"` character similar to how it's treated in `.csv` files:
@@ -424,27 +526,110 @@ export function getNextSubstring(string, endCharacter, startIndex) {
424
526
  * @param {string} string — A string of comma-separated substrings.
425
527
  * @return {string[]} An array of substrings.
426
528
  */
427
- export function parseSeparatedSubstrings(string, arrayValueSeparator) {
529
+ export function parseSeparatedSubstrings(string, separatorCharacter) {
428
530
  var elements = [];
429
531
  var index = 0;
430
532
  while (index < string.length) {
431
- var _getNextSubstring = getNextSubstring(string, arrayValueSeparator, index),
533
+ var _getNextSubstring = getNextSubstring(string, separatorCharacter, index),
432
534
  _getNextSubstring2 = _slicedToArray(_getNextSubstring, 2),
433
535
  substring = _getNextSubstring2[0],
434
536
  length = _getNextSubstring2[1];
435
- index += length + arrayValueSeparator.length;
537
+ index += length + separatorCharacter.length;
436
538
  elements.push(substring.trim());
437
539
  }
438
540
  return elements;
439
541
  }
542
+ function transformValue(value, isEmptyValue, path, options) {
543
+ if (isEmptyValue) {
544
+ if (isObject(value)) {
545
+ return options.transformEmptyObject(value, {
546
+ path: path
547
+ });
548
+ } else if (Array.isArray(value)) {
549
+ return options.transformEmptyArray(value, {
550
+ path: path
551
+ });
552
+ }
553
+ }
554
+ return value;
555
+ }
556
+ function getPropertyPath(propertyName, parentObjectPath) {
557
+ return "".concat(parentObjectPath ? parentObjectPath + '.' : '').concat(propertyName);
558
+ }
559
+
560
+ // Recursively runs `required` validations for the parsed data row tree.
561
+ function runPendingRequiredValidations(schemaEntry, value, isEmptyValue, errors, children, parentObjectIsRequired, parentObjectValue, parentObjectValueIsEmpty, parentObjectErrors) {
562
+ var requiredErrors = [];
563
+
564
+ // See if this property is required.
565
+ var isRequired = isPropertyRequired(schemaEntry, parentObjectIsRequired, parentObjectValue, parentObjectValueIsEmpty, parentObjectErrors);
566
+
567
+ // If this property is required and empty, create a "required" error.
568
+ if (isRequired && isEmptyValue) {
569
+ requiredErrors.push(createError({
570
+ error: 'required',
571
+ column: schemaEntry.column,
572
+ valueType: schemaEntry.type,
573
+ value: value
574
+ }));
575
+ }
576
+
577
+ // Run `required` validations of the children.
578
+ if (children) {
579
+ for (var _iterator2 = _createForOfIteratorHelperLoose(children), _step2; !(_step2 = _iterator2()).done;) {
580
+ var child = _step2.value;
581
+ var requiredErrorsOfChild = runPendingRequiredValidations(child.schemaEntry, child.value, child.isEmptyValue, child.errors, child.children,
582
+ // The following properties describe the parent object of the `child`,
583
+ // i.e. the current (iterated) object.
584
+ isRequired, value, isEmptyValue, errors);
585
+ if (requiredErrorsOfChild) {
586
+ requiredErrors = requiredErrors.concat(requiredErrorsOfChild);
587
+ }
588
+ }
589
+ }
590
+ if (requiredErrors.length > 0) {
591
+ return requiredErrors;
592
+ }
593
+ }
594
+ function isPropertyRequired(schemaEntry, parentObjectIsRequired, parentObjectValue, parentObjectValueIsEmpty, parentObjectErrors) {
595
+ // If the parent object is marked as `required: false` then it's allowed
596
+ // to be absent entirely from the input data. If that's the case,
597
+ // i.e. if the parent object is absent entirely from the input data,
598
+ // then any descendant properties of such object are allowed to be absent too,
599
+ // which means that they should also be considered being `required: false`.
600
+ //
601
+ // Also, if the parent object couldn't be parsed due to some non-`required` errors,
602
+ // it can't be known whether it's actually empty or not. In case of such uncertainty,
603
+ // the code shouldn't attempt to be overly smart and do things that might not be necessary,
604
+ // so such parent object is just assumed to be empty in order to not falsly trigger
605
+ // any `required` validations that otherwise wouldn't have been run.
606
+ // In other words, skipping some `required` validations is better than
607
+ // running `required` validations that shouldn't have been run.
608
+ //
609
+ if (parentObjectIsRequired === false && (parentObjectValueIsEmpty || parentObjectErrors)) {
610
+ return false;
611
+ }
612
+ return schemaEntry.required && (typeof schemaEntry.required === 'boolean' ? schemaEntry.required :
613
+ // If there were any non-`required` errors when parsing the parent object,
614
+ // the `parentObject` will be `undefined`. In that case, "complex" `required()`
615
+ // validations — the ones where `required` is a function — can't really be run
616
+ // because those validations assume a fully and correctly parsed parent object
617
+ // be passed as an argument, and the thing is that the `parentObject` is unknown.
618
+ // As a result, only "basic" `required` validations could be run,
619
+ // i.e. the ones where `required` is just a boolean, and "complex" `required`
620
+ // validations, i.e. the ones where `required` is a functions, should be skipped,
621
+ // because it's better to skip some `required` errors than to trigger falsy ones.
622
+ parentObjectErrors ? false : schemaEntry.required(parentObjectValue));
623
+ }
440
624
  function createError(_ref2) {
441
- var schemaEntry = _ref2.schemaEntry,
625
+ var column = _ref2.column,
626
+ valueType = _ref2.valueType,
442
627
  value = _ref2.value,
443
628
  errorMessage = _ref2.error,
444
629
  reason = _ref2.reason;
445
630
  var error = {
446
631
  error: errorMessage,
447
- column: schemaEntry.column,
632
+ column: column,
448
633
  value: value
449
634
  };
450
635
  if (reason) {
@@ -452,14 +637,14 @@ function createError(_ref2) {
452
637
  }
453
638
  // * Regular values specify a `type?` property, which is included in the `error` object.
454
639
  // * Nested objects specify a `schema` property, which is not included in the `error` object.
455
- if (schemaEntry.type) {
456
- error.type = schemaEntry.type;
640
+ if (valueType) {
641
+ error.type = valueType;
457
642
  }
458
643
  return error;
459
644
  }
460
645
  function validateSchema(schema) {
461
- for (var _i4 = 0, _Object$keys2 = Object.keys(schema); _i4 < _Object$keys2.length; _i4++) {
462
- var key = _Object$keys2[_i4];
646
+ for (var _i2 = 0, _Object$keys2 = Object.keys(schema); _i2 < _Object$keys2.length; _i2++) {
647
+ var key = _Object$keys2[_i2];
463
648
  var schemaEntry = schema[key];
464
649
  // Validate that the `schema` is not using a deprecated `type: nestedSchema` format.
465
650
  if (_typeof(schemaEntry.type) === 'object' && !Array.isArray(schemaEntry.type)) {
@@ -472,6 +657,30 @@ function validateSchema(schema) {
472
657
  }
473
658
  }
474
659
  }
660
+
661
+ // A nested object could have a `required` property but the only allowed value is `false`.
662
+ // The reason why `true` value is not allowed is because in case of a "required" error
663
+ // there's no single column title corresponding to such nested object, and column title
664
+ // is required to create a "required" error.
665
+ validateObjectSchemaRequiredProperty(schema, undefined);
666
+ }
667
+ function validateObjectSchemaRequiredProperty(schema, required) {
668
+ if (required !== undefined && required !== false) {
669
+ throw new Error("In a schema, a nested object can have a `required` property but the only allowed value is `undefined` or `false`. Otherwise, a \"required\" error for a nested object would have to include a specific `column` title and a nested object doesn't have one. You've specified the following `required`: ".concat(required));
670
+ }
671
+ // For each property of the described object.
672
+ for (var _i3 = 0, _Object$keys3 = Object.keys(schema); _i3 < _Object$keys3.length; _i3++) {
673
+ var key = _Object$keys3[_i3];
674
+ // If this property is itself an object.
675
+ if (isObject(schema[key].schema)) {
676
+ // Validate that a `column` property can't coexist with a `schema` property.
677
+ if (schema[key].column) {
678
+ throw new Error("In a schema, `column` property is only allowed when describing a property value rather than a nested object. Key: ".concat(key, ". Schema:\n").concat(JSON.stringify(schema[key], null, 2)));
679
+ }
680
+ // Recurse into the child object.
681
+ validateObjectSchemaRequiredProperty(schema[key].schema, schema[key].required);
682
+ }
683
+ }
475
684
  }
476
685
  function isEmptyValue(value) {
477
686
  return value === undefined || value === null;
@@ -488,7 +697,7 @@ var DEFAULT_OPTIONS = {
488
697
  transformEmptyArray: function transformEmptyArray() {
489
698
  return null;
490
699
  },
491
- arrayValueSeparator: ','
700
+ separatorCharacter: ','
492
701
  };
493
702
  function applyDefaultOptions(options) {
494
703
  if (options) {
@@ -497,4 +706,11 @@ function applyDefaultOptions(options) {
497
706
  return DEFAULT_OPTIONS;
498
707
  }
499
708
  }
709
+
710
+ // This `value` marks the start of a tree structure that is parsed from a given data row.
711
+ var PARSED_OBJECT_TREE_START = {};
712
+ var objectConstructor = {}.constructor;
713
+ function isObject(object) {
714
+ return object !== undefined && object !== null && object.constructor === objectConstructor;
715
+ }
500
716
  //# sourceMappingURL=parseData.js.map