Skip to content

Commit

Permalink
split unedited chunks when trimming, to ensure correct sourcemaps (#53)
Browse files Browse the repository at this point in the history
  • Loading branch information
Rich-Harris committed Apr 11, 2016
1 parent 2258c67 commit 52f4740
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 16 deletions.
37 changes: 21 additions & 16 deletions src/MagicString.js
Expand Up @@ -354,18 +354,19 @@ MagicString.prototype = {

do {
let lastChunk = this.chunks[ this.chunks.length - 1 ];
if ( rx.test( lastChunk.content ) ) {
lastChunk.edit( lastChunk.content.replace( rx, '' ) );
}

if ( lastChunk.content.length || this.chunks.length === 1 ) {
break;
const match = rx.exec( lastChunk.content );
if ( !match ) return this;

if ( lastChunk.edited ) {
lastChunk.edit( lastChunk.content.slice( 0, match.index ) );
} else {
this.chunks.pop();
lastChunk.split( match.index + lastChunk.start ); // generated chunk is discarded
}
} while ( true );

return this;
if ( match.index > 0 || this.chunks.length === 1 ) return this;
this.chunks.pop();
} while ( true );
},

trimStart ( charType ) {
Expand All @@ -376,17 +377,21 @@ MagicString.prototype = {

do {
let firstChunk = this.chunks[0];
if ( rx.test( firstChunk.content ) ) {
firstChunk.edit( firstChunk.content.replace( rx, '' ) );
}

if ( firstChunk.content.length || this.chunks.length === 1 ) {
break;
const match = rx.exec( firstChunk.content );
if ( !match ) return this;

const end = match.index + match[0].length;

if ( firstChunk.edited ) {
firstChunk.edit( firstChunk.content.slice( match.index ) );
} else {
this.chunks.shift();
const newChunk = firstChunk.split( end + firstChunk.start ); // existing chunk is discarded
this.chunks[0] = newChunk;
}
} while ( true );

return this;
if ( end < firstChunk.content.length || this.chunks.length === 1 ) return this;
this.chunks.shift();
} while ( true );
}
};
28 changes: 28 additions & 0 deletions test/index.js
Expand Up @@ -260,6 +260,34 @@ describe( 'MagicString', function () {
assert.equal( loc.column, i );
});
});

it.only( 'generates a map with trimmed content (#53)', function () {
var s = new MagicString( 'abcdefghijkl ' ).trim();
var map = s.generateMap({
file: 'output',
source: 'input',
includeContent: true,
hires: true
});

var smc = new SourceMapConsumer( map );
var loc = smc.originalPositionFor({ line: 1, column: 11 });

assert.equal( loc.column, 11 );

s = new MagicString( ' abcdefghijkl' ).trim();
map = s.generateMap({
file: 'output',
source: 'input',
includeContent: true,
hires: true
});

smc = new SourceMapConsumer( map );
loc = smc.originalPositionFor({ line: 1, column: 1 });

assert.equal( loc.column, 2 );
});
});

describe( 'getIndentString', function () {
Expand Down

0 comments on commit 52f4740

Please sign in to comment.