parse-nested-form-data 1.0.0 → 1.1.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,398 +1,608 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@remix-run/web-file')) :
3
- typeof define === 'function' && define.amd ? define(['exports', '@remix-run/web-file'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.parseNestedFormData = {}, global.RemixRunWebFile));
5
- })(this, (function (exports, webFile) { 'use strict';
1
+ /**
2
+ * @name parse-nested-form-data
3
+ * @license MIT license.
4
+ * @copyright (c) 2022 Christian Schurr
5
+ * @author Christian Schurr <chris@schurr.dev>
6
+ */
7
+ (function(global, factory) {
8
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.parseNestedFormData = {}));
9
+ })(this, function(exports) {
10
+ Object.defineProperties(exports, {
11
+ __esModule: { value: true },
12
+ [Symbol.toStringTag]: { value: "Module" }
13
+ });
14
+ // src/errors.ts
15
+ /**
16
+ * Thrown when a path is used multiple times or has mismatching path parts.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * const formData = new FormData()
21
+ * formData.append('a[0]', 'b')
22
+ * formData.append('a[0]', 'c')
23
+ * parseFormData(formData)
24
+ * // throws DuplicateKeyError('a[0]')
25
+ * ```
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * const formData = new FormData()
30
+ * formData.append('a', 'b')
31
+ * formData.append('a', 'c')
32
+ * parseFormData(formData)
33
+ * // throws DuplicateKeyError('a')
34
+ * ```
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * const formData = new FormData()
39
+ * formData.append('a', 'b')
40
+ * formData.append('a[]', 'c')
41
+ * parseFormData(formData)
42
+ * // throws DuplicateKeyError('a[]')
43
+ * ```
44
+ *
45
+ */
46
+ var DuplicateKeyError = class extends Error {
47
+ constructor(key) {
48
+ super(`Duplicate key at path part ${key}`);
49
+ this.name = "DuplicateKeyError";
50
+ this.key = key;
51
+ }
52
+ };
53
+ /**
54
+ * Thrown when an array is used at the same path with an order parameter and
55
+ * without an order parameter.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * const formData = new FormData()
60
+ * formData.append('a[0]', 'a')
61
+ * formData.append('a[]', 'b')
62
+ * parseFormData(formData)
63
+ * // => throws `MixedArrayError(a[])`
64
+ * ```
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * const formData = new FormData()
69
+ * formData.append('a[]', 'a')
70
+ * formData.append('a[0]', 'b')
71
+ * parseFormData(formData)
72
+ * // => throws `MixedArrayError(a[0])`
73
+ * ```
74
+ */
75
+ var MixedArrayError = class extends Error {
76
+ constructor(key) {
77
+ super(`Mixed array at path part ${key}`);
78
+ this.name = "MixedArrayError";
79
+ this.key = key;
80
+ }
81
+ };
82
+ /**
83
+ * Cuts a path to 100 characters plus `...`, so a huge path from a client
84
+ * doesn't end up in full in logs or error responses.
85
+ */
86
+ function shortKey(key) {
87
+ return key.length > 100 ? `${key.slice(0, 100)}...` : key;
88
+ }
89
+ /**
90
+ * Thrown when an object path part is `__proto__`, `constructor` or
91
+ * `prototype`, which could modify `Object.prototype`. The names are rejected
92
+ * at any position in the path. Entries with other names on `Object.prototype`
93
+ * (`toString`, ...) are removed instead (see `parseFormData`).
94
+ * `key` is the path up to the forbidden part, cut to 100 characters plus `...`
95
+ * when it's longer.
96
+ *
97
+ * @example
98
+ * ```ts
99
+ * const formData = new FormData()
100
+ * formData.append('__proto__.polluted', 'yes')
101
+ * parseFormData(formData)
102
+ * // throws ForbiddenKeyError('__proto__')
103
+ * ```
104
+ */
105
+ var ForbiddenKeyError = class extends Error {
106
+ constructor(key) {
107
+ key = shortKey(key);
108
+ super(`Forbidden key at path part ${key}`);
109
+ this.name = "ForbiddenKeyError";
110
+ this.key = key;
111
+ }
112
+ };
113
+ /**
114
+ * Thrown when a path has more path parts than the `depth` option allows.
115
+ * `key` is the path up to the first path part over the limit, cut to
116
+ * 100 characters plus `...` when it's longer.
117
+ * Within one entry the depth is checked first, so a path that's too deep throws
118
+ * `DepthLimitError` even if it would also throw another error, like a
119
+ * `ForbiddenKeyError` for `__proto__`.
120
+ *
121
+ * @example
122
+ * ```ts
123
+ * const formData = new FormData()
124
+ * formData.append('a.b[0].c', 'x')
125
+ * parseFormData(formData, {depth: 2})
126
+ * // throws DepthLimitError('a.b[0]')
127
+ * ```
128
+ */
129
+ var DepthLimitError = class extends Error {
130
+ constructor(key) {
131
+ key = shortKey(key);
132
+ super(`Depth limit exceeded at path part ${key}`);
133
+ this.name = "DepthLimitError";
134
+ this.key = key;
135
+ }
136
+ };
137
+ /**
138
+ * Thrown when an array index in a path is larger than `4294967294`, the
139
+ * largest index a JavaScript array can hold.
140
+ * `key` is the path up to that array part, cut to 100 characters plus `...`
141
+ * when it's longer.
142
+ *
143
+ * @example
144
+ * ```ts
145
+ * const formData = new FormData()
146
+ * formData.append('a[4294967295]', 'b')
147
+ * parseFormData(formData)
148
+ * // throws InvalidPathError('a[4294967295]')
149
+ * ```
150
+ */
151
+ var InvalidPathError = class extends Error {
152
+ constructor(key) {
153
+ key = shortKey(key);
154
+ super(`Invalid path at path part ${key}`);
155
+ this.name = "InvalidPathError";
156
+ this.key = key;
157
+ }
158
+ };
159
+ // src/path-parts.ts
160
+ /**
161
+ * Finds the `]` that ends the bracket part starting at the `[` at `open`.
162
+ * Returns -1 if this `[` is not a bracket part but a normal character of the key.
163
+ *
164
+ * Brackets can be nested: in `a[b[c]]` the last `]` belongs to
165
+ * the first `[`.
166
+ *
167
+ * Special cases:
168
+ * - Some `[` are never closed. The part then ends at the last `]`:
169
+ * `a[[0]` => key `[0`.
170
+ * - If there is no `]` after the `[` at all, the `[` is a normal character:
171
+ * `a[0` => key `a[0`.
172
+ * - The same goes for a `]` without a `[`: `a]b` => key `a]b`, and
173
+ * `a[b]]` => key `]` inside `b`.
174
+ *
175
+ * The scan stops at the returned `]`. The caller continues from there, so no
176
+ * character of the path is scanned twice.
177
+ */
178
+ function closeOf(path, open, lastClose) {
179
+ if (open > lastClose) return -1;
180
+ let nesting = 0;
181
+ for (let idx = open; idx < lastClose; idx++) if (path[idx] === "[") nesting++;
182
+ else if (path[idx] === "]" && --nesting === 0) return idx;
183
+ return lastClose;
184
+ }
185
+ /**
186
+ *
187
+ * Transforms a FormData path into an array of `PathPart`s.
188
+ *
189
+ * @param path - the path to extract the path parts from
190
+ * @param depth - the maximum number of path parts (default: `Infinity`)
191
+ * @returns {Array<PathPart>} the extracted path parts
192
+ * @throws `DepthLimitError` if the path has more path parts than `depth`, at
193
+ * the first part over the limit
194
+ *
195
+ * @example
196
+ * ```ts
197
+ * const path = 'a[0].b'
198
+ * const result = extractPathParts(path)
199
+ * // => [{path: 'a', type: 'object', default: [], pathToPart: 'a'},
200
+ * // {path: '0', type: 'array', default: {}, pathToPart: 'a[0]'},
201
+ * // {path: 'b', type: 'object', default: {}, pathToPart: 'a[0].b'}]
202
+ * ```
203
+ *
204
+ * @example
205
+ * ```ts
206
+ * const path = 'a.b'
207
+ * const result = extractPathParts(path)
208
+ * // => [{path: 'a', type: 'object', default: {}, pathToPart: 'a'},
209
+ * // {path: 'b', type: 'object', default: {}, pathToPart: 'a.b'}]
210
+ * ```
211
+ *
212
+ * @example
213
+ * ```ts
214
+ * const path = 'a[b][0]'
215
+ * const result = extractPathParts(path)
216
+ * // => [{path: 'a', type: 'object', default: {}, pathToPart: 'a'},
217
+ * // {path: 'b', type: 'object', default: [], pathToPart: 'a[b]'},
218
+ * // {path: '0', type: 'array', default: {}, pathToPart: 'a[b][0]'}]
219
+ * ```
220
+ *
221
+ * @example
222
+ * ```ts
223
+ * const path = 'a[][0]'
224
+ * const result = extractPathParts(path)
225
+ * // => [{path: 'a', type: 'object', default: [], pathToPart: 'a'},
226
+ * // {path: '', type: 'array', default: [], pathToPart: 'a[]'},
227
+ * // {path: '0', type: 'array', default: {}, pathToPart: 'a[][0]'}]
228
+ * ```
229
+ *
230
+ *
231
+ */
232
+ function extractPathParts(path, depth = Infinity) {
233
+ const lastClose = path.lastIndexOf("]");
234
+ const parts = [];
235
+ const addPart = (key, type, end) => {
236
+ if (key === "" && type === "object") return;
237
+ if (parts.length === depth) throw new DepthLimitError(path.slice(0, end));
238
+ parts.push({
239
+ path: key,
240
+ type,
241
+ default: {},
242
+ pathToPart: path.slice(0, end)
243
+ });
244
+ };
245
+ let start = 0;
246
+ for (let idx = 0; idx < path.length; idx++) {
247
+ const close = path[idx] === "[" ? closeOf(path, idx, lastClose) : -1;
248
+ if (path[idx] !== "." && close < idx) continue;
249
+ addPart(path.slice(start, idx), "object", idx);
250
+ if (close > idx) {
251
+ const key = path.slice(idx + 1, close);
252
+ addPart(key, /^\d*$/.test(key) ? "array" : "object", close + 1);
253
+ idx = close;
254
+ }
255
+ start = idx + 1;
256
+ }
257
+ addPart(path.slice(start), "object", path.length);
258
+ parts.forEach((part, idx) => {
259
+ if (parts[idx + 1]?.type === "array") part.default = [];
260
+ });
261
+ return parts;
262
+ }
263
+ // src/transform.ts
264
+ /**
265
+ * Default Transformer for `parseFormData`.
266
+ *
267
+ * Transforms a FormData Entry into a path and a `JsonLeafValue`.
268
+ *
269
+ * - `path` starts with `+` -> transform value to `number`
270
+ * - `path` starts with `&` -> transform value to `boolean`
271
+ * - `path` starts with `-` -> transform value to `null`
272
+ *
273
+ * @example
274
+ * ```ts
275
+ * const entry = ['a[0]', 'b']
276
+ * const result = defaultTransform(entry)
277
+ * // => {path: 'a[0]', value: 'b'}
278
+ * ```
279
+ *
280
+ * @example
281
+ * ```ts
282
+ * const entry = ['+a[0]', '1']
283
+ * const result = defaultTransform(entry)
284
+ * // => {path: 'a[0]', value: 1}
285
+ * ```
286
+ *
287
+ * @example
288
+ * ```ts
289
+ * const entry = ['&a[0]', 'true']
290
+ * const result = defaultTransform(entry)
291
+ * // => {path: 'a[0]', value: true}
292
+ * ```
293
+ *
294
+ * @example
295
+ * ```ts
296
+ * const entry = ['-a[0]', 'null']
297
+ * const result = defaultTransform(entry)
298
+ * // => {path: 'a[0]', value: null}
299
+ * ```
300
+ *
301
+ * @example
302
+ * ```ts
303
+ * const entry = ['a[0]', new File([''], 'file.txt')]
304
+ * const result = defaultTransform(entry)
305
+ * // => {path: 'a[0]', value: File}
306
+ * ```
307
+ *
308
+ *
309
+ * @param entry [path, value]: the FormData entry
310
+ * @returns the path and the transformed value
311
+ */
312
+ function defaultTransform(entry) {
313
+ let path = entry[0];
314
+ let value = entry[1];
315
+ if (path.startsWith("+")) {
316
+ path = path.slice(1);
317
+ value = Number(value);
318
+ } else if (path.startsWith("&")) {
319
+ path = path.slice(1);
320
+ value = value === "on" || value === "true" || Boolean(Number(value));
321
+ } else if (path.startsWith("-")) {
322
+ path = path.slice(1);
323
+ value = null;
324
+ }
325
+ return {
326
+ path,
327
+ value
328
+ };
329
+ }
330
+ // src/index.ts
331
+ const FORBIDDEN_OBJECT_KEYS = /* @__PURE__ */ new Set([
332
+ "__proto__",
333
+ "constructor",
334
+ "prototype"
335
+ ]);
336
+ const MAX_ARRAY_INDEX = 4294967294;
337
+ function isPrototypeKey(key) {
338
+ return Object.getOwnPropertyDescriptor(Object.prototype, key) !== void 0;
339
+ }
340
+ /**
341
+ * Detects `File` and `Blob` values by their `Symbol.toStringTag`, which works
342
+ * for native instances, polyfills (e.g. `@remix-run/web-file`) and values from
343
+ * other realms, where `instanceof` would fail.
344
+ */
345
+ function isFileLike(val) {
346
+ const tag = Object.prototype.toString.call(val);
347
+ return tag === "[object File]" || tag === "[object Blob]";
348
+ }
349
+ function isJsonObject(val) {
350
+ return typeof val === "object" && !Array.isArray(val) && val !== null && !isFileLike(val);
351
+ }
352
+ /**
353
+ *
354
+ * Returns the value accessed via `pathPart` in the `currentPathObject`,
355
+ * a setter function to set the value in the `currentPathObject` via the
356
+ * provided `pathPart`, and the key (object key or array index) it uses.
357
+ *
358
+ * @param pathPart - the path part to get the value, setter and key for
359
+ * @param currentPathObject - the object at the current path (before the path part)
360
+ * @param arraysWithOrder - a set of arrays that have an order
361
+ * @returns the current value, a setter for it, and the key (object key or
362
+ * array index) in `currentPathObject`
363
+ *
364
+ * @example
365
+ * ```ts
366
+ * const pathPart = {path: 'a', type: 'object', default: {}, pathToPart: 'a'}
367
+ * const currentPathObject = {}
368
+ * const arraysWithOrder = new Set()
369
+ * const [value, setValue, key] = handlePathPart(pathPart, currentPathObject, arraysWithOrder)
370
+ * setValue('b')
371
+ * // => currentPathObject = {a: 'b'}, key = 'a'
372
+ * ```
373
+ *
374
+ * @example
375
+ * ```ts
376
+ * const pathPart = {path: '0', type: 'array', default: [], pathToPart: 'a[0]'}
377
+ * const currentPathObject = {a: []}
378
+ * const arraysWithOrder = new Set()
379
+ * const [value, setValue, key] = handlePathPart(pathPart, currentPathObject.a, arraysWithOrder)
380
+ * setValue('b')
381
+ * // => currentPathObject = {a: ['b']}, key = 0
382
+ * ```
383
+ *
384
+ */
385
+ function handlePathPart(pathPart, currentPathObject, arraysWithOrder) {
386
+ if (pathPart.type === "object") {
387
+ const key = pathPart.path;
388
+ if (FORBIDDEN_OBJECT_KEYS.has(key)) throw new ForbiddenKeyError(pathPart.pathToPart);
389
+ if (Array.isArray(currentPathObject)) throw new DuplicateKeyError(pathPart.pathToPart);
390
+ const currentObject = currentPathObject;
391
+ return [
392
+ Object.prototype.hasOwnProperty.call(currentObject, key) ? currentObject[key] : void 0,
393
+ (val) => {
394
+ if (!isPrototypeKey(key)) {
395
+ currentObject[key] = val;
396
+ return;
397
+ }
398
+ Object.defineProperty(currentObject, key, {
399
+ value: val,
400
+ writable: true,
401
+ enumerable: true,
402
+ configurable: true
403
+ });
404
+ },
405
+ key
406
+ ];
407
+ }
408
+ const isOrdered = pathPart.path !== "";
409
+ if (isOrdered && Number(pathPart.path) > MAX_ARRAY_INDEX) throw new InvalidPathError(pathPart.pathToPart);
410
+ if (!Array.isArray(currentPathObject)) throw new DuplicateKeyError(pathPart.pathToPart);
411
+ const currentArray = currentPathObject;
412
+ const isOrderedArray = arraysWithOrder.has(currentArray);
413
+ if (isOrdered) arraysWithOrder.add(currentArray);
414
+ if (!isOrdered && isOrderedArray || isOrdered && !isOrderedArray && currentArray.length > 0) throw new MixedArrayError(pathPart.pathToPart);
415
+ const order = isOrdered ? Number(pathPart.path) : currentArray.length;
416
+ return [
417
+ currentArray[order],
418
+ (val) => currentArray[order] = val,
419
+ order
420
+ ];
421
+ }
422
+ /**
423
+ *
424
+ * Parses a FormData object to a JSON object. This is done by parsing the `name`
425
+ * attribute of each `FormDataEntryValue` and then inserting the value at the
426
+ * path. Also by default the start of the path is used to transform the value.
427
+ *
428
+ *
429
+ * In front of the whole `key`:
430
+ * - `+` => parse to `Number`
431
+ * - `-` => set value to `null`
432
+ * - `&` => parse to `Boolean`
433
+ *
434
+ * - `.` between path parts => nest into `objects`
435
+ * - `[key]` after path part => nest into `objects`, same as `.key`; the text
436
+ * in brackets is the key as it is (`a[b.c]` => key `b.c`)
437
+ * - `[\d*]` after path part => push to array in order `\d` or push to end if `[]`
438
+ *
439
+ * @example
440
+ * ```ts
441
+ * const formData = new FormData()
442
+ * formData.append('+a', '1')
443
+ * formData.append('&b', 'true')
444
+ * formData.append('-c', 'null')
445
+ * formData.append('d', 'foo')
446
+ * parseFormData(formData)
447
+ * // => {a: 1, b: true, c: null, d: 'foo'}
448
+ * ```
449
+ *
450
+ * @example
451
+ * ```ts
452
+ * const formData = new FormData()
453
+ * formData.append('a.b', 'foo')
454
+ * parseFormData(formData)
455
+ * // => {a: {b: 'foo'}}
456
+ * ```
457
+ *
458
+ * @example
459
+ * ```ts
460
+ * const formData = new FormData()
461
+ * formData.append('a[b]', 'foo')
462
+ * formData.append('a.c', 'bar')
463
+ * parseFormData(formData)
464
+ * // => {a: {b: 'foo', c: 'bar'}}
465
+ * ```
466
+ *
467
+ * @example
468
+ * ```ts
469
+ * const formData = new FormData()
470
+ * formData.append('a[0]', 'foo')
471
+ * formData.append('a[1]', 'bar')
472
+ * parseFormData(formData)
473
+ * // => {a: ['foo', 'bar']}
474
+ * ```
475
+ *
476
+ * @example
477
+ * ```ts
478
+ * const formData = new FormData()
479
+ * formData.append('a[]', 'foo')
480
+ * formData.append('a[]', 'bar')
481
+ * parseFormData(formData)
482
+ * // => {a: ['foo', 'bar']}
483
+ * ```
484
+ *
485
+ * @example
486
+ * ```ts
487
+ * const formData = new FormData()
488
+ * formData.append('a[0]', 'foo')
489
+ * parseFormData(formData, {
490
+ * transformEntry: ([path, value]) => ({
491
+ * path,
492
+ * value: typeof value === 'string' ? value + 'bar' : value,
493
+ * }),
494
+ * })
495
+ * // => {a: ['foobar']}
496
+ * ```
497
+ *
498
+ * @example
499
+ * ```ts
500
+ * const formData = new FormData()
501
+ * formData.append('a[0]', 'foo')
502
+ * formData.append('a[1]', '')
503
+ * parseFormData(formData, {removeEmptyString: true})
504
+ * // => {a: ['foo']}
505
+ * ```
506
+ *
507
+ * @param {Iterable<[string, string | File]>} formData - an iterator of an [`path`, `value`] tuple
508
+ * - `path` := an optional prefix (`+`, `-`, `&`), then path parts: keys after
509
+ * `.` or in brackets (`[key]`), and array parts `[]` or `[\d+]` (e.g.
510
+ * `+a[][1].b[c]`)
511
+ * - `value` := `string` or `File` (native or polyfilled `File` values are kept
512
+ * as they are)
513
+ * @param {ParseFormDataOptions} options - options for parsing the form data
514
+ * - `transformEntry` - a function to transform the path and the value before
515
+ * inserting the value at the path in the resulting object (default: `defaultTransform`)
516
+ * - `removeEmptyString` - if `true` removes all entries where the value is an empty string
517
+ * - `depth` - the maximum number of path parts in a path, counting every part
518
+ * (default: `Infinity`)
519
+ * @returns {JsonObject} the parsed JSON object
520
+ * @throws `TypeError` if `depth` isn't a positive integer or `Infinity`
521
+ * @throws `DepthLimitError` if a path has more path parts than `depth`
522
+ * - e.g. `a.b[0]` with `depth: 2` => `DepthLimitError('a.b[0]')`
523
+ * @throws `DuplicateKeyError` if
524
+ * - two entries set a value at the same path
525
+ * - e.g. `a` and `a`, `a[0]` and `a[0]`, `a.b` and `a[b]`
526
+ * - an entry uses a path part as an object, array or value and another entry
527
+ * uses it differently
528
+ * - e.g. `a` and `a.b`, `a.b` and `a[]`, `a[]` and `a.b`
529
+ * - the path starts with an array part
530
+ * - e.g. `[0]` or `[]`
531
+ * @throws `MixedArrayError` if at a specific path part an unordered array is
532
+ * defined and at a later path part an ordered array is defined or vice versa
533
+ * - e.g. `a[0]` and `a[]`
534
+ * - e.g. `a[]` and `a[0]`
535
+ * @throws `ForbiddenKeyError` if an object path part is `__proto__`,
536
+ * `constructor` or `prototype`
537
+ * - e.g. `__proto__.polluted`
538
+ * @throws `InvalidPathError` if an array index is larger than `4294967294`
539
+ * - e.g. `a[4294967295]`
540
+ *
541
+ * Every error's `key` is the path after `transformEntry`, not the field name
542
+ * (e.g. `+a.b.c` with `depth: 2` => `DepthLimitError('a.b.c')`).
543
+ *
544
+ * An entry with any other object path part named like a property on
545
+ * `Object.prototype` (`toString`, `hasOwnProperty`, ...) is removed from the
546
+ * result. It's parsed like any other entry first, so it causes the same errors
547
+ * as an unused name: an error doesn't tell the client which properties exist
548
+ * on the server's `Object.prototype`.
549
+ * - e.g. `user.toString` => `{}`
550
+ * - e.g. `user[toString]` => `{}`
551
+ */
552
+ function parseFormData(formData, { removeEmptyString = false, transformEntry = defaultTransform, depth = Infinity } = {}) {
553
+ if (depth !== Infinity && !(Number.isInteger(depth) && depth > 0)) throw new TypeError(`depth must be a positive integer or Infinity, got ${String(depth)}`);
554
+ const result = {};
555
+ const arraysWithOrder = /* @__PURE__ */ new Set();
556
+ const createdByRemoved = [];
557
+ for (const entry of Array.from(formData)) {
558
+ if (removeEmptyString && entry[1] === "") continue;
559
+ const { path, value } = transformEntry(entry, defaultTransform);
560
+ const pathParts = extractPathParts(path, depth);
561
+ const isRemoved = pathParts.some((pathPart) => pathPart.type === "object" && isPrototypeKey(pathPart.path));
562
+ let currentPathObject = result;
563
+ pathParts.forEach((pathPart, idx) => {
564
+ const [nextPathValue, setNextPathValue, key] = handlePathPart(pathPart, currentPathObject, arraysWithOrder);
565
+ const parent = currentPathObject;
566
+ if (pathParts.length - 1 === idx) {
567
+ if (nextPathValue !== void 0) throw new DuplicateKeyError(pathPart.pathToPart);
568
+ setNextPathValue(value);
569
+ if (isRemoved) createdByRemoved.push([
570
+ parent,
571
+ key,
572
+ void 0
573
+ ]);
574
+ } else {
575
+ if (nextPathValue !== void 0 && !isJsonObject(nextPathValue) && !Array.isArray(nextPathValue)) throw new DuplicateKeyError(pathPart.pathToPart);
576
+ const nextPathObject = nextPathValue ?? pathPart.default;
577
+ currentPathObject = nextPathObject;
578
+ setNextPathValue(nextPathObject);
579
+ if (isRemoved && nextPathValue === void 0) createdByRemoved.push([
580
+ parent,
581
+ key,
582
+ nextPathObject
583
+ ]);
584
+ }
585
+ });
586
+ }
587
+ for (let idx = createdByRemoved.length - 1; idx >= 0; idx--) {
588
+ const [parent, key, container] = createdByRemoved[idx];
589
+ if (container && Object.keys(container).length > 0) continue;
590
+ Reflect.deleteProperty(parent, key);
591
+ if (Array.isArray(parent)) arraysWithOrder.add(parent);
592
+ }
593
+ for (const orderedArray of Array.from(arraysWithOrder)) {
594
+ const values = Object.values(orderedArray);
595
+ orderedArray.length = 0;
596
+ for (const value of values) orderedArray.push(value);
597
+ }
598
+ return result;
599
+ }
600
+ exports.DepthLimitError = DepthLimitError;
601
+ exports.DuplicateKeyError = DuplicateKeyError;
602
+ exports.ForbiddenKeyError = ForbiddenKeyError;
603
+ exports.InvalidPathError = InvalidPathError;
604
+ exports.MixedArrayError = MixedArrayError;
605
+ exports.parseFormData = parseFormData;
606
+ });
6
607
 
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;
394
-
395
- Object.defineProperty(exports, '__esModule', { value: true });
396
-
397
- }));
398
- //# sourceMappingURL=parse-nested-form-data.umd.js.map
608
+ //# sourceMappingURL=parse-nested-form-data.umd.js.map