From 355dd7934e7b921c3c7033b6101edca216f27f4b Mon Sep 17 00:00:00 2001 From: Brian Donovan Date: Mon, 23 Mar 2015 08:39:58 -0700 Subject: [PATCH] Disallow non-string content. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Without this it’s quite easy to accidentally pass an array, which may seem to just work but will have the wrong length, causing further operations at or after the affected location to be wrong. --- src/MagicString/index.js | 12 ++++++++++++ test/index.js | 24 ++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/MagicString/index.js b/src/MagicString/index.js index 80f004f..807eb95 100644 --- a/src/MagicString/index.js +++ b/src/MagicString/index.js @@ -19,6 +19,10 @@ MagicString.prototype = { }, append: function ( content ) { + if ( typeof content !== 'string' ) { + throw new TypeError( 'appended content must be a string' ); + } + this.str += content; return this; }, @@ -165,6 +169,10 @@ MagicString.prototype = { }, insert: function ( index, content ) { + if ( typeof content !== 'string' ) { + throw new TypeError( 'inserted content must be a string' ); + } + if ( index === 0 ) { this.prepend( content ); } else if ( index === this.original.length ) { @@ -224,6 +232,10 @@ MagicString.prototype = { }, replace: function ( start, end, content ) { + if ( typeof content !== 'string' ) { + throw new TypeError( 'replacement content must be a string' ); + } + var firstChar, lastChar, d; firstChar = this.locate( start ); diff --git a/test/index.js b/test/index.js index fc8ba65..36eeb70 100644 --- a/test/index.js +++ b/test/index.js @@ -30,6 +30,14 @@ describe( 'MagicString', function () { var s = new MagicString( 'abcdefghijkl' ); assert.strictEqual( s.append( 'xyz' ), s ); }); + + it( 'should throw when given non-string content', function () { + var s = new MagicString( '' ); + assert.throws( + function () { s.append( [] ); }, + TypeError + ); + }); }); describe( 'clone', function () { @@ -263,6 +271,14 @@ describe( 'MagicString', function () { assert.equal( s.insert(1, '1').toString(), 'a1b' ); assert.equal( s.insert(1, '2').toString(), 'a12b' ); }); + + it( 'should throw when given non-string content', function () { + var s = new MagicString( '' ); + assert.throws( + function () { s.insert( 0, [] ); }, + TypeError + ); + }); }); describe( 'locate', function () { @@ -466,6 +482,14 @@ describe( 'MagicString', function () { var s = new MagicString( 'abcdefghijkl' ); assert.strictEqual( s.replace( 3, 4, 'D' ), s ); }); + + it( 'should throw when given non-string content', function () { + var s = new MagicString( '' ); + assert.throws( + function () { s.replace( 0, 1, [] ); }, + TypeError + ); + }); }); describe( 'slice', function () {