stringify.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. 'use strict';
  2. var getSideChannel = require('side-channel');
  3. var utils = require('./utils');
  4. var formats = require('./formats');
  5. var has = Object.prototype.hasOwnProperty;
  6. var arrayPrefixGenerators = {
  7. brackets: function brackets(prefix) {
  8. return prefix + '[]';
  9. },
  10. comma: 'comma',
  11. indices: function indices(prefix, key) {
  12. return prefix + '[' + key + ']';
  13. },
  14. repeat: function repeat(prefix) {
  15. return prefix;
  16. }
  17. };
  18. var isArray = Array.isArray;
  19. var push = Array.prototype.push;
  20. var pushToArray = function (arr, valueOrArray) {
  21. push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]);
  22. };
  23. var toISO = Date.prototype.toISOString;
  24. var defaultFormat = formats['default'];
  25. var defaults = {
  26. addQueryPrefix: false,
  27. allowDots: false,
  28. allowEmptyArrays: false,
  29. arrayFormat: 'indices',
  30. charset: 'utf-8',
  31. charsetSentinel: false,
  32. delimiter: '&',
  33. encode: true,
  34. encodeDotInKeys: false,
  35. encoder: utils.encode,
  36. encodeValuesOnly: false,
  37. format: defaultFormat,
  38. formatter: formats.formatters[defaultFormat],
  39. // deprecated
  40. indices: false,
  41. serializeDate: function serializeDate(date) {
  42. return toISO.call(date);
  43. },
  44. skipNulls: false,
  45. strictNullHandling: false
  46. };
  47. var isNonNullishPrimitive = function isNonNullishPrimitive(v) {
  48. return typeof v === 'string'
  49. || typeof v === 'number'
  50. || typeof v === 'boolean'
  51. || typeof v === 'symbol'
  52. || typeof v === 'bigint';
  53. };
  54. var sentinel = {};
  55. var stringify = function stringify(
  56. object,
  57. prefix,
  58. generateArrayPrefix,
  59. commaRoundTrip,
  60. allowEmptyArrays,
  61. strictNullHandling,
  62. skipNulls,
  63. encodeDotInKeys,
  64. encoder,
  65. filter,
  66. sort,
  67. allowDots,
  68. serializeDate,
  69. format,
  70. formatter,
  71. encodeValuesOnly,
  72. charset,
  73. sideChannel
  74. ) {
  75. var obj = object;
  76. var tmpSc = sideChannel;
  77. var step = 0;
  78. var findFlag = false;
  79. while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) {
  80. // Where object last appeared in the ref tree
  81. var pos = tmpSc.get(object);
  82. step += 1;
  83. if (typeof pos !== 'undefined') {
  84. if (pos === step) {
  85. throw new RangeError('Cyclic object value');
  86. } else {
  87. findFlag = true; // Break while
  88. }
  89. }
  90. if (typeof tmpSc.get(sentinel) === 'undefined') {
  91. step = 0;
  92. }
  93. }
  94. if (typeof filter === 'function') {
  95. obj = filter(prefix, obj);
  96. } else if (obj instanceof Date) {
  97. obj = serializeDate(obj);
  98. } else if (generateArrayPrefix === 'comma' && isArray(obj)) {
  99. obj = utils.maybeMap(obj, function (value) {
  100. if (value instanceof Date) {
  101. return serializeDate(value);
  102. }
  103. return value;
  104. });
  105. }
  106. if (obj === null) {
  107. if (strictNullHandling) {
  108. return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix;
  109. }
  110. obj = '';
  111. }
  112. if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) {
  113. if (encoder) {
  114. var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format);
  115. return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))];
  116. }
  117. return [formatter(prefix) + '=' + formatter(String(obj))];
  118. }
  119. var values = [];
  120. if (typeof obj === 'undefined') {
  121. return values;
  122. }
  123. var objKeys;
  124. if (generateArrayPrefix === 'comma' && isArray(obj)) {
  125. // we need to join elements in
  126. if (encodeValuesOnly && encoder) {
  127. obj = utils.maybeMap(obj, encoder);
  128. }
  129. objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }];
  130. } else if (isArray(filter)) {
  131. objKeys = filter;
  132. } else {
  133. var keys = Object.keys(obj);
  134. objKeys = sort ? keys.sort(sort) : keys;
  135. }
  136. var encodedPrefix = encodeDotInKeys ? prefix.replace(/\./g, '%2E') : prefix;
  137. var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encodedPrefix + '[]' : encodedPrefix;
  138. if (allowEmptyArrays && isArray(obj) && obj.length === 0) {
  139. return adjustedPrefix + '[]';
  140. }
  141. for (var j = 0; j < objKeys.length; ++j) {
  142. var key = objKeys[j];
  143. var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key];
  144. if (skipNulls && value === null) {
  145. continue;
  146. }
  147. var encodedKey = allowDots && encodeDotInKeys ? key.replace(/\./g, '%2E') : key;
  148. var keyPrefix = isArray(obj)
  149. ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, encodedKey) : adjustedPrefix
  150. : adjustedPrefix + (allowDots ? '.' + encodedKey : '[' + encodedKey + ']');
  151. sideChannel.set(object, step);
  152. var valueSideChannel = getSideChannel();
  153. valueSideChannel.set(sentinel, sideChannel);
  154. pushToArray(values, stringify(
  155. value,
  156. keyPrefix,
  157. generateArrayPrefix,
  158. commaRoundTrip,
  159. allowEmptyArrays,
  160. strictNullHandling,
  161. skipNulls,
  162. encodeDotInKeys,
  163. generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder,
  164. filter,
  165. sort,
  166. allowDots,
  167. serializeDate,
  168. format,
  169. formatter,
  170. encodeValuesOnly,
  171. charset,
  172. valueSideChannel
  173. ));
  174. }
  175. return values;
  176. };
  177. var normalizeStringifyOptions = function normalizeStringifyOptions(opts) {
  178. if (!opts) {
  179. return defaults;
  180. }
  181. if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') {
  182. throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided');
  183. }
  184. if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') {
  185. throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided');
  186. }
  187. if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') {
  188. throw new TypeError('Encoder has to be a function.');
  189. }
  190. var charset = opts.charset || defaults.charset;
  191. if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
  192. throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
  193. }
  194. var format = formats['default'];
  195. if (typeof opts.format !== 'undefined') {
  196. if (!has.call(formats.formatters, opts.format)) {
  197. throw new TypeError('Unknown format option provided.');
  198. }
  199. format = opts.format;
  200. }
  201. var formatter = formats.formatters[format];
  202. var filter = defaults.filter;
  203. if (typeof opts.filter === 'function' || isArray(opts.filter)) {
  204. filter = opts.filter;
  205. }
  206. var arrayFormat;
  207. if (opts.arrayFormat in arrayPrefixGenerators) {
  208. arrayFormat = opts.arrayFormat;
  209. } else if ('indices' in opts) {
  210. arrayFormat = opts.indices ? 'indices' : 'repeat';
  211. } else {
  212. arrayFormat = defaults.arrayFormat;
  213. }
  214. if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') {
  215. throw new TypeError('`commaRoundTrip` must be a boolean, or absent');
  216. }
  217. var allowDots = typeof opts.allowDots === 'undefined' ? opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots;
  218. return {
  219. addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,
  220. allowDots: allowDots,
  221. allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,
  222. arrayFormat: arrayFormat,
  223. charset: charset,
  224. charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
  225. commaRoundTrip: opts.commaRoundTrip,
  226. delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,
  227. encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,
  228. encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys,
  229. encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,
  230. encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
  231. filter: filter,
  232. format: format,
  233. formatter: formatter,
  234. serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,
  235. skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,
  236. sort: typeof opts.sort === 'function' ? opts.sort : null,
  237. strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
  238. };
  239. };
  240. module.exports = function (object, opts) {
  241. var obj = object;
  242. var options = normalizeStringifyOptions(opts);
  243. var objKeys;
  244. var filter;
  245. if (typeof options.filter === 'function') {
  246. filter = options.filter;
  247. obj = filter('', obj);
  248. } else if (isArray(options.filter)) {
  249. filter = options.filter;
  250. objKeys = filter;
  251. }
  252. var keys = [];
  253. if (typeof obj !== 'object' || obj === null) {
  254. return '';
  255. }
  256. var generateArrayPrefix = arrayPrefixGenerators[options.arrayFormat];
  257. var commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip;
  258. if (!objKeys) {
  259. objKeys = Object.keys(obj);
  260. }
  261. if (options.sort) {
  262. objKeys.sort(options.sort);
  263. }
  264. var sideChannel = getSideChannel();
  265. for (var i = 0; i < objKeys.length; ++i) {
  266. var key = objKeys[i];
  267. if (options.skipNulls && obj[key] === null) {
  268. continue;
  269. }
  270. pushToArray(keys, stringify(
  271. obj[key],
  272. key,
  273. generateArrayPrefix,
  274. commaRoundTrip,
  275. options.allowEmptyArrays,
  276. options.strictNullHandling,
  277. options.skipNulls,
  278. options.encodeDotInKeys,
  279. options.encode ? options.encoder : null,
  280. options.filter,
  281. options.sort,
  282. options.allowDots,
  283. options.serializeDate,
  284. options.format,
  285. options.formatter,
  286. options.encodeValuesOnly,
  287. options.charset,
  288. sideChannel
  289. ));
  290. }
  291. var joined = keys.join(options.delimiter);
  292. var prefix = options.addQueryPrefix === true ? '?' : '';
  293. if (options.charsetSentinel) {
  294. if (options.charset === 'iso-8859-1') {
  295. // encodeURIComponent('&#10003;'), the "numeric entity" representation of a checkmark
  296. prefix += 'utf8=%26%2310003%3B&';
  297. } else {
  298. // encodeURIComponent('✓')
  299. prefix += 'utf8=%E2%9C%93&';
  300. }
  301. }
  302. return joined.length > 0 ? prefix + joined : '';
  303. };