stringify.js 9.6 KB

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