parse.js 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703
  1. 'use strict';
  2. var test = require('tape');
  3. var hasPropertyDescriptors = require('has-property-descriptors')();
  4. var iconv = require('iconv-lite');
  5. var mockProperty = require('mock-property');
  6. var hasOverrideMistake = require('has-override-mistake')();
  7. var SaferBuffer = require('safer-buffer').Buffer;
  8. var v = require('es-value-fixtures');
  9. var inspect = require('object-inspect');
  10. var emptyTestCases = require('./empty-keys-cases').emptyTestCases;
  11. var hasProto = require('has-proto')();
  12. var qs = require('../');
  13. var utils = require('../lib/utils');
  14. test('parse()', function (t) {
  15. t.test('parses a simple string', function (st) {
  16. st.deepEqual(qs.parse('0=foo'), { 0: 'foo' });
  17. st.deepEqual(qs.parse('foo=c++'), { foo: 'c ' });
  18. st.deepEqual(qs.parse('a[>=]=23'), { a: { '>=': '23' } });
  19. st.deepEqual(qs.parse('a[<=>]==23'), { a: { '<=>': '=23' } });
  20. st.deepEqual(qs.parse('a[==]=23'), { a: { '==': '23' } });
  21. st.deepEqual(qs.parse('foo', { strictNullHandling: true }), { foo: null });
  22. st.deepEqual(qs.parse('foo'), { foo: '' });
  23. st.deepEqual(qs.parse('foo='), { foo: '' });
  24. st.deepEqual(qs.parse('foo=bar'), { foo: 'bar' });
  25. st.deepEqual(qs.parse(' foo = bar = baz '), { ' foo ': ' bar = baz ' });
  26. st.deepEqual(qs.parse('foo=bar=baz'), { foo: 'bar=baz' });
  27. st.deepEqual(qs.parse('foo=bar&bar=baz'), { foo: 'bar', bar: 'baz' });
  28. st.deepEqual(qs.parse('foo2=bar2&baz2='), { foo2: 'bar2', baz2: '' });
  29. st.deepEqual(qs.parse('foo=bar&baz', { strictNullHandling: true }), { foo: 'bar', baz: null });
  30. st.deepEqual(qs.parse('foo=bar&baz'), { foo: 'bar', baz: '' });
  31. st.deepEqual(qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World'), {
  32. cht: 'p3',
  33. chd: 't:60,40',
  34. chs: '250x100',
  35. chl: 'Hello|World'
  36. });
  37. st.end();
  38. });
  39. t.test('comma: false', function (st) {
  40. st.deepEqual(qs.parse('a[]=b&a[]=c'), { a: ['b', 'c'] });
  41. st.deepEqual(qs.parse('a[0]=b&a[1]=c'), { a: ['b', 'c'] });
  42. st.deepEqual(qs.parse('a=b,c'), { a: 'b,c' });
  43. st.deepEqual(qs.parse('a=b&a=c'), { a: ['b', 'c'] });
  44. st.end();
  45. });
  46. t.test('comma: true', function (st) {
  47. st.deepEqual(qs.parse('a[]=b&a[]=c', { comma: true }), { a: ['b', 'c'] });
  48. st.deepEqual(qs.parse('a[0]=b&a[1]=c', { comma: true }), { a: ['b', 'c'] });
  49. st.deepEqual(qs.parse('a=b,c', { comma: true }), { a: ['b', 'c'] });
  50. st.deepEqual(qs.parse('a=b&a=c', { comma: true }), { a: ['b', 'c'] });
  51. st.end();
  52. });
  53. t.test('allows enabling dot notation', function (st) {
  54. st.deepEqual(qs.parse('a.b=c'), { 'a.b': 'c' });
  55. st.deepEqual(qs.parse('a.b=c', { allowDots: true }), { a: { b: 'c' } });
  56. st.end();
  57. });
  58. t.test('decode dot keys correctly', function (st) {
  59. st.deepEqual(
  60. qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe', { allowDots: false, decodeDotInKeys: false }),
  61. { 'name%2Eobj.first': 'John', 'name%2Eobj.last': 'Doe' },
  62. 'with allowDots false and decodeDotInKeys false'
  63. );
  64. st.deepEqual(
  65. qs.parse('name.obj.first=John&name.obj.last=Doe', { allowDots: true, decodeDotInKeys: false }),
  66. { name: { obj: { first: 'John', last: 'Doe' } } },
  67. 'with allowDots false and decodeDotInKeys false'
  68. );
  69. st.deepEqual(
  70. qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe', { allowDots: true, decodeDotInKeys: false }),
  71. { 'name%2Eobj': { first: 'John', last: 'Doe' } },
  72. 'with allowDots true and decodeDotInKeys false'
  73. );
  74. st.deepEqual(
  75. qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe', { allowDots: true, decodeDotInKeys: true }),
  76. { 'name.obj': { first: 'John', last: 'Doe' } },
  77. 'with allowDots true and decodeDotInKeys true'
  78. );
  79. st.deepEqual(
  80. qs.parse(
  81. 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe',
  82. { allowDots: false, decodeDotInKeys: false }
  83. ),
  84. { 'name%2Eobj%2Esubobject.first%2Egodly%2Ename': 'John', 'name%2Eobj%2Esubobject.last': 'Doe' },
  85. 'with allowDots false and decodeDotInKeys false'
  86. );
  87. st.deepEqual(
  88. qs.parse(
  89. 'name.obj.subobject.first.godly.name=John&name.obj.subobject.last=Doe',
  90. { allowDots: true, decodeDotInKeys: false }
  91. ),
  92. { name: { obj: { subobject: { first: { godly: { name: 'John' } }, last: 'Doe' } } } },
  93. 'with allowDots true and decodeDotInKeys false'
  94. );
  95. st.deepEqual(
  96. qs.parse(
  97. 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe',
  98. { allowDots: true, decodeDotInKeys: true }
  99. ),
  100. { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } },
  101. 'with allowDots true and decodeDotInKeys true'
  102. );
  103. st.deepEqual(
  104. qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe'),
  105. { 'name%2Eobj.first': 'John', 'name%2Eobj.last': 'Doe' },
  106. 'with allowDots and decodeDotInKeys undefined'
  107. );
  108. st.end();
  109. });
  110. t.test('decodes dot in key of object, and allow enabling dot notation when decodeDotInKeys is set to true and allowDots is undefined', function (st) {
  111. st.deepEqual(
  112. qs.parse(
  113. 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe',
  114. { decodeDotInKeys: true }
  115. ),
  116. { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } },
  117. 'with allowDots undefined and decodeDotInKeys true'
  118. );
  119. st.end();
  120. });
  121. t.test('throws when decodeDotInKeys is not of type boolean', function (st) {
  122. st['throws'](
  123. function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: 'foobar' }); },
  124. TypeError
  125. );
  126. st['throws'](
  127. function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: 0 }); },
  128. TypeError
  129. );
  130. st['throws'](
  131. function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: NaN }); },
  132. TypeError
  133. );
  134. st['throws'](
  135. function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: null }); },
  136. TypeError
  137. );
  138. st.end();
  139. });
  140. t.test('allows empty arrays in obj values', function (st) {
  141. st.deepEqual(qs.parse('foo[]&bar=baz', { allowEmptyArrays: true }), { foo: [], bar: 'baz' });
  142. st.deepEqual(qs.parse('foo[]&bar=baz', { allowEmptyArrays: false }), { foo: [''], bar: 'baz' });
  143. st.end();
  144. });
  145. t.test('throws when allowEmptyArrays is not of type boolean', function (st) {
  146. st['throws'](
  147. function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: 'foobar' }); },
  148. TypeError
  149. );
  150. st['throws'](
  151. function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: 0 }); },
  152. TypeError
  153. );
  154. st['throws'](
  155. function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: NaN }); },
  156. TypeError
  157. );
  158. st['throws'](
  159. function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: null }); },
  160. TypeError
  161. );
  162. st.end();
  163. });
  164. t.test('allowEmptyArrays + strictNullHandling', function (st) {
  165. st.deepEqual(
  166. qs.parse('testEmptyArray[]', { strictNullHandling: true, allowEmptyArrays: true }),
  167. { testEmptyArray: [] }
  168. );
  169. st.end();
  170. });
  171. t.deepEqual(qs.parse('a[b]=c'), { a: { b: 'c' } }, 'parses a single nested string');
  172. t.deepEqual(qs.parse('a[b][c]=d'), { a: { b: { c: 'd' } } }, 'parses a double nested string');
  173. t.deepEqual(
  174. qs.parse('a[b][c][d][e][f][g][h]=i'),
  175. { a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } },
  176. 'defaults to a depth of 5'
  177. );
  178. t.test('only parses one level when depth = 1', function (st) {
  179. st.deepEqual(qs.parse('a[b][c]=d', { depth: 1 }), { a: { b: { '[c]': 'd' } } });
  180. st.deepEqual(qs.parse('a[b][c][d]=e', { depth: 1 }), { a: { b: { '[c][d]': 'e' } } });
  181. st.end();
  182. });
  183. t.test('uses original key when depth = 0', function (st) {
  184. st.deepEqual(qs.parse('a[0]=b&a[1]=c', { depth: 0 }), { 'a[0]': 'b', 'a[1]': 'c' });
  185. st.deepEqual(qs.parse('a[0][0]=b&a[0][1]=c&a[1]=d&e=2', { depth: 0 }), { 'a[0][0]': 'b', 'a[0][1]': 'c', 'a[1]': 'd', e: '2' });
  186. st.deepEqual(qs.parse('a.b=c', { depth: 0, allowDots: true }), { 'a[b]': 'c' }, 'normalizes dots before applying depth-0 behavior');
  187. st.deepEqual(qs.parse('toString=foo', { depth: 0 }), {}, 'respects prototype guard at depth 0');
  188. st.deepEqual(qs.parse('toString=foo', { depth: 0, allowPrototypes: true }), { toString: 'foo' }, 'allows prototypes at depth 0 when enabled');
  189. st.end();
  190. });
  191. t.test('ignores prototype keys when depth = 0 and allowPrototypes is false', function (st) {
  192. st.deepEqual(qs.parse('toString=foo', { depth: 0 }), {});
  193. st.deepEqual(qs.parse('hasOwnProperty=bar', { depth: 0 }), {});
  194. st.deepEqual(qs.parse('toString=foo&a=b', { depth: 0 }), { a: 'b' });
  195. st.end();
  196. });
  197. t.test('allows prototype keys when depth = 0 and allowPrototypes is true', function (st) {
  198. st.deepEqual(qs.parse('toString=foo', { depth: 0, allowPrototypes: true }), { toString: 'foo' });
  199. st.end();
  200. });
  201. t.test('uses original key when depth = false', function (st) {
  202. st.deepEqual(qs.parse('a[0]=b&a[1]=c', { depth: false }), { 'a[0]': 'b', 'a[1]': 'c' });
  203. st.deepEqual(qs.parse('a[0][0]=b&a[0][1]=c&a[1]=d&e=2', { depth: false }), { 'a[0][0]': 'b', 'a[0][1]': 'c', 'a[1]': 'd', e: '2' });
  204. st.end();
  205. });
  206. t.deepEqual(qs.parse('a=b&a=c'), { a: ['b', 'c'] }, 'parses a simple array');
  207. t.test('parses an explicit array', function (st) {
  208. st.deepEqual(qs.parse('a[]=b'), { a: ['b'] });
  209. st.deepEqual(qs.parse('a[]=b&a[]=c'), { a: ['b', 'c'] });
  210. st.deepEqual(qs.parse('a[]=b&a[]=c&a[]=d'), { a: ['b', 'c', 'd'] });
  211. st.end();
  212. });
  213. t.test('parses a mix of simple and explicit arrays', function (st) {
  214. st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] });
  215. st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] });
  216. st.deepEqual(qs.parse('a[0]=b&a=c'), { a: ['b', 'c'] });
  217. st.deepEqual(qs.parse('a=b&a[0]=c'), { a: ['b', 'c'] });
  218. st.deepEqual(qs.parse('a[1]=b&a=c', { arrayLimit: 20 }), { a: ['b', 'c'] });
  219. st.deepEqual(qs.parse('a[]=b&a=c', { arrayLimit: 0 }), { a: { 0: 'b', 1: 'c' } });
  220. st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] });
  221. st.deepEqual(qs.parse('a=b&a[1]=c', { arrayLimit: 20 }), { a: ['b', 'c'] });
  222. st.deepEqual(qs.parse('a=b&a[]=c', { arrayLimit: 0 }), { a: { 0: 'b', 1: 'c' } });
  223. st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] });
  224. st.end();
  225. });
  226. t.test('parses a nested array', function (st) {
  227. st.deepEqual(qs.parse('a[b][]=c&a[b][]=d'), { a: { b: ['c', 'd'] } });
  228. st.deepEqual(qs.parse('a[>=]=25'), { a: { '>=': '25' } });
  229. st.end();
  230. });
  231. t.test('parses keys with literal [] inside a bracket group (#493)', function (st) {
  232. // A bracket pair inside a bracket group should be treated literally as part of the key
  233. st.deepEqual(
  234. qs.parse('search[withbracket[]]=foobar'),
  235. { search: { 'withbracket[]': 'foobar' } },
  236. 'treats inner [] literally when inside a bracket group'
  237. );
  238. // Single-level variant
  239. st.deepEqual(
  240. qs.parse('a[b[]]=c'),
  241. { a: { 'b[]': 'c' } },
  242. 'keeps "b[]" as a literal key'
  243. );
  244. // Nested with an array push on the outer level
  245. st.deepEqual(
  246. qs.parse('list[][x[]]=y'),
  247. { list: [{ 'x[]': 'y' }] },
  248. 'preserves inner [] while still treating outer [] as array push'
  249. );
  250. // Multiple nested bracket pairs: inner [] remains literal as part of the key
  251. st.deepEqual(
  252. qs.parse('a[b[c[]]]=d'),
  253. { a: { 'b[c[]]': 'd' } },
  254. 'treats "b[c[]]" as a literal key inside the bracket group'
  255. );
  256. // Depth limits with literal brackets: preserve inner [] while limiting bracket-group parsing
  257. st.deepEqual(
  258. qs.parse('a[b[c[]]][d]=e', { depth: 1 }),
  259. { a: { 'b[c[]]': { '[d]': 'e' } } },
  260. 'respects depth: 1 and preserves literal inner [] in the parsed key'
  261. );
  262. // Unterminated inner bracket group is wrapped as a literal remainder segment
  263. st.deepEqual(
  264. qs.parse('a[[]b=c'),
  265. { a: { '[[]b': 'c' } },
  266. 'handles unterminated inner bracket groups without throwing'
  267. );
  268. st.end();
  269. });
  270. t.test('allows to specify array indices', function (st) {
  271. st.deepEqual(qs.parse('a[1]=c&a[0]=b&a[2]=d'), { a: ['b', 'c', 'd'] });
  272. st.deepEqual(qs.parse('a[1]=c&a[0]=b'), { a: ['b', 'c'] });
  273. st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 20 }), { a: ['c'] });
  274. st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 0 }), { a: { 1: 'c' } });
  275. st.deepEqual(qs.parse('a[1]=c'), { a: ['c'] });
  276. st.end();
  277. });
  278. t.test('limits specific array indices to arrayLimit', function (st) {
  279. st.deepEqual(qs.parse('a[19]=a', { arrayLimit: 20 }), { a: ['a'] });
  280. st.deepEqual(qs.parse('a[20]=a', { arrayLimit: 20 }), { a: { 20: 'a' } });
  281. st.deepEqual(qs.parse('a[19]=a'), { a: ['a'] });
  282. st.deepEqual(qs.parse('a[20]=a'), { a: { 20: 'a' } });
  283. st.end();
  284. });
  285. t.deepEqual(qs.parse('a[12b]=c'), { a: { '12b': 'c' } }, 'supports keys that begin with a number');
  286. t.test('supports encoded = signs', function (st) {
  287. st.deepEqual(qs.parse('he%3Dllo=th%3Dere'), { 'he=llo': 'th=ere' });
  288. st.end();
  289. });
  290. t.test('is ok with url encoded strings', function (st) {
  291. st.deepEqual(qs.parse('a[b%20c]=d'), { a: { 'b c': 'd' } });
  292. st.deepEqual(qs.parse('a[b]=c%20d'), { a: { b: 'c d' } });
  293. st.end();
  294. });
  295. t.test('allows brackets in the value', function (st) {
  296. st.deepEqual(qs.parse('pets=["tobi"]'), { pets: '["tobi"]' });
  297. st.deepEqual(qs.parse('operators=[">=", "<="]'), { operators: '[">=", "<="]' });
  298. st.end();
  299. });
  300. t.test('allows empty values', function (st) {
  301. st.deepEqual(qs.parse(''), {});
  302. st.deepEqual(qs.parse(null), {});
  303. st.deepEqual(qs.parse(undefined), {});
  304. st.end();
  305. });
  306. t.test('transforms arrays to objects', function (st) {
  307. st.deepEqual(qs.parse('foo[0]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } });
  308. st.deepEqual(qs.parse('foo[bad]=baz&foo[0]=bar'), { foo: { bad: 'baz', 0: 'bar' } });
  309. st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar'), { foo: { bad: 'baz', 0: 'bar' } });
  310. st.deepEqual(qs.parse('foo[]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } });
  311. st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo'), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } });
  312. st.deepEqual(qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb'), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] });
  313. st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: false }), { a: { 0: 'b', t: 'u' } });
  314. st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: true }), { a: { 0: 'b', t: 'u', hasOwnProperty: 'c' } });
  315. st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: false }), { a: { 0: 'b', x: 'y' } });
  316. st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: true }), { a: { 0: 'b', hasOwnProperty: 'c', x: 'y' } });
  317. st.end();
  318. });
  319. t.test('transforms arrays to objects (dot notation)', function (st) {
  320. st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: 'baz' } });
  321. st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad.boo=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } });
  322. st.deepEqual(qs.parse('foo[0][0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } });
  323. st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15'], bar: '2' }] });
  324. st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15', '16'], bar: '2' }] });
  325. st.deepEqual(qs.parse('foo.bad=baz&foo[0]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } });
  326. st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } });
  327. st.deepEqual(qs.parse('foo[]=bar&foo.bad=baz', { allowDots: true }), { foo: { 0: 'bar', bad: 'baz' } });
  328. st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } });
  329. st.deepEqual(qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb', { allowDots: true }), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] });
  330. st.end();
  331. });
  332. t.test('correctly prunes undefined values when converting an array to an object', function (st) {
  333. st.deepEqual(qs.parse('a[2]=b&a[99999999]=c'), { a: { 2: 'b', 99999999: 'c' } });
  334. st.end();
  335. });
  336. t.test('supports malformed uri characters', function (st) {
  337. st.deepEqual(qs.parse('{%:%}', { strictNullHandling: true }), { '{%:%}': null });
  338. st.deepEqual(qs.parse('{%:%}='), { '{%:%}': '' });
  339. st.deepEqual(qs.parse('foo=%:%}'), { foo: '%:%}' });
  340. st.end();
  341. });
  342. t.test('doesn\'t produce empty keys', function (st) {
  343. st.deepEqual(qs.parse('_r=1&'), { _r: '1' });
  344. st.end();
  345. });
  346. t.test('cannot access Object prototype', function (st) {
  347. qs.parse('constructor[prototype][bad]=bad');
  348. qs.parse('bad[constructor][prototype][bad]=bad');
  349. st.equal(typeof Object.prototype.bad, 'undefined');
  350. st.end();
  351. });
  352. t.test('parses arrays of objects', function (st) {
  353. st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] });
  354. st.deepEqual(qs.parse('a[0][b]=c'), { a: [{ b: 'c' }] });
  355. st.end();
  356. });
  357. t.test('allows for empty strings in arrays', function (st) {
  358. st.deepEqual(qs.parse('a[]=b&a[]=&a[]=c'), { a: ['b', '', 'c'] });
  359. st.deepEqual(
  360. qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true, arrayLimit: 20 }),
  361. { a: ['b', null, 'c', ''] },
  362. 'with arrayLimit 20 + array indices: null then empty string works'
  363. );
  364. st.deepEqual(
  365. qs.parse('a[]=b&a[]&a[]=c&a[]=', { strictNullHandling: true, arrayLimit: 0 }),
  366. { a: { 0: 'b', 1: null, 2: 'c', 3: '' } },
  367. 'with arrayLimit 0 + array brackets: null then empty string works'
  368. );
  369. st.deepEqual(
  370. qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true, arrayLimit: 20 }),
  371. { a: ['b', '', 'c', null] },
  372. 'with arrayLimit 20 + array indices: empty string then null works'
  373. );
  374. st.deepEqual(
  375. qs.parse('a[]=b&a[]=&a[]=c&a[]', { strictNullHandling: true, arrayLimit: 0 }),
  376. { a: { 0: 'b', 1: '', 2: 'c', 3: null } },
  377. 'with arrayLimit 0 + array brackets: empty string then null works'
  378. );
  379. st.deepEqual(
  380. qs.parse('a[]=&a[]=b&a[]=c'),
  381. { a: ['', 'b', 'c'] },
  382. 'array brackets: empty strings work'
  383. );
  384. st.end();
  385. });
  386. t.test('compacts sparse arrays', function (st) {
  387. st.deepEqual(qs.parse('a[10]=1&a[2]=2', { arrayLimit: 20 }), { a: ['2', '1'] });
  388. st.deepEqual(qs.parse('a[1][b][2][c]=1', { arrayLimit: 20 }), { a: [{ b: [{ c: '1' }] }] });
  389. st.deepEqual(qs.parse('a[1][2][3][c]=1', { arrayLimit: 20 }), { a: [[[{ c: '1' }]]] });
  390. st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { arrayLimit: 20 }), { a: [[[{ c: ['1'] }]]] });
  391. st.end();
  392. });
  393. t.test('parses sparse arrays', function (st) {
  394. /* eslint no-sparse-arrays: 0 */
  395. st.deepEqual(qs.parse('a[4]=1&a[1]=2', { allowSparse: true }), { a: [, '2', , , '1'] });
  396. st.deepEqual(qs.parse('a[1][b][2][c]=1', { allowSparse: true }), { a: [, { b: [, , { c: '1' }] }] });
  397. st.deepEqual(qs.parse('a[1][2][3][c]=1', { allowSparse: true }), { a: [, [, , [, , , { c: '1' }]]] });
  398. st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { allowSparse: true }), { a: [, [, , [, , , { c: [, '1'] }]]] });
  399. st.end();
  400. });
  401. t.test('parses semi-parsed strings', function (st) {
  402. st.deepEqual(qs.parse({ 'a[b]': 'c' }), { a: { b: 'c' } });
  403. st.deepEqual(qs.parse({ 'a[b]': 'c', 'a[d]': 'e' }), { a: { b: 'c', d: 'e' } });
  404. st.end();
  405. });
  406. t.test('parses buffers correctly', function (st) {
  407. var b = SaferBuffer.from('test');
  408. st.deepEqual(qs.parse({ a: b }), { a: b });
  409. st.end();
  410. });
  411. t.test('parses jquery-param strings', function (st) {
  412. // readable = 'filter[0][]=int1&filter[0][]==&filter[0][]=77&filter[]=and&filter[2][]=int2&filter[2][]==&filter[2][]=8'
  413. var encoded = 'filter%5B0%5D%5B%5D=int1&filter%5B0%5D%5B%5D=%3D&filter%5B0%5D%5B%5D=77&filter%5B%5D=and&filter%5B2%5D%5B%5D=int2&filter%5B2%5D%5B%5D=%3D&filter%5B2%5D%5B%5D=8';
  414. var expected = { filter: [['int1', '=', '77'], 'and', ['int2', '=', '8']] };
  415. st.deepEqual(qs.parse(encoded), expected);
  416. st.end();
  417. });
  418. t.test('continues parsing when no parent is found', function (st) {
  419. st.deepEqual(qs.parse('[]=&a=b'), { 0: '', a: 'b' });
  420. st.deepEqual(qs.parse('[]&a=b', { strictNullHandling: true }), { 0: null, a: 'b' });
  421. st.deepEqual(qs.parse('[foo]=bar'), { foo: 'bar' });
  422. st.end();
  423. });
  424. t.test('does not error when parsing a very long array', function (st) {
  425. var str = 'a[]=a';
  426. while (Buffer.byteLength(str) < 128 * 1024) {
  427. str = str + '&' + str;
  428. }
  429. st.doesNotThrow(function () {
  430. qs.parse(str);
  431. });
  432. st.end();
  433. });
  434. t.test('does not throw when a native prototype has an enumerable property', function (st) {
  435. st.intercept(Object.prototype, 'crash', { value: '' });
  436. st.intercept(Array.prototype, 'crash', { value: '' });
  437. st.doesNotThrow(qs.parse.bind(null, 'a=b'));
  438. st.deepEqual(qs.parse('a=b'), { a: 'b' });
  439. st.doesNotThrow(qs.parse.bind(null, 'a[][b]=c'));
  440. st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] });
  441. st.end();
  442. });
  443. t.test('parses a string with an alternative string delimiter', function (st) {
  444. st.deepEqual(qs.parse('a=b;c=d', { delimiter: ';' }), { a: 'b', c: 'd' });
  445. st.end();
  446. });
  447. t.test('parses a string with an alternative RegExp delimiter', function (st) {
  448. st.deepEqual(qs.parse('a=b; c=d', { delimiter: /[;,] */ }), { a: 'b', c: 'd' });
  449. st.end();
  450. });
  451. t.test('does not use non-splittable objects as delimiters', function (st) {
  452. st.deepEqual(qs.parse('a=b&c=d', { delimiter: true }), { a: 'b', c: 'd' });
  453. st.end();
  454. });
  455. t.test('allows overriding parameter limit', function (st) {
  456. st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: 1 }), { a: 'b' });
  457. st.end();
  458. });
  459. t.test('allows setting the parameter limit to Infinity', function (st) {
  460. st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: Infinity }), { a: 'b', c: 'd' });
  461. st.end();
  462. });
  463. t.test('allows overriding array limit', function (st) {
  464. st.deepEqual(qs.parse('a[0]=b', { arrayLimit: -1 }), { a: { 0: 'b' } });
  465. st.deepEqual(qs.parse('a[0]=b', { arrayLimit: 0 }), { a: { 0: 'b' } });
  466. st.deepEqual(qs.parse('a[-1]=b', { arrayLimit: -1 }), { a: { '-1': 'b' } });
  467. st.deepEqual(qs.parse('a[-1]=b', { arrayLimit: 0 }), { a: { '-1': 'b' } });
  468. st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayLimit: -1 }), { a: { 0: 'b', 1: 'c' } });
  469. st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayLimit: 0 }), { a: { 0: 'b', 1: 'c' } });
  470. st.end();
  471. });
  472. t.test('allows disabling array parsing', function (st) {
  473. var indices = qs.parse('a[0]=b&a[1]=c', { parseArrays: false });
  474. st.deepEqual(indices, { a: { 0: 'b', 1: 'c' } });
  475. st.equal(Array.isArray(indices.a), false, 'parseArrays:false, indices case is not an array');
  476. var emptyBrackets = qs.parse('a[]=b', { parseArrays: false });
  477. st.deepEqual(emptyBrackets, { a: { 0: 'b' } });
  478. st.equal(Array.isArray(emptyBrackets.a), false, 'parseArrays:false, empty brackets case is not an array');
  479. st.end();
  480. });
  481. t.test('allows for query string prefix', function (st) {
  482. st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' });
  483. st.deepEqual(qs.parse('foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' });
  484. st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: false }), { '?foo': 'bar' });
  485. st.end();
  486. });
  487. t.test('parses an object', function (st) {
  488. var input = {
  489. 'user[name]': { 'pop[bob]': 3 },
  490. 'user[email]': null
  491. };
  492. var expected = {
  493. user: {
  494. name: { 'pop[bob]': 3 },
  495. email: null
  496. }
  497. };
  498. var result = qs.parse(input);
  499. st.deepEqual(result, expected);
  500. st.end();
  501. });
  502. t.test('parses string with comma as array divider', function (st) {
  503. st.deepEqual(qs.parse('foo=bar,tee', { comma: true }), { foo: ['bar', 'tee'] });
  504. st.deepEqual(qs.parse('foo[bar]=coffee,tee', { comma: true }), { foo: { bar: ['coffee', 'tee'] } });
  505. st.deepEqual(qs.parse('foo=', { comma: true }), { foo: '' });
  506. st.deepEqual(qs.parse('foo', { comma: true }), { foo: '' });
  507. st.deepEqual(qs.parse('foo', { comma: true, strictNullHandling: true }), { foo: null });
  508. // test cases inversed from from stringify tests
  509. st.deepEqual(qs.parse('a[0]=c'), { a: ['c'] });
  510. st.deepEqual(qs.parse('a[]=c'), { a: ['c'] });
  511. st.deepEqual(qs.parse('a[]=c', { comma: true }), { a: ['c'] });
  512. st.deepEqual(qs.parse('a[0]=c&a[1]=d'), { a: ['c', 'd'] });
  513. st.deepEqual(qs.parse('a[]=c&a[]=d'), { a: ['c', 'd'] });
  514. st.deepEqual(qs.parse('a=c,d', { comma: true }), { a: ['c', 'd'] });
  515. st.end();
  516. });
  517. t.test('parses values with comma as array divider', function (st) {
  518. st.deepEqual(qs.parse({ foo: 'bar,tee' }, { comma: false }), { foo: 'bar,tee' });
  519. st.deepEqual(qs.parse({ foo: 'bar,tee' }, { comma: true }), { foo: ['bar', 'tee'] });
  520. st.end();
  521. });
  522. t.test('use number decoder, parses string that has one number with comma option enabled', function (st) {
  523. var decoder = function (str, defaultDecoder, charset, type) {
  524. if (!isNaN(Number(str))) {
  525. return parseFloat(str);
  526. }
  527. return defaultDecoder(str, defaultDecoder, charset, type);
  528. };
  529. st.deepEqual(qs.parse('foo=1', { comma: true, decoder: decoder }), { foo: 1 });
  530. st.deepEqual(qs.parse('foo=0', { comma: true, decoder: decoder }), { foo: 0 });
  531. st.end();
  532. });
  533. t.test('parses brackets holds array of arrays when having two parts of strings with comma as array divider', function (st) {
  534. st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=4,5,6', { comma: true }), { foo: [['1', '2', '3'], ['4', '5', '6']] });
  535. st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=', { comma: true }), { foo: [['1', '2', '3'], ''] });
  536. st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=,', { comma: true }), { foo: [['1', '2', '3'], ['', '']] });
  537. st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=a', { comma: true }), { foo: [['1', '2', '3'], 'a'] });
  538. st.end();
  539. });
  540. t.test('parses url-encoded brackets holds array of arrays when having two parts of strings with comma as array divider', function (st) {
  541. st.deepEqual(qs.parse('foo%5B%5D=1,2,3&foo%5B%5D=4,5,6', { comma: true }), { foo: [['1', '2', '3'], ['4', '5', '6']] });
  542. st.deepEqual(qs.parse('foo%5B%5D=1,2,3&foo%5B%5D=', { comma: true }), { foo: [['1', '2', '3'], ''] });
  543. st.deepEqual(qs.parse('foo%5B%5D=1,2,3&foo%5B%5D=,', { comma: true }), { foo: [['1', '2', '3'], ['', '']] });
  544. st.deepEqual(qs.parse('foo%5B%5D=1,2,3&foo%5B%5D=a', { comma: true }), { foo: [['1', '2', '3'], 'a'] });
  545. st.end();
  546. });
  547. t.test('parses comma delimited array while having percent-encoded comma treated as normal text', function (st) {
  548. st.deepEqual(qs.parse('foo=a%2Cb', { comma: true }), { foo: 'a,b' });
  549. st.deepEqual(qs.parse('foo=a%2C%20b,d', { comma: true }), { foo: ['a, b', 'd'] });
  550. st.deepEqual(qs.parse('foo=a%2C%20b,c%2C%20d', { comma: true }), { foo: ['a, b', 'c, d'] });
  551. st.end();
  552. });
  553. t.test('parses an object in dot notation', function (st) {
  554. var input = {
  555. 'user.name': { 'pop[bob]': 3 },
  556. 'user.email.': null
  557. };
  558. var expected = {
  559. user: {
  560. name: { 'pop[bob]': 3 },
  561. email: null
  562. }
  563. };
  564. var result = qs.parse(input, { allowDots: true });
  565. st.deepEqual(result, expected);
  566. st.end();
  567. });
  568. t.test('parses an object and not child values', function (st) {
  569. var input = {
  570. 'user[name]': { 'pop[bob]': { test: 3 } },
  571. 'user[email]': null
  572. };
  573. var expected = {
  574. user: {
  575. name: { 'pop[bob]': { test: 3 } },
  576. email: null
  577. }
  578. };
  579. var result = qs.parse(input);
  580. st.deepEqual(result, expected);
  581. st.end();
  582. });
  583. t.test('does not blow up when Buffer global is missing', function (st) {
  584. var restore = mockProperty(global, 'Buffer', { 'delete': true });
  585. var result = qs.parse('a=b&c=d');
  586. restore();
  587. st.deepEqual(result, { a: 'b', c: 'd' });
  588. st.end();
  589. });
  590. t.test('does not crash when parsing circular references', function (st) {
  591. var a = {};
  592. a.b = a;
  593. var parsed;
  594. st.doesNotThrow(function () {
  595. parsed = qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a });
  596. });
  597. st.equal('foo' in parsed, true, 'parsed has "foo" property');
  598. st.equal('bar' in parsed.foo, true);
  599. st.equal('baz' in parsed.foo, true);
  600. st.equal(parsed.foo.bar, 'baz');
  601. st.deepEqual(parsed.foo.baz, a);
  602. st.end();
  603. });
  604. t.test('does not crash when parsing deep objects', function (st) {
  605. var parsed;
  606. var str = 'foo';
  607. for (var i = 0; i < 5000; i++) {
  608. str += '[p]';
  609. }
  610. str += '=bar';
  611. st.doesNotThrow(function () {
  612. parsed = qs.parse(str, { depth: 5000 });
  613. });
  614. st.equal('foo' in parsed, true, 'parsed has "foo" property');
  615. var depth = 0;
  616. var ref = parsed.foo;
  617. while ((ref = ref.p)) {
  618. depth += 1;
  619. }
  620. st.equal(depth, 5000, 'parsed is 5000 properties deep');
  621. st.end();
  622. });
  623. t.test('parses null objects correctly', { skip: !hasProto }, function (st) {
  624. var a = { __proto__: null, b: 'c' };
  625. st.deepEqual(qs.parse(a), { b: 'c' });
  626. var result = qs.parse({ a: a });
  627. st.equal('a' in result, true, 'result has "a" property');
  628. st.deepEqual(result.a, a);
  629. st.end();
  630. });
  631. t.test('parses dates correctly', function (st) {
  632. var now = new Date();
  633. st.deepEqual(qs.parse({ a: now }), { a: now });
  634. st.end();
  635. });
  636. t.test('parses regular expressions correctly', function (st) {
  637. var re = /^test$/;
  638. st.deepEqual(qs.parse({ a: re }), { a: re });
  639. st.end();
  640. });
  641. t.test('does not allow overwriting prototype properties', function (st) {
  642. st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: false }), {});
  643. st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: false }), {});
  644. st.deepEqual(
  645. qs.parse('toString', { allowPrototypes: false }),
  646. {},
  647. 'bare "toString" results in {}'
  648. );
  649. st.end();
  650. });
  651. t.test('can allow overwriting prototype properties', function (st) {
  652. st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }), { a: { hasOwnProperty: 'b' } });
  653. st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: true }), { hasOwnProperty: 'b' });
  654. st.deepEqual(
  655. qs.parse('toString', { allowPrototypes: true }),
  656. { toString: '' },
  657. 'bare "toString" results in { toString: "" }'
  658. );
  659. st.end();
  660. });
  661. t.test('does not crash when the global Object prototype is frozen', { skip: !hasPropertyDescriptors || !hasOverrideMistake }, function (st) {
  662. // We can't actually freeze the global Object prototype as that will interfere with other tests, and once an object is frozen, it
  663. // can't be unfrozen. Instead, we add a new non-writable property to simulate this.
  664. st.teardown(mockProperty(Object.prototype, 'frozenProp', { value: 'foo', nonWritable: true, nonEnumerable: true }));
  665. st['throws'](
  666. function () {
  667. var obj = {};
  668. obj.frozenProp = 'bar';
  669. },
  670. // node < 6 has a different error message
  671. /^TypeError: Cannot assign to read only property 'frozenProp' of (?:object '#<Object>'|#<Object>)/,
  672. 'regular assignment of an inherited non-writable property throws'
  673. );
  674. var parsed;
  675. st.doesNotThrow(
  676. function () {
  677. parsed = qs.parse('frozenProp', { allowPrototypes: false });
  678. },
  679. 'parsing a nonwritable Object.prototype property does not throw'
  680. );
  681. st.deepEqual(parsed, {}, 'bare "frozenProp" results in {}');
  682. st.end();
  683. });
  684. t.test('params starting with a closing bracket', function (st) {
  685. st.deepEqual(qs.parse(']=toString'), { ']': 'toString' });
  686. st.deepEqual(qs.parse(']]=toString'), { ']]': 'toString' });
  687. st.deepEqual(qs.parse(']hello]=toString'), { ']hello]': 'toString' });
  688. st.end();
  689. });
  690. t.test('params starting with a starting bracket', function (st) {
  691. st.deepEqual(qs.parse('[=toString'), { '[': 'toString' });
  692. st.deepEqual(qs.parse('[[=toString'), { '[[': 'toString' });
  693. st.deepEqual(qs.parse('[hello[=toString'), { '[hello[': 'toString' });
  694. st.end();
  695. });
  696. t.test('add keys to objects', function (st) {
  697. st.deepEqual(
  698. qs.parse('a[b]=c&a=d', { strictMerge: false }),
  699. { a: { b: 'c', d: true } },
  700. 'can add keys to objects'
  701. );
  702. st.deepEqual(
  703. qs.parse('a[b]=c&a=toString', { strictMerge: false }),
  704. { a: { b: 'c' } },
  705. 'can not overwrite prototype'
  706. );
  707. st.deepEqual(
  708. qs.parse('a[b]=c&a=toString', { strictMerge: false, allowPrototypes: true }),
  709. { a: { b: 'c', toString: true } },
  710. 'can overwrite prototype with allowPrototypes true'
  711. );
  712. st.deepEqual(
  713. qs.parse('a[b]=c&a=toString', { strictMerge: false, plainObjects: true }),
  714. { __proto__: null, a: { __proto__: null, b: 'c', toString: true } },
  715. 'can overwrite prototype with plainObjects true'
  716. );
  717. st.end();
  718. });
  719. t.test('strictMerge wraps object and primitive into an array', function (st) {
  720. st.deepEqual(
  721. qs.parse('a[b]=c&a=d'),
  722. { a: [{ b: 'c' }, 'd'] },
  723. 'object then primitive produces array'
  724. );
  725. st.deepEqual(
  726. qs.parse('a=d&a[b]=c'),
  727. { a: ['d', { b: 'c' }] },
  728. 'primitive then object produces array'
  729. );
  730. st.deepEqual(
  731. qs.parse('a[b]=c&a=toString'),
  732. { a: [{ b: 'c' }, 'toString'] },
  733. 'prototype-colliding value is preserved in array'
  734. );
  735. st.deepEqual(
  736. qs.parse('a[b]=c&a=toString', { plainObjects: true }),
  737. { __proto__: null, a: [{ __proto__: null, b: 'c' }, 'toString'] },
  738. 'plainObjects preserved in array wrapping'
  739. );
  740. st.end();
  741. });
  742. t.test('dunder proto is ignored', function (st) {
  743. var payload = 'categories[__proto__]=login&categories[__proto__]&categories[length]=42';
  744. var result = qs.parse(payload, { allowPrototypes: true });
  745. st.deepEqual(
  746. result,
  747. {
  748. categories: {
  749. length: '42'
  750. }
  751. },
  752. 'silent [[Prototype]] payload'
  753. );
  754. var plainResult = qs.parse(payload, { allowPrototypes: true, plainObjects: true });
  755. st.deepEqual(
  756. plainResult,
  757. {
  758. __proto__: null,
  759. categories: {
  760. __proto__: null,
  761. length: '42'
  762. }
  763. },
  764. 'silent [[Prototype]] payload: plain objects'
  765. );
  766. var query = qs.parse('categories[__proto__]=cats&categories[__proto__]=dogs&categories[some][json]=toInject', { allowPrototypes: true });
  767. st.notOk(Array.isArray(query.categories), 'is not an array');
  768. st.notOk(query.categories instanceof Array, 'is not instanceof an array');
  769. st.deepEqual(query.categories, { some: { json: 'toInject' } });
  770. st.equal(JSON.stringify(query.categories), '{"some":{"json":"toInject"}}', 'stringifies as a non-array');
  771. st.deepEqual(
  772. qs.parse('foo[__proto__][hidden]=value&foo[bar]=stuffs', { allowPrototypes: true }),
  773. {
  774. foo: {
  775. bar: 'stuffs'
  776. }
  777. },
  778. 'hidden values'
  779. );
  780. st.deepEqual(
  781. qs.parse('foo[__proto__][hidden]=value&foo[bar]=stuffs', { allowPrototypes: true, plainObjects: true }),
  782. {
  783. __proto__: null,
  784. foo: {
  785. __proto__: null,
  786. bar: 'stuffs'
  787. }
  788. },
  789. 'hidden values: plain objects'
  790. );
  791. st.end();
  792. });
  793. t.test('can return null objects', { skip: !hasProto }, function (st) {
  794. var expected = {
  795. __proto__: null,
  796. a: {
  797. __proto__: null,
  798. b: 'c',
  799. hasOwnProperty: 'd'
  800. }
  801. };
  802. st.deepEqual(qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true }), expected);
  803. st.deepEqual(qs.parse(null, { plainObjects: true }), { __proto__: null });
  804. var expectedArray = {
  805. __proto__: null,
  806. a: {
  807. __proto__: null,
  808. 0: 'b',
  809. c: 'd'
  810. }
  811. };
  812. st.deepEqual(qs.parse('a[]=b&a[c]=d', { plainObjects: true }), expectedArray);
  813. st.end();
  814. });
  815. t.test('can parse with custom encoding', function (st) {
  816. st.deepEqual(qs.parse('%8c%a7=%91%e5%8d%e3%95%7b', {
  817. decoder: function (str) {
  818. var reg = /%([0-9A-F]{2})/ig;
  819. var result = [];
  820. var parts = reg.exec(str);
  821. while (parts) {
  822. result.push(parseInt(parts[1], 16));
  823. parts = reg.exec(str);
  824. }
  825. return String(iconv.decode(SaferBuffer.from(result), 'shift_jis'));
  826. }
  827. }), { 県: '大阪府' });
  828. st.end();
  829. });
  830. t.test('receives the default decoder as a second argument', function (st) {
  831. st.plan(1);
  832. qs.parse('a', {
  833. decoder: function (str, defaultDecoder) {
  834. st.equal(defaultDecoder, utils.decode);
  835. }
  836. });
  837. st.end();
  838. });
  839. t.test('throws error with wrong decoder', function (st) {
  840. st['throws'](function () {
  841. qs.parse({}, { decoder: 'string' });
  842. }, new TypeError('Decoder has to be a function.'));
  843. st.end();
  844. });
  845. t.test('does not mutate the options argument', function (st) {
  846. var options = {};
  847. qs.parse('a[b]=true', options);
  848. st.deepEqual(options, {});
  849. st.end();
  850. });
  851. t.test('throws if an invalid charset is specified', function (st) {
  852. st['throws'](function () {
  853. qs.parse('a=b', { charset: 'foobar' });
  854. }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'));
  855. st.end();
  856. });
  857. t.test('parses an iso-8859-1 string if asked to', function (st) {
  858. st.deepEqual(qs.parse('%A2=%BD', { charset: 'iso-8859-1' }), { '¢': '½' });
  859. st.end();
  860. });
  861. var urlEncodedCheckmarkInUtf8 = '%E2%9C%93';
  862. var urlEncodedOSlashInUtf8 = '%C3%B8';
  863. var urlEncodedNumCheckmark = '%26%2310003%3B';
  864. var urlEncodedNumSmiley = '%26%239786%3B';
  865. t.test('prefers an utf-8 charset specified by the utf8 sentinel to a default charset of iso-8859-1', function (st) {
  866. st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'iso-8859-1' }), { ø: 'ø' });
  867. st.end();
  868. });
  869. t.test('prefers an iso-8859-1 charset specified by the utf8 sentinel to a default charset of utf-8', function (st) {
  870. st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { 'ø': 'ø' });
  871. st.end();
  872. });
  873. t.test('does not require the utf8 sentinel to be defined before the parameters whose decoding it affects', function (st) {
  874. st.deepEqual(qs.parse('a=' + urlEncodedOSlashInUtf8 + '&utf8=' + urlEncodedNumCheckmark, { charsetSentinel: true, charset: 'utf-8' }), { a: 'ø' });
  875. st.end();
  876. });
  877. t.test('ignores an utf8 sentinel with an unknown value', function (st) {
  878. st.deepEqual(qs.parse('utf8=foo&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { ø: 'ø' });
  879. st.end();
  880. });
  881. t.test('uses the utf8 sentinel to switch to utf-8 when no default charset is given', function (st) {
  882. st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { ø: 'ø' });
  883. st.end();
  884. });
  885. t.test('uses the utf8 sentinel to switch to iso-8859-1 when no default charset is given', function (st) {
  886. st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { 'ø': 'ø' });
  887. st.end();
  888. });
  889. t.test('interprets numeric entities in iso-8859-1 when `interpretNumericEntities`', function (st) {
  890. st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1', interpretNumericEntities: true }), { foo: '☺' });
  891. st.end();
  892. });
  893. t.test('handles a custom decoder returning `null`, in the `iso-8859-1` charset, when `interpretNumericEntities`', function (st) {
  894. st.deepEqual(qs.parse('foo=&bar=' + urlEncodedNumSmiley, {
  895. charset: 'iso-8859-1',
  896. decoder: function (str, defaultDecoder, charset) {
  897. return str ? defaultDecoder(str, defaultDecoder, charset) : null;
  898. },
  899. interpretNumericEntities: true
  900. }), { foo: null, bar: '☺' });
  901. st.end();
  902. });
  903. t.test('handles a custom decoder returning `null`, with a string key of `null`', function (st) {
  904. st.deepEqual(
  905. qs.parse('null=1&ToNull=2', {
  906. decoder: function (str, defaultDecoder, charset) {
  907. return str === 'ToNull' ? null : defaultDecoder(str, defaultDecoder, charset);
  908. }
  909. }),
  910. { 'null': '1' },
  911. '"null" key is not overridden by `null` decoder result'
  912. );
  913. st.end();
  914. });
  915. t.test('does not interpret numeric entities in iso-8859-1 when `interpretNumericEntities` is absent', function (st) {
  916. st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1' }), { foo: '&#9786;' });
  917. st.end();
  918. });
  919. t.test('does not interpret numeric entities when the charset is utf-8, even when `interpretNumericEntities`', function (st) {
  920. st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'utf-8', interpretNumericEntities: true }), { foo: '&#9786;' });
  921. st.end();
  922. });
  923. t.test('interpretNumericEntities with comma:true and iso charset does not crash', function (st) {
  924. st.deepEqual(
  925. qs.parse('b&a[]=1,' + urlEncodedNumSmiley, { comma: true, charset: 'iso-8859-1', interpretNumericEntities: true }),
  926. { b: '', a: ['1,☺'] }
  927. );
  928. st.end();
  929. });
  930. t.test('does not interpret %uXXXX syntax in iso-8859-1 mode', function (st) {
  931. st.deepEqual(qs.parse('%u263A=%u263A', { charset: 'iso-8859-1' }), { '%u263A': '%u263A' });
  932. st.end();
  933. });
  934. t.test('allows for decoding keys and values differently', function (st) {
  935. var decoder = function (str, defaultDecoder, charset, type) {
  936. if (type === 'key') {
  937. return defaultDecoder(str, defaultDecoder, charset, type).toLowerCase();
  938. }
  939. if (type === 'value') {
  940. return defaultDecoder(str, defaultDecoder, charset, type).toUpperCase();
  941. }
  942. throw 'this should never happen! type: ' + type;
  943. };
  944. st.deepEqual(qs.parse('KeY=vAlUe', { decoder: decoder }), { key: 'VALUE' });
  945. var noopDecoder = function () { return 'x'; };
  946. noopDecoder();
  947. st['throws'](
  948. function () { decoder('x', noopDecoder, 'utf-8', 'unknown'); },
  949. 'this should never happen! type: unknown',
  950. 'decoder throws for unexpected type'
  951. );
  952. st.end();
  953. });
  954. t.test('parameter limit tests', function (st) {
  955. st.test('does not throw error when within parameter limit', function (sst) {
  956. var result = qs.parse('a=1&b=2&c=3', { parameterLimit: 5, throwOnLimitExceeded: true });
  957. sst.deepEqual(result, { a: '1', b: '2', c: '3' }, 'parses without errors');
  958. sst.end();
  959. });
  960. st.test('throws error when throwOnLimitExceeded is present but not boolean', function (sst) {
  961. sst['throws'](
  962. function () {
  963. qs.parse('a=1&b=2&c=3&d=4&e=5&f=6', { parameterLimit: 3, throwOnLimitExceeded: 'true' });
  964. },
  965. new TypeError('`throwOnLimitExceeded` option must be a boolean'),
  966. 'throws error when throwOnLimitExceeded is present and not boolean'
  967. );
  968. sst.end();
  969. });
  970. st.test('throws error when parameter limit exceeded', function (sst) {
  971. sst['throws'](
  972. function () {
  973. qs.parse('a=1&b=2&c=3&d=4&e=5&f=6', { parameterLimit: 3, throwOnLimitExceeded: true });
  974. },
  975. new RangeError('Parameter limit exceeded. Only 3 parameters allowed.'),
  976. 'throws error when parameter limit is exceeded'
  977. );
  978. sst['throws'](
  979. function () {
  980. qs.parse('a=1&b=2', { parameterLimit: 1, throwOnLimitExceeded: true });
  981. },
  982. new RangeError('Parameter limit exceeded. Only 1 parameter allowed.'),
  983. 'throws error with singular "parameter" when parameterLimit is 1'
  984. );
  985. sst.end();
  986. });
  987. st.test('silently truncates when throwOnLimitExceeded is not given', function (sst) {
  988. var result = qs.parse('a=1&b=2&c=3&d=4&e=5', { parameterLimit: 3 });
  989. sst.deepEqual(result, { a: '1', b: '2', c: '3' }, 'parses and truncates silently');
  990. sst.end();
  991. });
  992. st.test('silently truncates when parameter limit exceeded without error', function (sst) {
  993. var result = qs.parse('a=1&b=2&c=3&d=4&e=5', { parameterLimit: 3, throwOnLimitExceeded: false });
  994. sst.deepEqual(result, { a: '1', b: '2', c: '3' }, 'parses and truncates silently');
  995. sst.end();
  996. });
  997. st.test('allows unlimited parameters when parameterLimit set to Infinity', function (sst) {
  998. var result = qs.parse('a=1&b=2&c=3&d=4&e=5&f=6', { parameterLimit: Infinity });
  999. sst.deepEqual(result, { a: '1', b: '2', c: '3', d: '4', e: '5', f: '6' }, 'parses all parameters without truncation');
  1000. sst.end();
  1001. });
  1002. st.test('allows unlimited parameters when parameterLimit is Infinity and throwOnLimitExceeded is true', function (sst) {
  1003. var result = qs.parse('a=1&b=2&c=3&d=4&e=5&f=6', { parameterLimit: Infinity, throwOnLimitExceeded: true });
  1004. sst.deepEqual(result, { a: '1', b: '2', c: '3', d: '4', e: '5', f: '6' }, 'parses all parameters without truncation or throwing');
  1005. sst.end();
  1006. });
  1007. st.end();
  1008. });
  1009. t.test('array limit tests', function (st) {
  1010. st.test('does not throw error when array is within limit', function (sst) {
  1011. var result = qs.parse('a[]=1&a[]=2&a[]=3', { arrayLimit: 5, throwOnLimitExceeded: true });
  1012. sst.deepEqual(result, { a: ['1', '2', '3'] }, 'parses array without errors');
  1013. sst.end();
  1014. });
  1015. st.test('throws error when throwOnLimitExceeded is present but not boolean for array limit', function (sst) {
  1016. sst['throws'](
  1017. function () {
  1018. qs.parse('a[]=1&a[]=2&a[]=3&a[]=4', { arrayLimit: 3, throwOnLimitExceeded: 'true' });
  1019. },
  1020. new TypeError('`throwOnLimitExceeded` option must be a boolean'),
  1021. 'throws error when throwOnLimitExceeded is present and not boolean for array limit'
  1022. );
  1023. sst.end();
  1024. });
  1025. st.test('throws error when array limit exceeded', function (sst) {
  1026. // 4 elements exceeds limit of 3
  1027. sst['throws'](
  1028. function () {
  1029. qs.parse('a[]=1&a[]=2&a[]=3&a[]=4', { arrayLimit: 3, throwOnLimitExceeded: true });
  1030. },
  1031. new RangeError('Array limit exceeded. Only 3 elements allowed in an array.'),
  1032. 'throws error when array limit is exceeded'
  1033. );
  1034. sst.end();
  1035. });
  1036. st.test('does not throw when at limit', function (sst) {
  1037. // 3 elements = limit of 3, should not throw
  1038. var result = qs.parse('a[]=1&a[]=2&a[]=3', { arrayLimit: 3, throwOnLimitExceeded: true });
  1039. sst.ok(Array.isArray(result.a), 'result is an array');
  1040. sst.deepEqual(result.a, ['1', '2', '3'], 'all values present');
  1041. sst.end();
  1042. });
  1043. st.test('converts array to object if length is greater than limit', function (sst) {
  1044. var result = qs.parse('a[1]=1&a[2]=2&a[3]=3&a[4]=4&a[5]=5&a[6]=6', { arrayLimit: 5 });
  1045. sst.deepEqual(result, { a: { 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6' } }, 'parses into object if array length is greater than limit');
  1046. sst.end();
  1047. });
  1048. st.test('throws error when indexed notation exceeds arrayLimit with throwOnLimitExceeded', function (sst) {
  1049. sst['throws'](
  1050. function () {
  1051. qs.parse('a[1001]=b', { arrayLimit: 1000, throwOnLimitExceeded: true });
  1052. },
  1053. new RangeError('Array limit exceeded. Only 1000 elements allowed in an array.'),
  1054. 'throws error for a single index exceeding arrayLimit'
  1055. );
  1056. sst['throws'](
  1057. function () {
  1058. qs.parse('a[0]=1&a[1]=2&a[2]=3&a[10]=4', { arrayLimit: 6, throwOnLimitExceeded: true, allowSparse: true });
  1059. },
  1060. new RangeError('Array limit exceeded. Only 6 elements allowed in an array.'),
  1061. 'throws error when a sparse index exceeds arrayLimit'
  1062. );
  1063. sst['throws'](
  1064. function () {
  1065. qs.parse('a[2]=b', { arrayLimit: 1, throwOnLimitExceeded: true });
  1066. },
  1067. new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
  1068. 'throws error with singular "element" when arrayLimit is 1'
  1069. );
  1070. sst.end();
  1071. });
  1072. st.test('does not throw for indexed notation within arrayLimit with throwOnLimitExceeded', function (sst) {
  1073. var result = qs.parse('a[4]=b', { arrayLimit: 5, throwOnLimitExceeded: true, allowSparse: true });
  1074. sst.ok(Array.isArray(result.a), 'result is an array');
  1075. sst.equal(result.a.length, 5, 'array has correct length');
  1076. sst.equal(result.a[4], 'b', 'value at index 4 is correct');
  1077. sst.end();
  1078. });
  1079. st.test('silently converts to object for indexed notation exceeding arrayLimit without throwOnLimitExceeded', function (sst) {
  1080. var result = qs.parse('a[1001]=b', { arrayLimit: 1000 });
  1081. sst.deepEqual(result, { a: { 1001: 'b' } }, 'converts to object without throwing');
  1082. sst.end();
  1083. });
  1084. st.test('throws when duplicate bracket keys exceed arrayLimit with throwOnLimitExceeded', function (sst) {
  1085. sst['throws'](
  1086. function () {
  1087. qs.parse('a[]=1&a[]=2&a[]=3&a[]=4&a[]=5&a[]=6', { arrayLimit: 5, throwOnLimitExceeded: true });
  1088. },
  1089. new RangeError('Array limit exceeded. Only 5 elements allowed in an array.'),
  1090. 'throws error when duplicate bracket notation exceeds array limit'
  1091. );
  1092. sst.end();
  1093. });
  1094. st.end();
  1095. });
  1096. t.end();
  1097. });
  1098. test('parses empty keys', function (t) {
  1099. emptyTestCases.forEach(function (testCase) {
  1100. t.test('skips empty string key with ' + testCase.input, function (st) {
  1101. st.deepEqual(qs.parse(testCase.input), testCase.noEmptyKeys);
  1102. st.end();
  1103. });
  1104. });
  1105. });
  1106. test('`duplicates` option', function (t) {
  1107. v.nonStrings.concat('not a valid option').forEach(function (invalidOption) {
  1108. if (typeof invalidOption !== 'undefined') {
  1109. t['throws'](
  1110. function () { qs.parse('', { duplicates: invalidOption }); },
  1111. TypeError,
  1112. 'throws on invalid option: ' + inspect(invalidOption)
  1113. );
  1114. }
  1115. });
  1116. t.deepEqual(
  1117. qs.parse('foo=bar&foo=baz'),
  1118. { foo: ['bar', 'baz'] },
  1119. 'duplicates: default, combine'
  1120. );
  1121. t.deepEqual(
  1122. qs.parse('foo=bar&foo=baz', { duplicates: 'combine' }),
  1123. { foo: ['bar', 'baz'] },
  1124. 'duplicates: combine'
  1125. );
  1126. t.deepEqual(
  1127. qs.parse('foo=bar&foo=baz', { duplicates: 'first' }),
  1128. { foo: 'bar' },
  1129. 'duplicates: first'
  1130. );
  1131. t.deepEqual(
  1132. qs.parse('foo=bar&foo=baz', { duplicates: 'last' }),
  1133. { foo: 'baz' },
  1134. 'duplicates: last'
  1135. );
  1136. t.test('bracket notation always combines regardless of duplicates', function (st) {
  1137. st.deepEqual(
  1138. qs.parse('a=1&a=2&b[]=1&b[]=2', { duplicates: 'last' }),
  1139. { a: '2', b: ['1', '2'] },
  1140. 'duplicates last: unbracketed takes last, bracketed combines'
  1141. );
  1142. st.deepEqual(
  1143. qs.parse('b[]=1&b[]=2', { duplicates: 'last' }),
  1144. { b: ['1', '2'] },
  1145. 'duplicates last: bracketed always combines'
  1146. );
  1147. st.deepEqual(
  1148. qs.parse('b[]=1&b[]=2', { duplicates: 'first' }),
  1149. { b: ['1', '2'] },
  1150. 'duplicates first: bracketed always combines'
  1151. );
  1152. st.deepEqual(
  1153. qs.parse('a=1&a=2&b[]=1&b[]=2', { duplicates: 'first' }),
  1154. { a: '1', b: ['1', '2'] },
  1155. 'duplicates first: unbracketed takes first, bracketed combines'
  1156. );
  1157. st.end();
  1158. });
  1159. t.end();
  1160. });
  1161. test('qs strictDepth option - throw cases', function (t) {
  1162. t.test('throws an exception when depth exceeds the limit with strictDepth: true', function (st) {
  1163. st['throws'](
  1164. function () {
  1165. qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1, strictDepth: true });
  1166. },
  1167. RangeError,
  1168. 'throws RangeError'
  1169. );
  1170. st.end();
  1171. });
  1172. t.test('throws an exception for multiple nested arrays with strictDepth: true', function (st) {
  1173. st['throws'](
  1174. function () {
  1175. qs.parse('a[0][1][2][3][4]=b', { depth: 3, strictDepth: true });
  1176. },
  1177. RangeError,
  1178. 'throws RangeError'
  1179. );
  1180. st.end();
  1181. });
  1182. t.test('throws an exception for nested objects and arrays with strictDepth: true', function (st) {
  1183. st['throws'](
  1184. function () {
  1185. qs.parse('a[b][c][0][d][e]=f', { depth: 3, strictDepth: true });
  1186. },
  1187. RangeError,
  1188. 'throws RangeError'
  1189. );
  1190. st.end();
  1191. });
  1192. t.test('throws an exception for different types of values with strictDepth: true', function (st) {
  1193. st['throws'](
  1194. function () {
  1195. qs.parse('a[b][c][d][e]=true&a[b][c][d][f]=42', { depth: 3, strictDepth: true });
  1196. },
  1197. RangeError,
  1198. 'throws RangeError'
  1199. );
  1200. st.end();
  1201. });
  1202. });
  1203. test('qs strictDepth option - non-throw cases', function (t) {
  1204. t.test('when depth is 0 and strictDepth true, do not throw', function (st) {
  1205. st.doesNotThrow(
  1206. function () {
  1207. qs.parse('a[b][c][d][e]=true&a[b][c][d][f]=42', { depth: 0, strictDepth: true });
  1208. },
  1209. RangeError,
  1210. 'does not throw RangeError'
  1211. );
  1212. st.end();
  1213. });
  1214. t.test('parses successfully when depth is within the limit with strictDepth: true', function (st) {
  1215. st.doesNotThrow(
  1216. function () {
  1217. var result = qs.parse('a[b]=c', { depth: 1, strictDepth: true });
  1218. st.deepEqual(result, { a: { b: 'c' } }, 'parses correctly');
  1219. }
  1220. );
  1221. st.end();
  1222. });
  1223. t.test('does not throw an exception when depth exceeds the limit with strictDepth: false', function (st) {
  1224. st.doesNotThrow(
  1225. function () {
  1226. var result = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 });
  1227. st.deepEqual(result, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } }, 'parses with depth limit');
  1228. }
  1229. );
  1230. st.end();
  1231. });
  1232. t.test('parses successfully when depth is within the limit with strictDepth: false', function (st) {
  1233. st.doesNotThrow(
  1234. function () {
  1235. var result = qs.parse('a[b]=c', { depth: 1 });
  1236. st.deepEqual(result, { a: { b: 'c' } }, 'parses correctly');
  1237. }
  1238. );
  1239. st.end();
  1240. });
  1241. t.test('does not throw when depth is exactly at the limit with strictDepth: true', function (st) {
  1242. st.doesNotThrow(
  1243. function () {
  1244. var result = qs.parse('a[b][c]=d', { depth: 2, strictDepth: true });
  1245. st.deepEqual(result, { a: { b: { c: 'd' } } }, 'parses correctly');
  1246. }
  1247. );
  1248. st.end();
  1249. });
  1250. });
  1251. test('DOS', function (t) {
  1252. var arr = [];
  1253. for (var i = 0; i < 105; i++) {
  1254. arr[arr.length] = 'x';
  1255. }
  1256. var attack = 'a[]=' + arr.join('&a[]=');
  1257. var result = qs.parse(attack, { arrayLimit: 100 });
  1258. t.notOk(Array.isArray(result.a), 'arrayLimit is respected: result is an object, not an array');
  1259. t.equal(Object.keys(result.a).length, 105, 'all values are preserved');
  1260. t.end();
  1261. });
  1262. test('arrayLimit boundary conditions', function (t) {
  1263. // arrayLimit is the max number of elements allowed in an array
  1264. t.test('exactly at the limit stays as array', function (st) {
  1265. // 3 elements = limit of 3
  1266. var result = qs.parse('a[]=1&a[]=2&a[]=3', { arrayLimit: 3 });
  1267. st.ok(Array.isArray(result.a), 'result is an array when count equals limit');
  1268. st.deepEqual(result.a, ['1', '2', '3'], 'all values present');
  1269. st.end();
  1270. });
  1271. t.test('one over the limit converts to object', function (st) {
  1272. // 4 elements exceeds limit of 3
  1273. var result = qs.parse('a[]=1&a[]=2&a[]=3&a[]=4', { arrayLimit: 3 });
  1274. st.notOk(Array.isArray(result.a), 'result is not an array when over limit');
  1275. st.deepEqual(result.a, { 0: '1', 1: '2', 2: '3', 3: '4' }, 'all values preserved as object');
  1276. st.end();
  1277. });
  1278. t.test('arrayLimit 1 with one value', function (st) {
  1279. // 1 element = limit of 1
  1280. var result = qs.parse('a[]=1', { arrayLimit: 1 });
  1281. st.ok(Array.isArray(result.a), 'result is an array when count equals limit');
  1282. st.deepEqual(result.a, ['1'], 'value preserved as array');
  1283. st.end();
  1284. });
  1285. t.test('arrayLimit 1 with two values converts to object', function (st) {
  1286. // 2 elements exceeds limit of 1
  1287. var result = qs.parse('a[]=1&a[]=2', { arrayLimit: 1 });
  1288. st.notOk(Array.isArray(result.a), 'result is not an array');
  1289. st.deepEqual(result.a, { 0: '1', 1: '2' }, 'all values preserved as object');
  1290. st.end();
  1291. });
  1292. t.end();
  1293. });
  1294. test('comma + arrayLimit', function (t) {
  1295. t.test('comma-separated values within arrayLimit stay as array', function (st) {
  1296. var result = qs.parse('a=1,2,3', { comma: true, arrayLimit: 5 });
  1297. st.ok(Array.isArray(result.a), 'result is an array');
  1298. st.deepEqual(result.a, ['1', '2', '3'], 'all values present');
  1299. st.end();
  1300. });
  1301. t.test('comma-separated values exceeding arrayLimit convert to object', function (st) {
  1302. var result = qs.parse('a=1,2,3,4', { comma: true, arrayLimit: 3 });
  1303. st.notOk(Array.isArray(result.a), 'result is not an array when over limit');
  1304. st.deepEqual(result.a, { 0: '1', 1: '2', 2: '3', 3: '4' }, 'all values preserved as object');
  1305. st.end();
  1306. });
  1307. t.test('comma-separated values exceeding arrayLimit with throwOnLimitExceeded throws', function (st) {
  1308. st['throws'](
  1309. function () {
  1310. qs.parse('a=1,2,3,4', { comma: true, arrayLimit: 3, throwOnLimitExceeded: true });
  1311. },
  1312. new RangeError('Array limit exceeded. Only 3 elements allowed in an array.'),
  1313. 'throws error when comma-split exceeds array limit'
  1314. );
  1315. st['throws'](
  1316. function () {
  1317. qs.parse('a=1,2,3', { comma: true, arrayLimit: 1, throwOnLimitExceeded: true });
  1318. },
  1319. new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
  1320. 'throws error with singular "element" when arrayLimit is 1'
  1321. );
  1322. st.end();
  1323. });
  1324. t.test('comma-separated values at exactly arrayLimit stay as array', function (st) {
  1325. var result = qs.parse('a=1,2,3', { comma: true, arrayLimit: 3 });
  1326. st.ok(Array.isArray(result.a), 'result is an array when exactly at limit');
  1327. st.deepEqual(result.a, ['1', '2', '3'], 'all values present');
  1328. st.end();
  1329. });
  1330. t.end();
  1331. });
  1332. test('mixed array and object notation', function (t) {
  1333. t.test('array brackets with object key - under limit', function (st) {
  1334. st.deepEqual(
  1335. qs.parse('a[]=b&a[c]=d'),
  1336. { a: { 0: 'b', c: 'd' } },
  1337. 'mixing [] and [key] converts to object'
  1338. );
  1339. st.end();
  1340. });
  1341. t.test('array index with object key - under limit', function (st) {
  1342. st.deepEqual(
  1343. qs.parse('a[0]=b&a[c]=d'),
  1344. { a: { 0: 'b', c: 'd' } },
  1345. 'mixing [0] and [key] produces object'
  1346. );
  1347. st.end();
  1348. });
  1349. t.test('plain value with array brackets - under limit', function (st) {
  1350. st.deepEqual(
  1351. qs.parse('a=b&a[]=c', { arrayLimit: 20 }),
  1352. { a: ['b', 'c'] },
  1353. 'plain value combined with [] stays as array under limit'
  1354. );
  1355. st.end();
  1356. });
  1357. t.test('array brackets with plain value - under limit', function (st) {
  1358. st.deepEqual(
  1359. qs.parse('a[]=b&a=c', { arrayLimit: 20 }),
  1360. { a: ['b', 'c'] },
  1361. '[] combined with plain value stays as array under limit'
  1362. );
  1363. st.end();
  1364. });
  1365. t.test('plain value with array index - under limit', function (st) {
  1366. st.deepEqual(
  1367. qs.parse('a=b&a[0]=c', { arrayLimit: 20 }),
  1368. { a: ['b', 'c'] },
  1369. 'plain value combined with [0] stays as array under limit'
  1370. );
  1371. st.end();
  1372. });
  1373. t.test('multiple plain values with duplicates combine', function (st) {
  1374. st.deepEqual(
  1375. qs.parse('a=b&a=c&a=d', { arrayLimit: 20 }),
  1376. { a: ['b', 'c', 'd'] },
  1377. 'duplicate plain keys combine into array'
  1378. );
  1379. st.end();
  1380. });
  1381. t.test('multiple plain values exceeding limit', function (st) {
  1382. // 3 elements (indices 0-2), max index 2 > limit 1
  1383. st.deepEqual(
  1384. qs.parse('a=b&a=c&a=d', { arrayLimit: 1 }),
  1385. { a: { 0: 'b', 1: 'c', 2: 'd' } },
  1386. 'duplicate plain keys convert to object when exceeding limit'
  1387. );
  1388. st.end();
  1389. });
  1390. t.test('mixed notation produces consistent results when arrayLimit is exceeded', function (st) {
  1391. var expected = { a: { 0: 'b', 1: 'c', 2: 'd' } };
  1392. st.deepEqual(
  1393. qs.parse('a[]=b&a[1]=c&a=d', { arrayLimit: -1 }),
  1394. expected,
  1395. 'arrayLimit -1'
  1396. );
  1397. st.deepEqual(
  1398. qs.parse('a[]=b&a[1]=c&a=d', { arrayLimit: 0 }),
  1399. expected,
  1400. 'arrayLimit 0'
  1401. );
  1402. st.deepEqual(
  1403. qs.parse('a[]=b&a[1]=c&a=d', { arrayLimit: 1 }),
  1404. expected,
  1405. 'arrayLimit 1'
  1406. );
  1407. st.end();
  1408. });
  1409. t.test('uses existing array length for currentArrayLength when parsing object input with bracket keys', function (st) {
  1410. var input = {};
  1411. var arr = ['x', 'y'];
  1412. arr.a = ['z', 'w'];
  1413. input['a[]'] = arr;
  1414. st.deepEqual(qs.parse(input), { a: ['x', 'y'] }, 'parses object input with bracket keys using existing array values');
  1415. st.end();
  1416. });
  1417. t.test('throws with singular message when object input bracket key exceeds arrayLimit of 1', function (st) {
  1418. var input = {};
  1419. var arr = ['x'];
  1420. arr.a = ['z', 'w'];
  1421. input['a[]'] = arr;
  1422. st['throws'](
  1423. function () {
  1424. qs.parse(input, { throwOnLimitExceeded: true, arrayLimit: 1 });
  1425. },
  1426. new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
  1427. 'throws singular error for object input exceeding arrayLimit 1'
  1428. );
  1429. st.end();
  1430. });
  1431. t.end();
  1432. });