Example #1
0
    loadMap(file, prev) {
        if ( prev === false ) return false;

        if ( prev ) {
            if ( typeof prev === 'string' ) {
                return prev;
            } else if ( prev instanceof mozilla.SourceMapConsumer ) {
                return mozilla.SourceMapGenerator
                    .fromSourceMap(prev).toString();
            } else if ( prev instanceof mozilla.SourceMapGenerator ) {
                return prev.toString();
            } else if ( typeof prev === 'object' && prev.mappings ) {
                return JSON.stringify(prev);
            } else {
                throw new Error('Unsupported previous source map format: ' +
                    prev.toString());
            }

        } else if ( this.inline ) {
            return this.decodeInline(this.annotation);

        } else if ( this.annotation ) {
            let map = this.annotation;
            if ( file ) map = path.join(path.dirname(file), map);

            this.root = path.dirname(map);
            if ( fs.existsSync && fs.existsSync(map) ) {
                return fs.readFileSync(map, 'utf-8').toString().trim();
            } else {
                return false;
            }
        }
    }
    instrumenter.instrument(content, jsPath, function (err, instrumentedCode) {
      if (err) {
        log.error('%s\n  at %s', err.message, file.originalPath)
      }

      if (file.sourceMap && instrumenter.lastSourceMap()) {
        log.debug('Adding source map to instrumented file for "%s".', file.originalPath)
        var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(instrumenter.lastSourceMap().toString()))
        generator.applySourceMap(new SourceMapConsumer(file.sourceMap))
        file.sourceMap = JSON.parse(generator.toString())
        instrumentedCode += '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,'
        instrumentedCode += new Buffer(JSON.stringify(file.sourceMap)).toString('base64') + '\n'
      }

      // remember the actual immediate instrumented JS for given original path
      sourceCache[jsPath] = content

      if (includeAllSources) {
        var coverageObjMatch = coverageObjRegex.exec(instrumentedCode)

        if (coverageObjMatch !== null) {
          var coverageObj = JSON.parse(coverageObjMatch[0])

          coverageMap.add(coverageObj)
        }
      }

      done(instrumentedCode)
    })
Example #3
0
Mapping.reset = function(mapIn)
{
	if (mapIn)
		map = sourceMap.SourceMapGenerator.fromSourceMap( new sourceMap.SourceMapConsumer(mapIn) )
	else
		map = new sourceMap.SourceMapGenerator();
}
Example #4
0
 SourceMapConcatHelper.prototype._write = function() {
   // ensure we're using forward slashes, because these are URLs
   var file = path.relative(path.dirname(this.dest), this.files.dest);
   file = file.replace(/\\/g, '/');
   var code_map = this.node.toStringWithSourceMap({
     file: file
   });
   // Consume the new sourcemap.
   var generator = SourceMapGenerator.fromSourceMap(
     new SourceMapConsumer(code_map.map.toJSON())
   );
   // Consume sourcemaps for source files.
   this.maps.forEach(Function.apply.bind(generator.applySourceMap, generator));
   // New sourcemap.
   var newSourceMap = generator.toJSON();
   // Return a string for inline use or write the map.
   if (this.options.sourceMapStyle === 'inline') {
     grunt.log.writeln(
       'Source map for ' + chalk.cyan(this.files.dest) + ' inlined.'
     );
     return JSON.stringify(newSourceMap, null, '');
   } else {
     grunt.file.write(
       this.dest,
       JSON.stringify(newSourceMap, null, '')
     );
     grunt.log.writeln('Source map ' + chalk.cyan(this.dest) + ' created.');
   }
 };
