parse.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. allowPrototypes: false,
  8. allowSparse: false,
  9. arrayLimit: 20,
  10. charset: 'utf-8',
  11. charsetSentinel: false,
  12. comma: false,
  13. decoder: utils.decode,
  14. delimiter: '&',
  15. depth: 5,
  16. ignoreQueryPrefix: false,
  17. interpretNumericEntities: false,
  18. parameterLimit: 1000,
  19. parseArrays: true,
  20. plainObjects: false,
  21. strictNullHandling: false
  22. };
  23. var interpretNumericEntities = function (str) {
  24. return str.replace(/&#(\d+);/g, function ($0, numberStr) {
  25. return String.fromCharCode(parseInt(numberStr, 10));
  26. });
  27. };
  28. var parseArrayValue = function (val, options) {
  29. if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) {
  30. return val.split(',');
  31. }
  32. return val;
  33. };
  34. // This is what browsers will submit when the ✓ character occurs in an
  35. // application/x-www-form-urlencoded body and the encoding of the page containing
  36. // the form is iso-8859-1, or when the submitted form has an accept-charset
  37. // attribute of iso-8859-1. Presumably also with other charsets that do not contain
  38. // the ✓ character, such as us-ascii.
  39. var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓')
  40. // These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.
  41. var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')
  42. var parseValues = function parseQueryStringValues(str, options) {
  43. var obj = {};
  44. var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
  45. var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
  46. var parts = cleanStr.split(options.delimiter, limit);
  47. var skipIndex = -1; // Keep track of where the utf8 sentinel was found
  48. var i;
  49. var charset = options.charset;
  50. if (options.charsetSentinel) {
  51. for (i = 0; i < parts.length; ++i) {
  52. if (parts[i].indexOf('utf8=') === 0) {
  53. if (parts[i] === charsetSentinel) {
  54. charset = 'utf-8';
  55. } else if (parts[i] === isoSentinel) {
  56. charset = 'iso-8859-1';
  57. }
  58. skipIndex = i;
  59. i = parts.length; // The eslint settings do not allow break;
  60. }
  61. }
  62. }
  63. for (i = 0; i < parts.length; ++i) {
  64. if (i === skipIndex) {
  65. continue;
  66. }
  67. var part = parts[i];
  68. var bracketEqualsPos = part.indexOf(']=');
  69. var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
  70. var key, val;
  71. if (pos === -1) {
  72. key = options.decoder(part, defaults.decoder, charset, 'key');
  73. val = options.strictNullHandling ? null : '';
  74. } else {
  75. key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key');
  76. val = utils.maybeMap(
  77. parseArrayValue(part.slice(pos + 1), options),
  78. function (encodedVal) {
  79. return options.decoder(encodedVal, defaults.decoder, charset, 'value');
  80. }
  81. );
  82. }
  83. if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {
  84. val = interpretNumericEntities(val);
  85. }
  86. if (part.indexOf('[]=') > -1) {
  87. val = isArray(val) ? [val] : val;
  88. }
  89. if (has.call(obj, key)) {
  90. obj[key] = utils.combine(obj[key], val);
  91. } else {
  92. obj[key] = val;
  93. }
  94. }
  95. return obj;
  96. };
  97. var parseObject = function (chain, val, options, valuesParsed) {
  98. var leaf = valuesParsed ? val : parseArrayValue(val, options);
  99. for (var i = chain.length - 1; i >= 0; --i) {
  100. var obj;
  101. var root = chain[i];
  102. if (root === '[]' && options.parseArrays) {
  103. obj = [].concat(leaf);
  104. } else {
  105. obj = options.plainObjects ? Object.create(null) : {};
  106. var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
  107. var index = parseInt(cleanRoot, 10);
  108. if (!options.parseArrays && cleanRoot === '') {
  109. obj = { 0: leaf };
  110. } else if (
  111. !isNaN(index)
  112. && root !== cleanRoot
  113. && String(index) === cleanRoot
  114. && index >= 0
  115. && (options.parseArrays && index <= options.arrayLimit)
  116. ) {
  117. obj = [];
  118. obj[index] = leaf;
  119. } else if (cleanRoot !== '__proto__') {
  120. obj[cleanRoot] = leaf;
  121. }
  122. }
  123. leaf = obj;
  124. }
  125. return leaf;
  126. };
  127. var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {
  128. if (!givenKey) {
  129. return;
  130. }
  131. // Transform dot notation to bracket notation
  132. var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
  133. // The regex chunks
  134. var brackets = /(\[[^[\]]*])/;
  135. var child = /(\[[^[\]]*])/g;
  136. // Get the parent
  137. var segment = options.depth > 0 && brackets.exec(key);
  138. var parent = segment ? key.slice(0, segment.index) : key;
  139. // Stash the parent if it exists
  140. var keys = [];
  141. if (parent) {
  142. // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties
  143. if (!options.plainObjects && has.call(Object.prototype, parent)) {
  144. if (!options.allowPrototypes) {
  145. return;
  146. }
  147. }
  148. keys.push(parent);
  149. }
  150. // Loop through children appending to the array until we hit depth
  151. var i = 0;
  152. while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) {
  153. i += 1;
  154. if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
  155. if (!options.allowPrototypes) {
  156. return;
  157. }
  158. }
  159. keys.push(segment[1]);
  160. }
  161. // If there's a remainder, just add whatever is left
  162. if (segment) {
  163. keys.push('[' + key.slice(segment.index) + ']');
  164. }
  165. return parseObject(keys, val, options, valuesParsed);
  166. };
  167. var normalizeParseOptions = function normalizeParseOptions(opts) {
  168. if (!opts) {
  169. return defaults;
  170. }
  171. if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') {
  172. throw new TypeError('Decoder has to be a function.');
  173. }
  174. if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
  175. throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
  176. }
  177. var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset;
  178. return {
  179. allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
  180. allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes,
  181. allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse,
  182. arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit,
  183. charset: charset,
  184. charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
  185. comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma,
  186. decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder,
  187. delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,
  188. // eslint-disable-next-line no-implicit-coercion, no-extra-parens
  189. depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth,
  190. ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
  191. interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities,
  192. parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit,
  193. parseArrays: opts.parseArrays !== false,
  194. plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects,
  195. strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
  196. };
  197. };
  198. module.exports = function (str, opts) {
  199. var options = normalizeParseOptions(opts);
  200. if (str === '' || str === null || typeof str === 'undefined') {
  201. return options.plainObjects ? Object.create(null) : {};
  202. }
  203. var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
  204. var obj = options.plainObjects ? Object.create(null) : {};
  205. // Iterate over the keys and setup the new object
  206. var keys = Object.keys(tempObj);
  207. for (var i = 0; i < keys.length; ++i) {
  208. var key = keys[i];
  209. var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string');
  210. obj = utils.merge(obj, newObj, options);
  211. }
  212. if (options.allowSparse === true) {
  213. return obj;
  214. }
  215. return utils.compact(obj);
  216. };