File tree Expand file tree Collapse file tree 2 files changed +66
-2
lines changed Expand file tree Collapse file tree 2 files changed +66
-2
lines changed Original file line number Diff line number Diff line change @@ -14,19 +14,26 @@ import {
14
14
export function parse ( serialized ) {
15
15
const parsed = JSON . parse ( serialized ) ;
16
16
17
- if ( typeof parsed === 'number' ) return hydrate ( parsed ) ;
17
+ if ( typeof parsed === 'number' ) return hydrate ( parsed , true ) ;
18
+
19
+ if ( ! Array . isArray ( parsed ) || parsed . length === 0 ) {
20
+ throw new Error ( 'Invalid input' ) ;
21
+ }
18
22
19
23
const values = /** @type {any[] } */ ( parsed ) ;
24
+
20
25
const hydrated = Array ( values . length ) ;
21
26
22
27
/** @param {number } index */
23
- function hydrate ( index ) {
28
+ function hydrate ( index , standalone = false ) {
24
29
if ( index === UNDEFINED ) return undefined ;
25
30
if ( index === NAN ) return NaN ;
26
31
if ( index === POSITIVE_INFINITY ) return Infinity ;
27
32
if ( index === NEGATIVE_INFINITY ) return - Infinity ;
28
33
if ( index === NEGATIVE_ZERO ) return - 0 ;
29
34
35
+ if ( standalone ) throw new Error ( `Invalid input` ) ;
36
+
30
37
if ( index in hydrated ) return hydrated [ index ] ;
31
38
32
39
const value = values [ index ] ;
Original file line number Diff line number Diff line change @@ -406,6 +406,63 @@ for (const [name, tests] of Object.entries(fixtures)) {
406
406
test . run ( ) ;
407
407
}
408
408
409
+ const invalid = [
410
+ {
411
+ name : 'empty string' ,
412
+ json : '' ,
413
+ message : 'Unexpected end of JSON input'
414
+ } ,
415
+ {
416
+ name : 'invalid JSON' ,
417
+ json : '][' ,
418
+ message : 'Unexpected token ] in JSON at position 0'
419
+ } ,
420
+ {
421
+ name : 'hole' ,
422
+ json : '-2' ,
423
+ message : 'Invalid input'
424
+ } ,
425
+ {
426
+ name : 'string' ,
427
+ json : '"hello"' ,
428
+ message : 'Invalid input'
429
+ } ,
430
+ {
431
+ name : 'number' ,
432
+ json : '42' ,
433
+ message : 'Invalid input'
434
+ } ,
435
+ {
436
+ name : 'boolean' ,
437
+ json : 'true' ,
438
+ message : 'Invalid input'
439
+ } ,
440
+ {
441
+ name : 'null' ,
442
+ json : 'null' ,
443
+ message : 'Invalid input'
444
+ } ,
445
+ {
446
+ name : 'object' ,
447
+ json : '{}' ,
448
+ message : 'Invalid input'
449
+ } ,
450
+ {
451
+ name : 'empty array' ,
452
+ json : '[]' ,
453
+ message : 'Invalid input'
454
+ }
455
+ ] ;
456
+
457
+ for ( const { name, json, message } of invalid ) {
458
+ uvu . test ( `parse error: ${ name } ` , ( ) => {
459
+ assert . throws (
460
+ ( ) => parse ( json ) ,
461
+ ( error ) => error . message === message
462
+ ) ;
463
+ } ) ;
464
+ }
465
+
409
466
for ( const fn of [ uneval , stringify ] ) {
410
467
uvu . test ( `${ fn . name } throws for non-POJOs` , ( ) => {
411
468
class Foo { }
You can’t perform that action at this time.
0 commit comments