parse-nested-form-data 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.
@@ -0,0 +1,393 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var webFile = require('@remix-run/web-file');
6
+
7
+ /**
8
+ * @name parse-nested-form-data
9
+ * @license MIT license.
10
+ * @copyright (c) 2022 Christian Schurr
11
+ * @author Christian Schurr <chris@schurr.dev>
12
+ */
13
+
14
+ /**
15
+ * Thrown when a path is used multiple times or has missmatching path parts.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * const formData = new FormData()
20
+ * formData.append('a[0]', 'b')
21
+ * formData.append('a[0]', 'c')
22
+ * parseFormData(formData)
23
+ * // throws DuplicateKeyError('a[0]')
24
+ * ```
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * const formData = new FormData()
29
+ * formData.append('a', 'b')
30
+ * formData.append('a', 'c')
31
+ * parseFormData(formData)
32
+ * // throws DuplicateKeyError('a')
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * const formData = new FormData()
37
+ * formData.append('a', 'b')
38
+ * formData.append('a[]', 'c')
39
+ * parseFormData(formData)
40
+ * // throws DuplicateKeyError('a[]')
41
+ * ```
42
+ *
43
+ */
44
+ class DuplicateKeyError extends Error {
45
+ constructor(key) {
46
+ super(`Duplicate key at path part ${key}`);
47
+ this.key = void 0;
48
+ this.key = key;
49
+ }
50
+ }
51
+ /**
52
+ * Thrown when an array is used at the same path with an order parameter and
53
+ * without an order parameter.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * const formData = new FormData()
58
+ * formData.append('a[0]', 'a')
59
+ * formData.append('a[]', 'b')
60
+ * parseFormData(formData)
61
+ * // => throws `MixedArrayError(a[])`
62
+ * ```
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * const formData = new FormData()
67
+ * formData.append('a[]', 'a')
68
+ * formData.append('a[0]', 'b')
69
+ * parseFormData(formData)
70
+ * // => throws `MixedArrayError(a[0])`
71
+ * ```
72
+ */
73
+ class MixedArrayError extends Error {
74
+ constructor(key) {
75
+ super(`Mixed array at path part ${key}`);
76
+ this.key = void 0;
77
+ this.key = key;
78
+ }
79
+ }
80
+ function isJsonObject(val) {
81
+ return typeof val === 'object' && !Array.isArray(val) && val !== null && !(val instanceof webFile.File);
82
+ }
83
+
84
+ /**
85
+ * Default Transformer for `parseFormData`.
86
+ *
87
+ * Transforms a FormData Entry into a path and a `JsonLeafValue`.
88
+ *
89
+ * - `path` starts with `+` -> transform value to `number`
90
+ * - `path` starts with `&` -> transform value to `boolean`
91
+ * - `path` starts with `-` -> transform value to `null`
92
+ *
93
+ * @example
94
+ * ```ts
95
+ * const entry = ['a[0]', 'b']
96
+ * const result = defaultTransform(entry)
97
+ * // => {path: 'a[0]', value: 'b'}
98
+ * ```
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * const entry = ['+a[0]', '1']
103
+ * const result = defaultTransform(entry)
104
+ * // => {path: 'a[0]', value: 1}
105
+ * ```
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * const entry = ['&a[0]', 'true']
110
+ * const result = defaultTransform(entry)
111
+ * // => {path: 'a[0]', value: true}
112
+ * ```
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * const entry = ['-a[0]', 'null']
117
+ * const result = defaultTransform(entry)
118
+ * // => {path: 'a[0]', value: null}
119
+ * ```
120
+ *
121
+ * @example
122
+ * ```ts
123
+ * const entry = ['a[0]', new File([''], 'file.txt')]
124
+ * const result = defaultTransform(entry)
125
+ * // => {path: 'a[0]', value: File}
126
+ * ```
127
+ *
128
+ *
129
+ * @param entry [path, value]: the FormData entry
130
+ * @returns the path and the transformed value
131
+ */
132
+ function defaultTransform(entry) {
133
+ let path = entry[0];
134
+ let value = entry[1];
135
+ if (path.startsWith('+')) {
136
+ path = path.slice(1);
137
+ value = Number(value);
138
+ } else if (path.startsWith('&')) {
139
+ path = path.slice(1);
140
+ value = value === 'on' || value === 'true' || Boolean(Number(value));
141
+ } else if (path.startsWith('-')) {
142
+ path = path.slice(1);
143
+ value = null;
144
+ }
145
+ return {
146
+ path,
147
+ value
148
+ };
149
+ }
150
+ /**
151
+ *
152
+ * Transforms a FormData path into an array of `PathPart`s.
153
+ *
154
+ * @param path - the path to extract the path parts from
155
+ * @returns {Array<PathPart>} the extracted path parts
156
+ *
157
+ * @example
158
+ * ```ts
159
+ * const path = 'a[0].b'
160
+ * const result = extractPathParts(path)
161
+ * // => [{path: 'a', type: 'object, default: [], pathToPart: 'a'},
162
+ * // {path: '0', type: 'array', default: {}, pathToPart: 'a[0]'},
163
+ * // {path: 'b', type: 'object', default: {}, pathToPart: 'a[0].b'}]
164
+ * ```
165
+ *
166
+ * @example
167
+ * ```ts
168
+ * const path = 'a.b'
169
+ * const result = extractPathParts(path)
170
+ * // => [{path: 'a', type: 'object, default: {}, pathToPart: 'a'},
171
+ * // {path: 'b', type: 'object', default: {}, pathToPart: 'a.b'}]
172
+ * ```
173
+ *
174
+ * @example
175
+ * ```ts
176
+ * const path = 'a[][0]'
177
+ * const result = extractPathParts(path)
178
+ * // => [{path: 'a', type: 'object, default: [], pathToPart: 'a'},
179
+ * // {path: '', type: 'array', default: [], pathToPart: 'a[]'},
180
+ * // {path: '0', type: 'array', default: {}, pathToPart: 'a[][0]'}]
181
+ * ```
182
+ *
183
+ *
184
+ */
185
+ function extractPathParts(path) {
186
+ const re = /((?<array>\d*)\]|(?<pathPart>[^.[]+))(?<nextType>\[|\.|$)/g;
187
+ return Array.from(path.matchAll(re)).map(match => {
188
+ // self casted RegexExpMatchArray to custom
189
+ const typedMatch = match;
190
+ const {
191
+ array,
192
+ pathPart,
193
+ nextType
194
+ } = typedMatch.groups;
195
+ const type = array === undefined ? 'object' : 'array';
196
+ const nextDefault = nextType === '[' ? [] : {};
197
+ return {
198
+ path: array ?? pathPart,
199
+ type,
200
+ default: nextDefault,
201
+ pathToPart: path.slice(0, typedMatch.index + typedMatch[1].length)
202
+ };
203
+ });
204
+ }
205
+
206
+ /**
207
+ *
208
+ * Returns the value accessed via `pathPart` in the `currentPathObject`
209
+ * and a setter function to set the value in the `currentPathObject` via the
210
+ * provided `pathPart`.
211
+ *
212
+ * @param pathPart - the path part to get the setter and getter for
213
+ * @param currentPathObject - the object at the current path (before the path part)
214
+ * @param arraysWithOrder - a set of arrays that have an order
215
+ * @returns the setter and getter for the path part
216
+ *
217
+ * @example
218
+ * ```ts
219
+ * const pathPart = {path: 'a', type: 'object', default: {}, pathToPart: 'a'}
220
+ * const currentPathObject = {}
221
+ * const arraysWithOrder = new Set()
222
+ * const [value, setValue] = getSetterAndGetter(pathPart, currentPathObject, arraysWithOrder)
223
+ * setValue('b')
224
+ * // => currentPathObject = {a: 'b'}
225
+ * ```
226
+ *
227
+ * @example
228
+ * ```ts
229
+ * const pathPart = {path: '0', type: 'array', default: [], pathToPart: 'a[0]'}
230
+ * const currentPathObject = {a: []}
231
+ * const arraysWithOrder = new Set()
232
+ * const [value, setValue] = getSetterAndGetter(pathPart, currentPathObject, arraysWithOrder)
233
+ * setValue('b')
234
+ * // => currentPathObject = {a: ['b']}
235
+ * ```
236
+ *
237
+ */
238
+ function handlePathPart(pathPart, currentPathObject, arraysWithOrder) {
239
+ if (pathPart.type === 'object') {
240
+ if (Array.isArray(currentPathObject)) {
241
+ throw new DuplicateKeyError(pathPart.pathToPart);
242
+ }
243
+ const currentObject = currentPathObject;
244
+ return [currentObject[pathPart.path], val => currentObject[pathPart.path] = val];
245
+ }
246
+ if (!Array.isArray(currentPathObject)) {
247
+ throw new DuplicateKeyError(pathPart.pathToPart);
248
+ }
249
+ const currentArray = currentPathObject;
250
+ const isOrdered = pathPart.path !== '';
251
+ const isOrderedArray = arraysWithOrder.has(currentArray);
252
+ if (isOrdered) {
253
+ arraysWithOrder.add(currentArray);
254
+ }
255
+ if (!isOrdered && isOrderedArray || isOrdered && !isOrderedArray && currentArray.length > 0) {
256
+ throw new MixedArrayError(pathPart.pathToPart);
257
+ }
258
+ const order = isOrdered ? Number(pathPart.path) : currentArray.length;
259
+ return [currentArray[order], val => currentArray[order] = val];
260
+ }
261
+
262
+ /**
263
+ *
264
+ * Parses a FormData object to a JSON object. This is done by parsing the `name`
265
+ * attribute of each `FormDataEntryValue` and then inserting the value at the
266
+ * path. Also by default the start of the path is used to transform the value.
267
+ *
268
+ *
269
+ * In front of the whole `key`:
270
+ * - `+` => parse to `Number`
271
+ * - `-` => set value to `null`
272
+ * - `&` => parse to `Boolean`
273
+ *
274
+ * - `.` between path parts => nest into `objects`
275
+ * - `[\d*]` after path part => push to array in order `\d` or push to end if `[]`
276
+ *
277
+
278
+ *
279
+ * @example
280
+ * ```ts
281
+ * const formData = new FormData()
282
+ * formData.append('+a', '1')
283
+ * formData.append('&b', 'true')
284
+ * formData.append('-c', 'null')
285
+ * formData.append('d', 'foo')
286
+ * parseFormData(formData, defaultTransform)
287
+ * // => {a: 1, b: true, c: null, d: 'foo'}
288
+ * ```
289
+ *
290
+ * @example
291
+ * ```ts
292
+ * const formData = new FormData()
293
+ * formData.append('a.b', 'foo')
294
+ * parseFormData(formData)
295
+ * // => {a: {b: 'foo'}}
296
+ * ```
297
+ *
298
+ * @example
299
+ * ```ts
300
+ * const formData = new FormData()
301
+ * formData.append('a[0]', 'foo')
302
+ * formData.append('a[1]', 'bar')
303
+ * parseFormData(formData)
304
+ * // => {a: ['foo', 'bar']}
305
+ * ```
306
+ *
307
+ * @example
308
+ * ```ts
309
+ * const formData = new FormData()
310
+ * formData.append('a[]', 'foo')
311
+ * formData.append('a[]', 'bar')
312
+ * parseFormData(formData)
313
+ * // => {a: ['foo', 'bar']}
314
+ * ```
315
+ *
316
+ * @example
317
+ * ```ts
318
+ * const formData = new FormData()
319
+ * formData.append('a[0]', 'foo')
320
+ * parseFormData(formData, {transformEntry: (path, value) => {path, value: value + 'bar'}})
321
+ * // => {a: ['foobar']}
322
+ * ```
323
+ *
324
+ * @example
325
+ * ```ts
326
+ * const formData = new FormData()
327
+ * formData.append('a[0]', 'foo')
328
+ * formData.append('a[1]', '')
329
+ * parseFormData(formData, {removeEmptyString: true})
330
+ * // => {a: ['foo']}
331
+ * ```
332
+ *
333
+ * @param {Iterable<[string, string | File]>} formData - an iterator of an [`path`, `value`] tuple
334
+ * - `path` := `^(\+|\-|\&)?([^\.]+?(\[\d*\])*)(\.[^\.]+?(\[\d*\])*)*$` (e.g. `+a[][1].b`)
335
+ * - `value` := `string` or `File`
336
+ * @param {ParseFormDataOptions} options - options for parsing the form data
337
+ * - `transformEntry` - a function to transform the path and the value before
338
+ * inserting the value at the path in the resulting object (default: `defaultTransform`)
339
+ * - `removeEmptyString` - if `true` removes all entries where the value is an empty string
340
+ * @returns {JsonObject} the parsed JSON object
341
+ * @throws `DuplicateKeyError` if
342
+ * - a path part is an object and the path part is already defined as an object
343
+ * - a path part is an array and the path part is already defined as an array
344
+ * @throws `MixedArrayError` if at a specific path part an unordered array is
345
+ * defined and at a later path part an ordered array is defined or vice versa
346
+ * - e.g. `a[0]` and `a[]`
347
+ * - e.g. `a[]` and `a[0]`
348
+ */
349
+ function parseFormData(formData, _temp) {
350
+ let {
351
+ removeEmptyString = false,
352
+ transformEntry = defaultTransform
353
+ } = _temp === void 0 ? {} : _temp;
354
+ const result = {};
355
+
356
+ // all arrays we need to squash (in place) later
357
+ const arraysWithOrder = new Set();
358
+ for (const entry of Array.from(formData)) {
359
+ if (removeEmptyString && entry[1] === '') continue;
360
+ const {
361
+ path,
362
+ value
363
+ } = transformEntry(entry, defaultTransform);
364
+ const pathParts = extractPathParts(path);
365
+ let currentPathObject = result;
366
+ pathParts.forEach((pathPart, idx) => {
367
+ const [nextPathValue, setNextPathValue] = handlePathPart(pathPart, currentPathObject, arraysWithOrder);
368
+ if (pathParts.length - 1 === idx) {
369
+ if (nextPathValue !== undefined) {
370
+ throw new DuplicateKeyError(pathPart.pathToPart);
371
+ }
372
+ setNextPathValue(value);
373
+ } else {
374
+ if (nextPathValue !== undefined && !isJsonObject(nextPathValue) && !Array.isArray(nextPathValue)) {
375
+ throw new DuplicateKeyError(pathPart.pathToPart);
376
+ }
377
+ const nextPathObject = nextPathValue ?? pathPart.default;
378
+ currentPathObject = nextPathObject;
379
+ setNextPathValue(nextPathObject);
380
+ }
381
+ });
382
+ }
383
+ for (const orderedArray of Array.from(arraysWithOrder)) {
384
+ // replace array with a squashed array
385
+ // array.flat(0) will remove all empty slots (e.g. [0, , 1] => [0, 1])
386
+ orderedArray.splice(0, orderedArray.length, ...orderedArray.flat(0));
387
+ }
388
+ return result;
389
+ }
390
+
391
+ exports.DuplicateKeyError = DuplicateKeyError;
392
+ exports.MixedArrayError = MixedArrayError;
393
+ exports.parseFormData = parseFormData;