Example #5
0
 Output.prototype.applySourceMaps = function (file) {
     if (file.sourceMapsApplied || file.skipPush || !file.original.gulp.sourceMap)
         return;
     file.sourceMapsApplied = true;
     var map = file.sourceMap;
     map.file = map.file.replace(/\\/g, '/');
     delete map.sourceRoot;
     map.sources = map.sources.map(function (path) { return path.replace(/\\/g, '/'); });
     var generator = sourceMap.SourceMapGenerator.fromSourceMap(new sourceMap.SourceMapConsumer(map));
     for (var _i = 0, _a = file.sourceMapOrigins; _i < _a.length; _i++) {
         var sourceFile = _a[_i];
         if (!sourceFile || !sourceFile.gulp || !sourceFile.gulp.sourceMap)
             continue;
         var inputOriginalMap = sourceFile.gulp.sourceMap;
         var inputMap = typeof inputOriginalMap === 'object' ? inputOriginalMap : JSON.parse(inputOriginalMap);
         /* We should only apply the input mappings if the input mapping isn't empty,
          * since `generator.applySourceMap` has a really bad performance on big inputs.
          */
         if (inputMap.mappings !== '') {
             var consumer = new sourceMap.SourceMapConsumer(inputMap);
             generator.applySourceMap(consumer);
         }
         if (!inputMap.sources || !inputMap.sourcesContent)
             continue;
         for (var i in inputMap.sources) {
             generator.setSourceContent(inputMap.sources[i], inputMap.sourcesContent[i]);
         }
     }
     file.sourceMapString = generator.toString();
 };
 SourceMapConcatHelper.prototype._write = function() {
   var code_map = this.node.toStringWithSourceMap({
     file: path.relative(path.dirname(this.dest), this.files.dest)
   });
   // Consume the new sourcemap.
   var generator = SourceMapGenerator.fromSourceMap(
     new SourceMapConsumer(code_map.map.toJSON())
   );
   // Consume sourcemaps for source files.
   this.maps.forEach(Function.apply.bind(generator.applySourceMap, generator));
   // New sourcemap.
   var newSourceMap = generator.toJSON();
   // Return a string for inline use or write the map.
   if (this.options.sourceMapStyle === 'inline') {
     grunt.log.writeln(
       'Source map for ' + chalk.cyan(this.files.dest) + ' inlined.'
     );
     return JSON.stringify(newSourceMap, null, '');
   } else {
     if (this.options.sourceRoot) {
       newSourceMap.sourceRoot = this.options.sourceRoot;
     }
     grunt.file.write(
       this.dest,
       JSON.stringify(newSourceMap, null, '')
     );
     grunt.log.writeln('Source map ' + chalk.cyan(this.dest) + ' created.');
   }
 };
Example #7
0
      value: function (file, prev) {
        if (prev === false) return;

        if (prev) {
          if (typeof (prev) == "string") {
            return prev;
          } else if (prev instanceof mozilla.SourceMapConsumer) {
            return mozilla.SourceMapGenerator.fromSourceMap(prev).toString();
          } else if (prev instanceof mozilla.SourceMapGenerator) {
            return prev.toString();
          } else if (typeof (prev) == "object" && prev.mappings) {
            return JSON.stringify(prev);
          } else {
            throw new Error("Unsupported previous source map format: " + prev.toString());
          }
        } else if (this.inline) {
          return this.decodeInline(this.annotation);
        } else if (this.annotation) {
          var map = this.annotation;
          if (file) map = path.join(path.dirname(file), map);

          this.root = path.dirname(map);
          if (fs.existsSync && fs.existsSync(map)) {
            return fs.readFileSync(map, "utf-8").toString().trim();
          }
        }
      }
			file.src.forEach(function(file) {
				var consumer = new sm.SourceMapConsumer(grunt.file.read(file)),
					map = sm.SourceMapGenerator.fromSourceMap(consumer);

				consumer.sources.forEach(function(sourcefile) {
					map.setSourceContent(sourcefile, grunt.file.read(path.dirname(file) + '/' + sourcefile))
				});

				grunt.file.write(file, map.toString());
			});
