parse.js 14 KB

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