| 79 | } |
| 80 | |
| 81 | function parserForArrayFormat(options) { |
| 82 | switch (options.arrayFormat) { |
| 83 | case 'index': { |
| 84 | // The next free index per key for an entry without one, like `foo[]`. That is what PHP and Rack write for an array item, and what `arrayFormat: 'bracket'` produces. It is appended after the highest index seen so far, like in PHP, instead of every such entry overriding the previous one. |
| 85 | const nextIndexes = new Map(); |
| 86 | |
| 87 | return (key, value, accumulator) => { |
| 88 | const result = /\[(?<index>\d*)\]$/v.exec(key); |
| 89 | |
| 90 | key = key.replace(/\[(?<index>\d*)\]$/v, ''); |
| 91 | |
| 92 | // A repeated key adds its value whether or not it has an index, like the other array formats, instead of silently dropping the earlier values. A plain entry after the first is appended like `foo[]`. A repeated index keeps the last value, like in PHP. |
| 93 | if (!result && accumulator[key] === undefined) { |
| 94 | accumulator[key] = value; |
| 95 | return; |
| 96 | } |
| 97 | |
| 98 | if (accumulator[key] === undefined) { |
| 99 | accumulator[key] = {}; |
| 100 | } else if (typeof accumulator[key] !== 'object' || accumulator[key] === null) { |
| 101 | // A scalar seen before the indexed entries becomes the first item, like in the other array formats. The empty key sorts before any index. |
| 102 | accumulator[key] = {'': accumulator[key]}; |
| 103 | nextIndexes.set(key, 1); |
| 104 | } |
| 105 | |
| 106 | const index = result?.groups?.index || (nextIndexes.get(key) ?? 0); |
| 107 | accumulator[key][index] = value; |
| 108 | nextIndexes.set(key, Math.max(nextIndexes.get(key) ?? 0, Number(index) + 1)); |
| 109 | }; |
| 110 | } |
| 111 | |
| 112 | case 'bracket': |
| 113 | case 'colon-list-separator': { |
| 114 | const marker = options.arrayFormat === 'bracket' ? /\[\]$/v : /:list$/v; |
| 115 | |
| 116 | return (key, value, accumulator) => { |
| 117 | const isArray = marker.test(key); |
| 118 | key = key.replace(marker, ''); |
| 119 | |
| 120 | // A repeated key adds its value whether or not it has the marker, like `arrayFormat: 'none'`, instead of silently dropping the earlier values. |
| 121 | if (accumulator[key] === undefined) { |
| 122 | accumulator[key] = isArray ? [value] : value; |
| 123 | return; |
| 124 | } |
| 125 | |
| 126 | if (!Array.isArray(accumulator[key])) { |
| 127 | accumulator[key] = [accumulator[key], value]; |
| 128 | return; |
| 129 | } |
| 130 | |
| 131 | accumulator[key].push(value); |
| 132 | }; |
| 133 | } |
| 134 | |
| 135 | case 'comma': |
| 136 | case 'separator': { |
| 137 | return (key, value, accumulator) => { |
| 138 | // Split the raw value before decoding. A percent-encoded separator (`%2C`) is part of an item, only a literal separator delimits items. This follows RFC 6570 §3.2.8, where list members are percent-encoded and joined with a literal `,`, and matches `stringify()`, `qs`, and OpenAPI clients such as swagger-js and openapi-fetch. |