Example #9
0
export function apply(sourceMap, applicator) {
  var cons = new SourceMapConsumer(sourceMap)
  var applCons = new SourceMapConsumer(applicator)

  var generator = SourceMapGenerator.fromSourceMap(applCons)
  // TODO: use the default (applicator.file) instead of applicator.sources[0]
  generator.applySourceMap(cons, applicator.sources[0])

  return generator.toJSON()
}
Example #10
0
 /**
  * Merge the two specified source-maps into a single source-map that hides the intermediate
  * source-map.
  * E.g. Consider these mappings:
  *
  * ```
  * OLD_SRC -> OLD_MAP -> INTERMEDIATE_SRC -> NEW_MAP -> NEW_SRC
  * ```
  *
  * this will be replaced with:
  *
  * ```
  * OLD_SRC -> MERGED_MAP -> NEW_SRC
  * ```
  */
 function mergeSourceMaps(oldMap, newMap) {
     if (!oldMap) {
         return convert_source_map_1.fromObject(newMap);
     }
     var oldMapConsumer = new source_map_1.SourceMapConsumer(oldMap);
     var newMapConsumer = new source_map_1.SourceMapConsumer(newMap);
     var mergedMapGenerator = source_map_1.SourceMapGenerator.fromSourceMap(newMapConsumer);
     mergedMapGenerator.applySourceMap(oldMapConsumer);
     var merged = convert_source_map_1.fromJSON(mergedMapGenerator.toString());
     return merged;
 }
Example #11
0
SourceMapSource.prototype.node = function(options) {
	var innerSourceMap = this._innerSourceMap;
	var sourceMap = this._sourceMap;
	if(innerSourceMap) {
		innerSourceMap = new SourceMapConsumer(innerSourceMap);
		sourceMap = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(sourceMap));
		sourceMap.setSourceContent(this._name, this._originalSource);
		sourceMap.applySourceMap(innerSourceMap, this._name);
		sourceMap = sourceMap.toJSON();
	}
	return SourceNode.fromStringWithSourceMap(this._value, new SourceMapConsumer(sourceMap));
};
Example #12
0
module.exports = function applySourceMap(file, sourceMap) {
  if (typeof sourceMap === 'string' || sourceMap instanceof String) {
    sourceMap = JSON.parse(sourceMap);
  }
  if (file.sourceMap) {
    var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(sourceMap));
    generator.applySourceMap(new SourceMapConsumer(file.sourceMap));
    file.sourceMap = JSON.parse(generator.toString());
  } else {
    file.sourceMap = sourceMap;
  }
};
Example #13
0
  /**
   * merge source map
   * @param  {String} content        []
   * @param  {Object} orginSourceMap []
   * @param  {Object} sourceMap      []
   * @return {}                []
   */
  mergeSourceMap(orginSourceMap, sourceMap){
    let {SourceMapGenerator, SourceMapConsumer} = require('source-map');
    sourceMap.file = sourceMap.file.replace(/\\/g, '/');
    sourceMap.sources = sourceMap.sources.map(filePath => {
      return filePath.replace(/\\/g, '/');
    });
    var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(sourceMap));
    generator.applySourceMap(new SourceMapConsumer(orginSourceMap));
    sourceMap = JSON.parse(generator.toString());

    return sourceMap;
  }
Example #14
0
    writeFileFromPrevMap: function (file, prev) {
        if (!prev) {
            return;
        }

        if (prev) {
            if (typeof prev === 'string') {
                return prev;
            }

            if (typeof prev === 'function') {
                var prevPath = prev(file);

                if (prevPath && fs.existsSync && fs.existsSync(prevPath)) {
                    return fs.readFileSync(prevPath, 'utf-8').toString().trim();
                } else {
                    throw new Error('Unable to load previous source map: ' + prevPath.toString());
                }
            }

            if (prev instanceof mozilla.SourceMapConsumer) {
                return mozilla.SourceMapGenerator.fromSourceMap(prev).toString();
            }

            if (prev instanceof mozilla.SourceMapGenerator) {
                return prev.toString();
            }

            if (isMap(prev)) {
                return JSON.stringify(prev);
            }

            throw new Error('Unsupported previous source map format: ' + prev.toString());
        }

        if (this.inline) {
            return this.decodeInline(this.annotation);
        }

        if (this.annotation) {
            var map = this.annotation;
            if (file) {
                map = path.join(path.dirname(file), map);
            }

            this.root = path.dirname(map);

            return (fs.existsSync && fs.existsSync(map)) ?
                fs.readFileSync(map, 'utf-8').toString().trim() :
                false;
        }
    },
