parse.js
1 'use strict'; 2 3 var utils = require('./utils'); 4 5 var has = Object.prototype.hasOwnProperty; 6 var isArray = Array.isArray; 7 8 var defaults = { 9 allowDots: false, 10 allowEmptyArrays: false, 11 allowPrototypes: false, 12 allowSparse: false, 13 arrayLimit: 20, 14 charset: 'utf-8', 15 charsetSentinel: false, 16 comma: false, 17 decodeDotInKeys: false, 18 decoder: utils.decode, 19 delimiter: '&', 20 depth: 5, 21 duplicates: 'combine', 22 ignoreQueryPrefix: false, 23 interpretNumericEntities: false, 24 parameterLimit: 1000, 25 parseArrays: true, 26 plainObjects: false, 27 strictDepth: false, 28 strictNullHandling: false, 29 throwOnLimitExceeded: false 30 }; 31 32 var interpretNumericEntities = function (str) { 33 return str.replace(/&#(\d+);/g, function ($0, numberStr) { 34 return String.fromCharCode(parseInt(numberStr, 10)); 35 }); 36 }; 37 38 var parseArrayValue = function (val, options, currentArrayLength) { 39 if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) { 40 return val.split(','); 41 } 42 43 if (options.throwOnLimitExceeded && currentArrayLength >= options.arrayLimit) { 44 throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.'); 45 } 46 47 return val; 48 }; 49 50 // This is what browsers will submit when the ✓ character occurs in an 51 // application/x-www-form-urlencoded body and the encoding of the page containing 52 // the form is iso-8859-1, or when the submitted form has an accept-charset 53 // attribute of iso-8859-1. Presumably also with other charsets that do not contain 54 // the ✓ character, such as us-ascii. 55 var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓') 56 57 // These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. 58 var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') 59 60 var parseValues = function parseQueryStringValues(str, options) { 61 var obj = { __proto__: null }; 62 63 var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; 64 cleanStr = cleanStr.replace(/%5B/gi, '[').replace(/%5D/gi, ']'); 65 66 var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; 67 var parts = cleanStr.split( 68 options.delimiter, 69 options.throwOnLimitExceeded ? limit + 1 : limit 70 ); 71 72 if (options.throwOnLimitExceeded && parts.length > limit) { 73 throw new RangeError('Parameter limit exceeded. Only ' + limit + ' parameter' + (limit === 1 ? '' : 's') + ' allowed.'); 74 } 75 76 var skipIndex = -1; // Keep track of where the utf8 sentinel was found 77 var i; 78 79 var charset = options.charset; 80 if (options.charsetSentinel) { 81 for (i = 0; i < parts.length; ++i) { 82 if (parts[i].indexOf('utf8=') === 0) { 83 if (parts[i] === charsetSentinel) { 84 charset = 'utf-8'; 85 } else if (parts[i] === isoSentinel) { 86 charset = 'iso-8859-1'; 87 } 88 skipIndex = i; 89 i = parts.length; // The eslint settings do not allow break; 90 } 91 } 92 } 93 94 for (i = 0; i < parts.length; ++i) { 95 if (i === skipIndex) { 96 continue; 97 } 98 var part = parts[i]; 99 100 var bracketEqualsPos = part.indexOf(']='); 101 var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; 102 103 var key; 104 var val; 105 if (pos === -1) { 106 key = options.decoder(part, defaults.decoder, charset, 'key'); 107 val = options.strictNullHandling ? null : ''; 108 } else { 109 key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); 110 111 val = utils.maybeMap( 112 parseArrayValue( 113 part.slice(pos + 1), 114 options, 115 isArray(obj[key]) ? obj[key].length : 0 116 ), 117 function (encodedVal) { 118 return options.decoder(encodedVal, defaults.decoder, charset, 'value'); 119 } 120 ); 121 } 122 123 if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { 124 val = interpretNumericEntities(String(val)); 125 } 126 127 if (part.indexOf('[]=') > -1) { 128 val = isArray(val) ? [val] : val; 129 } 130 131 var existing = has.call(obj, key); 132 if (existing && options.duplicates === 'combine') { 133 obj[key] = utils.combine(obj[key], val); 134 } else if (!existing || options.duplicates === 'last') { 135 obj[key] = val; 136 } 137 } 138 139 return obj; 140 }; 141 142 var parseObject = function (chain, val, options, valuesParsed) { 143 var currentArrayLength = 0; 144 if (chain.length > 0 && chain[chain.length - 1] === '[]') { 145 var parentKey = chain.slice(0, -1).join(''); 146 currentArrayLength = Array.isArray(val) && val[parentKey] ? val[parentKey].length : 0; 147 } 148 149 var leaf = valuesParsed ? val : parseArrayValue(val, options, currentArrayLength); 150 151 for (var i = chain.length - 1; i >= 0; --i) { 152 var obj; 153 var root = chain[i]; 154 155 if (root === '[]' && options.parseArrays) { 156 obj = options.allowEmptyArrays && (leaf === '' || (options.strictNullHandling && leaf === null)) 157 ? [] 158 : utils.combine([], leaf); 159 } else { 160 obj = options.plainObjects ? { __proto__: null } : {}; 161 var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; 162 var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, '.') : cleanRoot; 163 var index = parseInt(decodedRoot, 10); 164 if (!options.parseArrays && decodedRoot === '') { 165 obj = { 0: leaf }; 166 } else if ( 167 !isNaN(index) 168 && root !== decodedRoot 169 && String(index) === decodedRoot 170 && index >= 0 171 && (options.parseArrays && index <= options.arrayLimit) 172 ) { 173 obj = []; 174 obj[index] = leaf; 175 } else if (decodedRoot !== '__proto__') { 176 obj[decodedRoot] = leaf; 177 } 178 } 179 180 leaf = obj; 181 } 182 183 return leaf; 184 }; 185 186 var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { 187 if (!givenKey) { 188 return; 189 } 190 191 // Transform dot notation to bracket notation 192 var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; 193 194 // The regex chunks 195 196 var brackets = /(\[[^[\]]*])/; 197 var child = /(\[[^[\]]*])/g; 198 199 // Get the parent 200 201 var segment = options.depth > 0 && brackets.exec(key); 202 var parent = segment ? key.slice(0, segment.index) : key; 203 204 // Stash the parent if it exists 205 206 var keys = []; 207 if (parent) { 208 // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties 209 if (!options.plainObjects && has.call(Object.prototype, parent)) { 210 if (!options.allowPrototypes) { 211 return; 212 } 213 } 214 215 keys.push(parent); 216 } 217 218 // Loop through children appending to the array until we hit depth 219 220 var i = 0; 221 while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) { 222 i += 1; 223 if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { 224 if (!options.allowPrototypes) { 225 return; 226 } 227 } 228 keys.push(segment[1]); 229 } 230 231 // If there's a remainder, check strictDepth option for throw, else just add whatever is left 232 233 if (segment) { 234 if (options.strictDepth === true) { 235 throw new RangeError('Input depth exceeded depth option of ' + options.depth + ' and strictDepth is true'); 236 } 237 keys.push('[' + key.slice(segment.index) + ']'); 238 } 239 240 return parseObject(keys, val, options, valuesParsed); 241 }; 242 243 var normalizeParseOptions = function normalizeParseOptions(opts) { 244 if (!opts) { 245 return defaults; 246 } 247 248 if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { 249 throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); 250 } 251 252 if (typeof opts.decodeDotInKeys !== 'undefined' && typeof opts.decodeDotInKeys !== 'boolean') { 253 throw new TypeError('`decodeDotInKeys` option can only be `true` or `false`, when provided'); 254 } 255 256 if (opts.decoder !== null && typeof opts.decoder !== 'undefined' && typeof opts.decoder !== 'function') { 257 throw new TypeError('Decoder has to be a function.'); 258 } 259 260 if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { 261 throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); 262 } 263 264 if (typeof opts.throwOnLimitExceeded !== 'undefined' && typeof opts.throwOnLimitExceeded !== 'boolean') { 265 throw new TypeError('`throwOnLimitExceeded` option must be a boolean'); 266 } 267 268 var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; 269 270 var duplicates = typeof opts.duplicates === 'undefined' ? defaults.duplicates : opts.duplicates; 271 272 if (duplicates !== 'combine' && duplicates !== 'first' && duplicates !== 'last') { 273 throw new TypeError('The duplicates option must be either combine, first, or last'); 274 } 275 276 var allowDots = typeof opts.allowDots === 'undefined' ? opts.decodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; 277 278 return { 279 allowDots: allowDots, 280 allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, 281 allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, 282 allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse, 283 arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, 284 charset: charset, 285 charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, 286 comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, 287 decodeDotInKeys: typeof opts.decodeDotInKeys === 'boolean' ? opts.decodeDotInKeys : defaults.decodeDotInKeys, 288 decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, 289 delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, 290 // eslint-disable-next-line no-implicit-coercion, no-extra-parens 291 depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, 292 duplicates: duplicates, 293 ignoreQueryPrefix: opts.ignoreQueryPrefix === true, 294 interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, 295 parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, 296 parseArrays: opts.parseArrays !== false, 297 plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, 298 strictDepth: typeof opts.strictDepth === 'boolean' ? !!opts.strictDepth : defaults.strictDepth, 299 strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling, 300 throwOnLimitExceeded: typeof opts.throwOnLimitExceeded === 'boolean' ? opts.throwOnLimitExceeded : false 301 }; 302 }; 303 304 module.exports = function (str, opts) { 305 var options = normalizeParseOptions(opts); 306 307 if (str === '' || str === null || typeof str === 'undefined') { 308 return options.plainObjects ? { __proto__: null } : {}; 309 } 310 311 var tempObj = typeof str === 'string' ? parseValues(str, options) : str; 312 var obj = options.plainObjects ? { __proto__: null } : {}; 313 314 // Iterate over the keys and setup the new object 315 316 var keys = Object.keys(tempObj); 317 for (var i = 0; i < keys.length; ++i) { 318 var key = keys[i]; 319 var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); 320 obj = utils.merge(obj, newObj, options); 321 } 322 323 if (options.allowSparse === true) { 324 return obj; 325 } 326 327 return utils.compact(obj); 328 };