Example #15
0
function SourceMapSource(value, name, sourceMap, originalSource, innerSourceMap) {
	if(innerSourceMap) {
		innerSourceMap = new SourceMapConsumer(innerSourceMap);
		sourceMap = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(sourceMap));
		sourceMap.setSourceContent(name, originalSource);
		sourceMap.applySourceMap(innerSourceMap, name);
		sourceMap = sourceMap.toJSON();
	}
	var node = SourceNode.fromStringWithSourceMap(value, new SourceMapConsumer(sourceMap));
	SourceMapNodeSource.call(this, node);
	this._value = value;
	this._name = name;
}
Example #16
0
module.exports = function(source) {  
  const callback = this.async();
  if(!callback) throw new Error("Sync mode not supported");

  const compilerOptions = Object.assign({file: this.resourcePath}, loaderUtils.parseQuery(this.query));
  const compiler = Opal.Opal.Compiler.$new(source, Opal.hash(compilerOptions));    
  const currentLoader = getCurrentLoader(this).path;
  
  this.cacheable && this.cacheable()
  
  compiler.$compile();
  
  const result = compiler.$result();
  
  /* 
    Workaround to make IO work, 
    webpack polyfill global "process" module by default,
    while Opal::IO rely on it to deterimine in node environment or not 
  */
  let prepend = ['process = undefined;'];
  
  compiler.$requires().forEach(filename => {
    var resolved = resolveFilename(this, filename);
    if (resolved.match(/\.js$/)) {
      prepend.push(`require('${require.resolve('imports-loader')}!${resolved}');`);
      prepend.push(`Opal.loaded('${filename}');`)
    } else {
      prepend.push(`require('!!${currentLoader}?file=${filename}&requirable=true!${resolved}');`);
    }
  })
  
  if (this.sourceMap) {
    let rawMap = JSON.parse(compiler.$source_map().$as_json().$to_json());
    
    // Since it's compiled from the current resource
    rawMap.sources = [this.resourcePath];
    
    // Set source content
    let consumer = new SourceMapConsumer(rawMap)
    let map = SourceMapGenerator.fromSourceMap(consumer);
    map.setSourceContent(this.resourcePath, source);
    
    // Prepend the chunk of our injected script
    let node = SourceNode.fromStringWithSourceMap(result, new SourceMapConsumer(map.toString()));
    node.prepend(prepend.join(" "));
          
    callback(null, prepend.join(" ") + "\n" + result, JSON.parse(node.toStringWithSourceMap().map.toString()));
  } else {
    callback(null, prepend.join(" ") + "\n" + result);
  }
};
Example #17
0
function buildOptimizerLoader(content, previousSourceMap) {
    this.cacheable();
    const options = loaderUtils.getOptions(this) || {};
    // Make up names of the intermediate files so we can chain the sourcemaps.
    const inputFilePath = this.resourcePath + '.pre-build-optimizer.js';
    const outputFilePath = this.resourcePath + '.post-build-optimizer.js';
    const boOutput = build_optimizer_1.buildOptimizer({
        content,
        originalFilePath: this.resourcePath,
        inputFilePath,
        outputFilePath,
        emitSourceMap: options.sourceMap,
    });
    if (boOutput.emitSkipped || boOutput.content === null) {
        // Webpack typings for previousSourceMap are wrong, they are JSON objects and not strings.
        // tslint:disable-next-line:no-any
        this.callback(null, content, previousSourceMap);
        return;
    }
    const intermediateSourceMap = boOutput.sourceMap;
    let newContent = boOutput.content;
    let newSourceMap;
    if (options.sourceMap && intermediateSourceMap) {
        // Webpack doesn't need sourceMappingURL since we pass them on explicitely.
        newContent = newContent.replace(/^\/\/# sourceMappingURL=[^\r\n]*/gm, '');
        if (previousSourceMap) {
            // If there's a previous sourcemap, we have to chain them.
            // See https://github.com/mozilla/source-map/issues/216#issuecomment-150839869 for a simple
            // source map chaining example.
            // Use http://sokra.github.io/source-map-visualization/ to validate sourcemaps make sense.
            // Force the previous sourcemap to use the filename we made up for it.
            // In order for source maps to be chained, the consumed source map `file` needs to be in the
            // consumers source map `sources` array.
            previousSourceMap.file = inputFilePath;
            // Chain the sourcemaps.
            const consumer = new source_map_1.SourceMapConsumer(intermediateSourceMap);
            const generator = source_map_1.SourceMapGenerator.fromSourceMap(consumer);
            generator.applySourceMap(new source_map_1.SourceMapConsumer(previousSourceMap));
            newSourceMap = generator.toJSON();
        }
        else {
            // Otherwise just return our generated sourcemap.
            newSourceMap = intermediateSourceMap;
        }
    }
    // Webpack typings for previousSourceMap are wrong, they are JSON objects and not strings.
    // tslint:disable-next-line:no-any
    this.callback(null, newContent, newSourceMap);
}
Example #18
0
SourceMap.prototype.apply = function(nextSourceMap) {
    // We assume the nextSourceMap maps a single source, which
    // corresponds to the output of the current source map
    var nextSources = nextSourceMap.sources;
    if (nextSources.length !== 1) {
        throw new Error('Cannot apply a source map that maps multiple sources');
    }

    var currentMap = new SourceMapConsumer(this);
    var nextMap    = new SourceMapConsumer(nextSourceMap);

    var generator = SourceMapGenerator.fromSourceMap(nextMap);
    generator.applySourceMap(currentMap, nextSources[0]);
    return fromMapGenerator(generator);
};
Example #19
0
    compilerProcess.on('close', (function (code) {
      // non-zero exit means a compilation error
      if (code !== 0) {
        this.emit('error', new PluginError(this.PLUGIN_NAME_,
            'Compilation error: \n\n' + compiler.prependFullCommand(stdErrData)));
      }

      // standard error will contain compilation warnings, log those
      if (stdErrData.trim().length > 0) {
        logger(gutil.colors.yellow(this.PLUGIN_NAME_) + ': ' + stdErrData);
      }

      // If present, standard output will be a string of JSON encoded files.
      // Convert these back to vinyl
      if (stdOutData.trim().length > 0) {
        var outputFiles;
        try {
          outputFiles = jsonToVinyl(stdOutData);
        } catch (e) {
          this.emit('error', new PluginError(this.PLUGIN_NAME_, 'Error parsing json encoded files'));
          cb();
          return;
        }

        for (var i = 0; i < outputFiles.length; i++) {
          if (outputFiles[i].sourceMap) {
            // Closure compiler does not compose source maps (use input source maps)
            // We need to manually compose the maps so that we reference the original file
            var generator = SourceMapGenerator.fromSourceMap(
                new SourceMapConsumer(outputFiles[i].sourceMap));
            outputFiles[i].sourceMap = undefined;

            for (var j = 0; j < jsonFiles.length; j++) {
              if (!jsonFiles[j].source_map) {
                continue;
              }
              generator.applySourceMap(
                  new SourceMapConsumer(jsonFiles[j].source_map),
                  jsonFiles[j].path.substr(1));
            }
            applySourceMap(outputFiles[i], generator.toString());
          }
          this.push(outputFiles[i]);
        }
      }
      cb();
    }).bind(this));
Example #20
0
 Output.prototype.applySourceMaps = function (file) {
     if (file.sourceMapsApplied || file.skipPush || !file.original.gulp.sourceMap)
         return;
     file.sourceMapsApplied = true;
     var map = file.sourceMap;
     map.file = map.file.replace(/\\/g, '/');
     delete map.sourceRoot;
     map.sources = map.sources.map(function (path) { return path.replace(/\\/g, '/'); });
     var generator = sourceMap.SourceMapGenerator.fromSourceMap(new sourceMap.SourceMapConsumer(map));
     for (var fileName in file.sourceMapOrigins) {
         var sourceFile = this.project.input.getFile(fileName);
         if (!sourceFile || !sourceFile.gulp || !sourceFile.gulp.sourceMap)
             continue;
         generator.applySourceMap(new sourceMap.SourceMapConsumer(sourceFile.gulp.sourceMap));
     }
     file.sourceMapString = generator.toString();
 };
Example #21
0
    function endStream(){
        if (!firstFile) return this.emit('end');

        var contentPath = path.join(firstFile.base, fileName),
            mapPath = contentPath + '.map';

        if (/\.css$/.test(fileName)) {
            sourceNode.add('/*# sourceMappingURL=' + fileName + '.map' + ' */');
        } else {
            sourceNode.add('//# sourceMappingURL=' + fileName + '.map');
        }

        var codeMap = sourceNode.toStringWithSourceMap({
            file: fileName,
            sourceRoot: opts.sourceRoot || ''
        });

        var sourceMap = SourceMapGenerator
                                .fromSourceMap( new SourceMapConsumer( codeMap.map.toJSON() ) )
                                .toJSON();
                                
        sourceMap.file = path.basename(sourceMap.file);

        var contentFile = new File({
            cwd: firstFile.cwd,
            base: firstFile.base,
            path: contentPath,
            contents: new Buffer(codeMap.code)
        });

        var mapFile = new File({
            cwd: firstFile.cwd,
            base: firstFile.base,
            path: mapPath,
            contents: new Buffer(JSON.stringify(sourceMap, null, '  '))
        });

        this.emit('data', contentFile);
        this.emit('data', mapFile);
        this.emit('end');
    }
Example #22
0
  mergeSourceMap(map: Object) {
    var opts = this.opts;

    var inputMap = opts.inputSourceMap;

    if (inputMap) {
      map.sources[0] = inputMap.file;

      var inputMapConsumer   = new sourceMap.SourceMapConsumer(inputMap);
      var outputMapConsumer  = new sourceMap.SourceMapConsumer(map);
      var outputMapGenerator = sourceMap.SourceMapGenerator.fromSourceMap(outputMapConsumer);
      outputMapGenerator.applySourceMap(inputMapConsumer);

      var mergedMap = outputMapGenerator.toJSON();
      mergedMap.sources = inputMap.sources
      mergedMap.file    = inputMap.file;
      return mergedMap;
    }

    return map;
  }
Example #23
0
/**
 * Create source map from 'mapObject' and 'content'
 * @param {Object} mapObject
 * @param {String} content
 * @param {String} [url]
 * @returns {SourceMapGenerator}
 */
function createFromMap(mapObject, content, url) {
  url = url || '<source>';
  if ('string' == typeof mapObject) {
    try {
      mapObject = JSON.parse(mapObject);
    } catch (err) {
      mapObject = {
        version: 3,
        names: [],
        mappings: '',
        file: ''
      };
    }
  }
  if (emptySources(mapObject)) {
    mapObject.sources = [url];
    mapObject.sourcesContent = [content];
  }

  return SourceMapGenerator.fromSourceMap(new SourceMapConsumer(mapObject));
}
 transpile(compilerOptions) {
     const source = this.sourceText;
     const result = ts.transpileModule(source, {
         compilerOptions: Object.assign({}, compilerOptions, {
             sourceMap: true,
             inlineSources: false,
             inlineSourceMap: false,
             sourceRoot: ''
         }),
         fileName: this._fileName
     });
     if (result.sourceMapText) {
         const sourceMapJson = JSON.parse(result.sourceMapText);
         sourceMapJson.sources = [this._fileName];
         const consumer = new source_map_1.SourceMapConsumer(sourceMapJson);
         const map = source_map_1.SourceMapGenerator.fromSourceMap(consumer);
         if (this._changed) {
             const sourceMap = this._sourceString.generateMap({
                 file: path.basename(this._fileName.replace(/\.ts$/, '.js')),
                 source: this._fileName,
                 hires: true,
             });
             map.applySourceMap(new source_map_1.SourceMapConsumer(sourceMap), this._fileName);
         }
         const sourceMap = map.toJSON();
         const fileName = process.platform.startsWith('win')
             ? this._fileName.replace(/\//g, '\\')
             : this._fileName;
         sourceMap.sources = [fileName];
         sourceMap.file = path.basename(fileName, '.ts') + '.js';
         sourceMap.sourcesContent = [this._sourceText];
         return { outputText: result.outputText, sourceMap };
     }
     else {
         return {
             outputText: result.outputText,
             sourceMap: null
         };
     }
 }
Example #25
0
module.exports = function applySourceMap(file, sourceMap) {
  if (typeof sourceMap === 'string' || sourceMap instanceof String) {
    sourceMap = JSON.parse(sourceMap);
  }

  // check source map properties
  assertProperty(sourceMap, "mappings");
  assertProperty(sourceMap, "sources");
  
  // fix paths if Windows style paths
  sourceMap.sources = sourceMap.sources.map(function(filePath) {
    return filePath.replace(/\\/g, '/');
  });

  if (file.sourceMap) {
    var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(sourceMap));
    generator.applySourceMap(new SourceMapConsumer(file.sourceMap));
    file.sourceMap = JSON.parse(generator.toString());
  } else {
    file.sourceMap = sourceMap;
  }
};
    instrumenter.instrument(content, jsPath, function (err, instrumentedCode) {
      if (err) {
        log.error('%s\n  at %s', err.message, file.originalPath)
        done(err.message)
      } else {
        if (file.sourceMap && instrumenter.lastSourceMap()) {
          log.debug('Adding source map to instrumented file for "%s".', file.originalPath)
          var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(instrumenter.lastSourceMap().toString()))
          generator.applySourceMap(new SourceMapConsumer(file.sourceMap))
          file.sourceMap = JSON.parse(generator.toString())
          instrumentedCode += '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,'
          instrumentedCode += new Buffer(JSON.stringify(file.sourceMap)).toString('base64') + '\n'
        }

        // remember the actual immediate instrumented JS for given original path
        sourceCache[jsPath] = content

        if (includeAllSources) {
          // reset stateful regex
          coverageObjRegex.lastIndex = 0

          var coverageObjMatch = coverageObjRegex.exec(instrumentedCode)

          if (coverageObjMatch !== null) {
            var coverageObj = JSON.parse(coverageObjMatch[0])

            coverageMap.add(coverageObj)
          }
        }

        // RequireJS expects JavaScript files to end with `.js`
        if (useJSExtensionForCoffeeScript && instrumenterLiteral === 'ibrik') {
          file.path = file.path.replace(/\.coffee$/, '.js')
        }

        done(instrumentedCode)
      }
    })
Example #27
0
/**
 * Clone 'map'
 * @param {SourceMapGenerator} map
 * @returns {SourceMapGenerator}
 */
function clone(map) {
  return map instanceof SourceMapGenerator
    ? SourceMapGenerator.fromSourceMap(new SourceMapConsumer(map.toJSON()))
    : map;
}
Example #28
0
console.log('map for gen2');
console.log(gen2.map._mappings.toArray().reduce((acc, m, idx) => {
  return acc + `${idx}(${m.name}):{${m.originalLine},${m.originalColumn}}->{${m.generatedLine},${m.generatedColumn}},	`
}, ''));
console.log('map for gen3');
console.log(gen3.map._mappings.toArray().reduce((acc, m, idx) => {
  return acc + `${idx}(${m.name}):{${m.originalLine},${m.originalColumn}}->{${m.generatedLine},${m.generatedColumn}},	`
}, ''));
console.log('map for goal');
console.log(gen_goal.map._mappings.toArray().reduce((acc, m, idx) => {
  return acc + `${idx}(${m.name}):{${m.originalLine},${m.originalColumn}}->{${m.generatedLine},${m.generatedColumn}},	`
}, ''));
console.log('map for gen2 comment');
var smc_of_code2_comment = new SM.SourceMapConsumer(gen2MapFromComment)
console.log(SM.SourceMapGenerator.fromSourceMap(smc_of_code2_comment)._mappings.toArray().reduce((acc, m, idx) => {
  return acc + `${idx}(${m.name}):{${m.originalLine},${m.originalColumn}}->{${m.generatedLine},${m.generatedColumn}},	`
}, ''));

console.log();

var smc_of_gen2 = new SM.SourceMapConsumer(gen2.map.toString())

console.log('merge...');
var smc_of_gen3 = new SM.SourceMapConsumer(gen3.map.toString())
smc_of_gen3.eachMapping((m, idx) => {
  console.log(`${idx}(${m.name}):{${m.originalLine},${m.originalColumn}}->{${m.generatedLine},${m.generatedColumn}}`);
  // console.log('  origPos', smc_of_code2_comment.originalPositionFor({line: m.generatedLine, column: m.generatedColumn}));
  // var origPosInGen2 = smc_of_gen2.originalPositionFor({line: m.originalLine, column: m.originalColumn})
  var origPosInGen2 = smc_of_gen2.originalPositionFor({line: m.originalLine, column: m.originalColumn})
  var origPosInGen2_2 = smc_of_gen2.originalPositionFor({line: m.generatedLine, column: m.generatedColumn})
Example #29
0
 TsickleCompilerHost.prototype.sourceMapConsumerToGenerator = function (sourceMapConsumer) {
     return source_map_1.SourceMapGenerator.fromSourceMap(sourceMapConsumer);
 };
Example #30
0
module.exports = function(file, opts) {
  // 不是 js 文件不处理。
  if (!file.isJsLike || file.isPartial) {
    return;
  }

  var content = file.getContent();
  var forceNoWrap = file.wrap === false;
  
  if (!forceNoWrap && file.isMod) {
    
    var deps = '';
    if (opts.forwardDeclaration) {
      var reqs = opts.skipBuiltinModules ? [] : ['\'require\'', '\'exports\'', '\'module\''];

      file.requires.forEach(function(id) {
        var dep = fis.uri(id, file.dirname);
        if (dep.file) {
          if (dep.file.isJsLike) {
            reqs.push('\'' + (dep.file.moduleId || dep.file.id) + '\'');
          }
        } else {
          /(\.\w+)$/.test(id) ? (~opts.extList.indexOf(RegExp.$1) ? reqs.push('\'' + id.replace(/\.js$/i, '') + '\'') : '') : reqs.push('\'' + id + '\'');
        }
      });

      deps = ' [' + reqs.join(', ') + '],';
    }

    var originContent = content;

    if (opts.tab) {
      content = fis.util.pad(' ', opts.tab) + content.split(/\n|\r\n|\r/g).join('\n' + fis.util.pad(' ', opts.tab));
    }

    var prefix = 'define(\'' + (file.moduleId || file.id) + '\',' + deps + ' function(require, exports, module) {\n\n';
    var affix = '\n\n});\n';

    content = prefix + content + affix;

    if (file.moduleId !== file.id) {
      file.extras.moduleId = file.moduleId;
    }

    // 同时修改 sourcemap 文件内容。
    var derived = file.derived;
    if (!derived || !derived.length) {
      derived = file.extras && file.extras.derived;
    }

    if (derived && derived[0] && derived[0].rExt === '.map') {
      var SourceMap = require('source-map');
      

      var sourcemap = derived[0];
      var json = JSON.parse(sourcemap.getContent());
      var smc = new SourceMap.SourceMapConsumer(json);

      var sourceNode = new SourceMap.SourceNode();

      sourceNode.add(prefix);
      sourceNode.add(SourceMap.SourceNode.fromStringWithSourceMap(originContent, smc));
      sourceNode.add(affix);

      var code_map = sourceNode.toStringWithSourceMap({
        file: smc.file
      });

      var generater = SourceMap.SourceMapGenerator.fromSourceMap(new SourceMap.SourceMapConsumer(code_map.map.toJSON()));
      sourcemap.setContent(generater.toString());
    }

    file.setContent(content);
  }
}