Example #1
0
function forSource(data, sourcePath) {
    if (! data) {
        throw new Error('Missing data in SourceMap.forSource');
    }

    if (! sourcePath) {
        throw new Error('Missing sourcePath in SourceMap.forSource');
    }

    var generator = new SourceMapGenerator({
        // FIXME: or just filename?
        file: path.basename(sourcePath)
    });

    generator.setSourceContent(sourcePath, data);

    data.split('\n').forEach(function(l, i) {
        generator.addMapping({
            generated: { line: i + 1, column: null },
            original:  { line: i + 1, column: null },
            source: sourcePath
        });
    });

    return fromMapObject(generator.toJSON());
}
function mergeMap(oldMap, newMap) {
  console.log(oldMap);
  console.log(newMap);
  var oldMapConsumer = new SM.SourceMapConsumer(oldMap)
  var newMapConsumer = new SM.SourceMapConsumer(newMap)
  var mergedMapGenerator = new SM.SourceMapGenerator()
  console.log(SM.SourceMapGenerator.fromSourceMap(newMapConsumer)._mappings.toArray())
  newMapConsumer.eachMapping((m, idx) => {
    var oldOrigPos = oldMapConsumer.originalPositionFor({line: m.originalLine, column: m.originalColumn})
    console.log(idx, m)
    console.log(idx, oldOrigPos);
    mergedMapGenerator.addMapping({
      generated: {
        line: m.generatedLine,
        column: m.generatedColumn
      },
      original: {
        line: oldOrigPos.line,
        column: oldOrigPos.column
      },
      source: m.source,
      name: m.name
    })
  })
  mergedMapGenerator.setSourceContent('multi-transform-t-dummy.js', gen2MapFromComment.sourcesContent[0])
  return JSON.parse(mergedMapGenerator.toString())
}
Example #3
0
function generateMap(mappings, sourceRoot, mapFileBaseName, generatedLineOffset) {
  var SourceMapGenerator = require('source-map').SourceMapGenerator;

  var generator = new SourceMapGenerator({ file: mapFileBaseName });
  var seenFiles = Object.create(null);

  for (var generatedLineNumber in mappings) {
    var generatedLineNumber = parseInt(generatedLineNumber, 10);
    var mapping = mappings[generatedLineNumber];
    var originalFileName = mapping.originalFileName;
    generator.addMapping({
      generated: { line: generatedLineNumber + generatedLineOffset, column: 0 },
      original: { line: mapping.originalLineNumber, column: 0 },
      source: originalFileName
    });

    // we could call setSourceContent repeatedly, but readFileSync is slow, so
    // avoid doing it unnecessarily
    if (!(originalFileName in seenFiles)) {
      seenFiles[originalFileName] = true;
      var rootedPath = originalFileName[0] === path.sep ?
          originalFileName : path.join(sourceRoot, originalFileName);
      try {
        generator.setSourceContent(originalFileName, fs.readFileSync(rootedPath, 'utf-8'));
      } catch (e) {
        console.warn("sourcemapper: Unable to find original file for " + originalFileName +
          " at " + rootedPath);
      }
    }
  }

  fs.writeFileSync(mapFileBaseName + '.map', generator.toString());
}
Example #4
0
function getMap(fileName, sourceName, originalSource, generatedSource, options) {
  var map = new sourceMap.SourceMapGenerator({
    file: fileName
  });

  var defineToken = "define([";

  var commentMatcher = matcher.getComment(isFileCoffee(fileName));
  var commentMatch = commentMatcher.exec(originalSource);
  var commentEndIndex = commentMatch.index + commentMatch[0].length;

  var orgCoords = getCoordinates(originalSource, commentEndIndex);
  var genCoords = getCoordinates(generatedSource, defineToken);

  var offset = orgCoords.line - (genCoords.line + 1);

  var lineCount = generatedSource.split(/\r?\n/).length;
  for (var i = genCoords.line + 1; i < lineCount; i++) {
    map.addMapping({
      original: {
        line: i + offset,
        column: 1
      },
      generated: {
        line: i,
        column: 1 + getIndent(options).length,
      },
      source: sourceName
    });
  }

  return map.toString();
}
Example #5
0
export function concatenate(sourceMaps, offsets) {
  var generator = new SourceMapGenerator()
  var consumers = sourceMaps.map(sourceMap => new SourceMapConsumer(sourceMap))

  // TODO: look for content collisions in consumers?
  consumers.forEach((consumer, sourceMapIdx) => {
    consumer.sourcesContent.forEach((content, i) => {
      generator.setSourceContent(consumer.sources[i], content)
    })

    var offset = offsets[sourceMapIdx]
    consumer.eachMapping(mapping => {
      generator.addMapping({
          generated: {
              line: mapping.generatedLine + offset,
              column: mapping.generatedColumn
          },
          original: {
              line: mapping.originalLine,
              column: mapping.originalColumn
          },
          source: mapping.source,
          name: mapping.name
      })
    })
  })

  return generator.toJSON()
}
function genSourceMap(modules) {
  var sourceMapGen = new SourceMapGenerator({file: 'bundle.js', version: 3});
  var bundleLineNo = 0;
  for (var i = 0; i < modules.length; i++) {
    var module = modules[i];
    var transformedCode = module.code;
    var sourcePath = module.sourcePath;
    var sourceCode = module.sourceCode;
    var transformedLineCount = 0;
    var lastCharNewLine = false;
    for (var t = 0; t < transformedCode.length; t++) {
      if (t === 0 || lastCharNewLine) {
        sourceMapGen.addMapping({
          generated: {line: bundleLineNo + 1, column: 0},
          original: {line: transformedLineCount + 1, column: 0},
          source: sourcePath
        });
      }
      lastCharNewLine = transformedCode[t] === '\n';
      if (lastCharNewLine) {
        transformedLineCount++;
        bundleLineNo++;
      }
    }
    bundleLineNo++;
    sourceMapGen.setSourceContent(
      sourcePath,
      sourceCode
    );
  }
  return sourceMapGen.toJSON();
}
Example #7
0
    _.each(argv, function(filename) {
        // Read the file content.
        var source = getFileContents(filename);

        if(filename.match(literateExtension)) {
            // Strip out the Markdown.
            source = source.match(/^ {4,}.+$/mg).join('\n').replace(/^ {4}/gm, '');
        } else {
            console.assert(filename.match(extensions), 'Filename must end with ".roy" or ".lroy"');
        }

        exported = {};
        var outputPath = filename.replace(extensions, '.js');
        var SourceMapGenerator = require('source-map').SourceMapGenerator;
        var sourceMap = new SourceMapGenerator({file: path.basename(outputPath)});

        var compiled = compile(source, env, aliases, {
            nodejs: !browserModules,
            filename: filename,
            run: run,
            exported: exported,
            sourceMap: sourceMap
        });
        if(run) {
            // Execute the JavaScript output.
            output = vm.runInNewContext(compiled.output, sandbox, 'eval');
        } else {
            // Write the JavaScript output.
            fs.writeFile(outputPath, compiled.output + '//@ sourceMappingURL=' + path.basename(outputPath) + '.map\n', 'utf8');
            fs.writeFile(outputPath + '.map', sourceMap.toString(), 'utf8');
            writeModule(env, exported, filename.replace(extensions, '.roym'));
        }
    });
Example #8
0
 function patchSourcemap(patches, rsm, smc) {
     var smg = new sm.SourceMapGenerator({
         file: rsm.file,
         sourceRoot: rsm.sourceRoot
     });
     patches = patches.reverse();
     var currentLine = -1;
     var currentLineDiff = 0;
     var source = null;
     smc.eachMapping(function (m) {
         var patch = patches[patches.length - 1];
         var original = { line: m.originalLine, column: m.originalColumn };
         var generated = { line: m.generatedLine, column: m.generatedColumn };
         if (currentLine !== generated.line) {
             currentLineDiff = 0;
         }
         currentLine = generated.line;
         generated.column += currentLineDiff;
         if (patch && m.generatedLine - 1 === patch.span.end.line && m.generatedColumn === patch.span.end.character) {
             var originalLength = patch.span.end.character - patch.span.start.character;
             var modifiedLength = patch.content.length;
             var lengthDiff = modifiedLength - originalLength;
             currentLineDiff += lengthDiff;
             generated.column += lengthDiff;
             patches.pop();
         }
         source = rsm.sourceRoot ? path.relative(rsm.sourceRoot, m.source) : m.source;
         source = source.replace(/\\/g, '/');
         smg.addMapping({ source: source, name: m.name, original: original, generated: generated });
     }, null, sm.SourceMapConsumer.GENERATED_ORDER);
     if (source) {
         smg.setSourceContent(source, smc.sourceContentFor(source));
     }
     return JSON.parse(smg.toString());
 }
Example #9
0
  it('generates source map', () => {
    const generator = new SourceMapGenerator({
      file: 'test.html'
    })
    generator.addMapping({
      source: 'test.html',
      original: { line: 1, column: 0 },
      generated: { line: 1, column: 0 }
    })
    const map = JSON.parse(generator.toString())

    const b = new Builder()
    b.addLine('var a = "a"')
    b.addLine('var render = function () { return "test" }', map)
    b.addLine('var b = "b"')

    const result = b.generate()
    const smc = new SourceMapConsumer(result.map)

    expect(result.code).toBe(code([
      'var a = "a"',
      'var render = function () { return "test" }',
      'var b = "b"'
    ]))

    let pos = smc.originalPositionFor({ line: 2, column: 0 })
    expect(pos.source).toBe('test.html')
    expect(pos.line).toBe(1)
    expect(pos.column).toBe(0)

    pos = smc.originalPositionFor({ line: 3, column: 0 })
    expect(pos.source).toBe(null)
    expect(pos.line).toBe(null)
    expect(pos.column).toBe(null)
  })
Example #10
0
test('parsing generated one to one mappings with last line having no original', function (t) {
  var gen = new Generator({ file: 'foo.js' })
  var add = [ 
    { generated: { line: 1, column: 0 },
      original: { line: 1, column: 0 },
      source: 'foo.js',
      name: null },
    { generated: { line: 2, column: 0 },
      original: { line: 2, column: 0 },
      source: 'foo.js',
      name: null },
    { generated: { line: 3, column: 0 },
      original: { line: 3, column: 0 },
      source: 'foo.js',
      name: null },
    { generated: { line: 4, column: 0 },
      original: { line: 4, column: 0 },
      source: 'foo.js',
      name: null },
    { generated: { line: 5, column: 0 },
      original: { line: 5, column: 0 },
      source: 'foo.js',
      name: null },
    { generated: { line: 6, column: 0 } } ]

  add.forEach(gen.addMapping.bind(gen))
  var addedMappings = add.map(function (m) { return m.original ? { generated: m.generated, original: m.original } : { generated: m.generated } })

  var mappings = gen.toJSON().mappings
    , parsed = parse(mappings)

  t.deepEqual(parsed, addedMappings, 'parses out added mappings')
});
Example #11
0
Context.prototype.createSourceMapObject = function (obj) {
  var map;

  if (obj.map) {
    map = JSON.parse(obj.map);
    map.sourceRoot = '';
    return map;
  }

  var name = path.basename(obj.file);
  var smg = new sourcemap.SourceMapGenerator({ file: name });

  obj.data.split('\n').forEach(function (line, idx) {
    smg.addMapping({
      source: name,
      original: { line: idx + 1, column: 0 },
      generated: { line: idx + 1, column: 0 }
    });
  });
  smg.setSourceContent(name, obj.data);

  map = smg.toJSON();
  map.sourceRoot = '';

  return map;
};
Example #12
0
 secret.mappings.forEach(function(mapping) {
   var sourceCursor = mapping.sourceLines.skipSpaces(mapping.sourceLoc.start) || mapping.sourceLines.lastPos();
   var targetCursor = targetLines.skipSpaces(mapping.targetLoc.start) || targetLines.lastPos();
   while (comparePos(sourceCursor, mapping.sourceLoc.end) < 0 && comparePos(targetCursor, mapping.targetLoc.end) < 0) {
     var sourceChar = mapping.sourceLines.charAt(sourceCursor);
     var targetChar = targetLines.charAt(targetCursor);
     assert.strictEqual(sourceChar, targetChar);
     var sourceName = mapping.sourceLines.name;
     smg.addMapping({
       source: sourceName,
       original: {
         line: sourceCursor.line,
         column: sourceCursor.column
       },
       generated: {
         line: targetCursor.line,
         column: targetCursor.column
       }
     });
     if (!hasOwn.call(sourcesToContents, sourceName)) {
       var sourceContent = mapping.sourceLines.toString();
       smg.setSourceContent(sourceName, sourceContent);
       sourcesToContents[sourceName] = sourceContent;
     }
     targetLines.nextPos(targetCursor, true);
     mapping.sourceLines.nextPos(sourceCursor, true);
   }
 });
Example #13
0
function mergeSourceMaps(
file,
originalMap,
secondMap)
{
  const merged = new sourceMap.SourceMapGenerator();
  const inputMap = new sourceMap.SourceMapConsumer(originalMap);
  new sourceMap.SourceMapConsumer(secondMap).
  eachMapping(mapping => {
    const original = inputMap.originalPositionFor({
      line: mapping.originalLine,
      column: mapping.originalColumn });

    if (original.line == null) {
      return;
    }

    merged.addMapping({
      generated: { line: mapping.generatedLine, column: mapping.generatedColumn },
      original: { line: original.line, column: original.column || 0 },
      source: file,
      name: original.name || mapping.name });

  });
  return merged.toJSON();
}
Example #14
0
function generateCss(sourcePath, fileContent) {
  var generator = new SourceMapGenerator({ file: sourcePath });
  var ast = css.parse(fileContent, { silent: true });

  function registerTokens(ast) {
    if (ast.position) {
      generator.addMapping({
        original: ast.position.start,
        generated: ast.position.start,
        source: sourcePath,
      });
    }

    for (var key in ast) {
      if (key === 'position' || !ast[key]) {
        break;
      }
      if (Object.prototype.toString.call(ast[key]) === '[object Object]') {
        registerTokens(ast[key]);
      } else if (Array.isArray(ast[key])) {
        ast[key].forEach(registerTokens);
      }
    }
  }
  registerTokens(ast);
  generator.setSourceContent(sourcePath, fileContent);

  return generator.toJSON();
}
Example #15
0
 return function* (next) {
   var fileType = (this.url.match(/\.(js)$/) || [])[1];
   var file, content;
   if (fileType === 'js') {
     var yiminghe = this.yiminghe = this.yiminghe || {};
     file = path.join(dir, this.url);
     content = this.body;
     if (!content) {
       var json = 0;
       if (!fs.existsSync(file)) {
         if (util.endsWith(file, '.json.js')) {
           file = file.slice(0, -3);
           json = 1;
         }
       }
       if (!fs.existsSync(file)) {
         return yield *next;
       }
       content = fs.readFileSync(file, 'utf-8');
       yiminghe.source = content;
       if (json) {
         content = 'module.exports = ' + content + ';';
       }
     }
     if (!option.nowrap || !option.nowrap.call(this)) {
       content = modularizeUtils.completeRequire(file, content, option);
       var leading = 'define(function (require, exports, module) {'; // no \n does not change file no
       var contents = content.split(/\n/);
       var map = new SourceMap.SourceMapGenerator({
         file: 'source-mapped.js.map'
       });
       for (var i = 0; i < contents.length; i++) {
         map.addMapping({
           generated: {
             line: i + 1,
             column: 0
           },
           original: {
             line: i + 1,
             column: 0
           },
           source: this.url
         });
       }
       yiminghe.sourceMaps = yiminghe.sourceMaps || [];
       // plain json
       yiminghe.sourceMaps.push(map.toJSON());
       content = leading + content + '\n});';
     }
     this.set('Content-Type', 'application/javascript;charset=utf-8');
     this.set('Content-Length', Buffer.byteLength(content));
     this.body = content;
     if (option.next && option.next.call(this)) {
       yield *next;
     }
   } else {
     yield *next;
   }
 };
Example #16
0
function createDummySourceMap(tokens, options) {
  options = options || {}

  if (typeof tokens === "string") {
    switch (options.type) {
      case "js":
        tokens = tokens.match(jsTokens)
        break
      case "css":
        tokens = tokens.match(cssTokens)
        break
      default:
        throw new Error("If you pass in a string, you must set `options.type` to either " +
                        "`js` or `css`. Got: " + options.type)
    }
  } else if (!Array.isArray(tokens)) {
    throw new Error("Either an array of tokens, or a string of JavaScript or CSS is required. " +
                    "Got: " + tokens)
  }

  if (!options.source) {
    throw new Error("`options.source` is required. Got: " + options.source)
  }

  var map = new sourceMap.SourceMapGenerator({ file: path.basename(options.source) })

  var line = 1
  var column = 0

  tokens.forEach(function(token) {
    if (!blank.test(token)) {
      map.addMapping({
        generated: {
          line: line,
          column: column
        },
        original: {
          line: line,
          column: column
        },
        source: options.source
      })
    }

    var lines = token.split(newline)
    var lastLine = lines.pop()
    var addedLines = lines.length
    if (addedLines) {
      line += addedLines
      column = lastLine.length
    } else {
      column += lastLine.length
    }
  })

  return map.toJSON()
}
var makeSourceMapGenerator = function makeSourceMapGenerator(file) {
  var filename = file.sourceFileName;
  var generator = new _sourceMap.SourceMapGenerator({
    file: filename,
    sourceRoot: file.sourceRoot
  });
  generator.setSourceContent(filename, file.code);
  return generator;
};
Example #18
0
function createSourceMap() {
  var map = new sourceMap.SourceMapGenerator({ file: 'forVisual.css' });
  map.addMapping({
    generated: { line: 2, column: 7 },
    source: 'forVisual.original.css',
    original: { line: 102, column: 107 },
  });
  return map;
}
Example #19
0
function createSourceMap({ source, mappings, code }) {
  const generator = new SourceMapGenerator({ file: source.url });
  mappings.forEach(mapping => generator.addMapping(mapping));
  generator.setSourceContent(source.url, code);

  let consumer = SourceMapConsumer.fromSourceMap(generator);
  _setConsumer(source, consumer);
  return generator.toJSON();
}
Example #20
0
export function makeSourceMapGenerator(file) {
  const filename = file.opts.sourceFileName
  const generator = new SourceMapGenerator({
    file: filename,
    sourceRoot: file.opts.sourceRoot
  })

  generator.setSourceContent(filename, file.code)
  return generator
}
Example #21
0
function makeSourceMapGenerator(file) {
  var generatorOpts = getGeneratorOpts(file);
  var filename = generatorOpts.sourceFileName;
  var generator = new SourceMapGenerator({
    file: filename,
    sourceRoot: generatorOpts.sourceRoot
  });
  generator.setSourceContent(filename, file.code);
  return generator;
}
Example #22
0
function withSourceMap(src, compiled, name, options) {

  //return compiled;

  var compiledLines = compiled.split('\n');
  var generator = new SourceMapGenerator({file: name + '.js'});

  var runTemplateSuffix = '';

  if (options.runTemplate) {

    options.locals = options.locals || {};
    if (options.urlPrefix) {
      options.locals.staticUrl = _staticUrl(options.filename, options.urlPrefix, options.__dirname);
    }

    runTemplateSuffix = "({staticUrl:"+options.locals.staticUrl+"})";
  }

  compiledLines.forEach(function(l, lineno) {
    var m = l.match(/^jade(_|\.)debug\.unshift\(\{ lineno: ([0-9]+)/);
    if (m) {
      var originalLine = Number(m[2]);
      var generatedLine = lineno + 2;

      if (originalLine > 0) {
        generator.addMapping({
          generated: {
            line: generatedLine,
            column: 0
          },
          source: name,
          original: {
            line: originalLine,
            column: 0
          }
        });
      }
    }

    var debugRe = /jade(_|\.)debug\.(shift|unshift)\([^)]*\);?/;
    var match;
    while(match = l.match(debugRe)) {
      l = replaceMatchWith(match, '');
    }
    compiledLines[lineno] =l;
  });
  generator.setSourceContent(name, src);

  var map = convert.fromJSON(generator.toString());
  compiledLines.push(SUFFIX);
  compiledLines.push(runTemplateSuffix);
  compiledLines.push(map.toComment());
  return compiledLines.join('\n');
}
Example #23
0
Lp.getSourceMap = function(sourceMapName, sourceRoot) {
  if (!sourceMapName) {
    return null;
  }
  var targetLines = this;
  function updateJSON(json) {
    json = json || {};
    isString.assert(sourceMapName);
    json.file = sourceMapName;
    if (sourceRoot) {
      isString.assert(sourceRoot);
      json.sourceRoot = sourceRoot;
    }
    return json;
  }
  var secret = getSecret(targetLines);
  if (secret.cachedSourceMap) {
    return updateJSON(secret.cachedSourceMap.toJSON());
  }
  var smg = new sourceMap.SourceMapGenerator(updateJSON());
  var sourcesToContents = {};
  secret.mappings.forEach(function(mapping) {
    var sourceCursor = mapping.sourceLines.skipSpaces(mapping.sourceLoc.start) || mapping.sourceLines.lastPos();
    var targetCursor = targetLines.skipSpaces(mapping.targetLoc.start) || targetLines.lastPos();
    while (comparePos(sourceCursor, mapping.sourceLoc.end) < 0 && comparePos(targetCursor, mapping.targetLoc.end) < 0) {
      var sourceChar = mapping.sourceLines.charAt(sourceCursor);
      var targetChar = targetLines.charAt(targetCursor);
      assert.strictEqual(sourceChar, targetChar);
      var sourceName = mapping.sourceLines.name;
      smg.addMapping({
        source: sourceName,
        original: {
          line: sourceCursor.line,
          column: sourceCursor.column
        },
        generated: {
          line: targetCursor.line,
          column: targetCursor.column
        }
      });
      if (!hasOwn.call(sourcesToContents, sourceName)) {
        var sourceContent = mapping.sourceLines.toString();
        smg.setSourceContent(sourceName, sourceContent);
        sourcesToContents[sourceName] = sourceContent;
      }
      targetLines.nextPos(targetCursor, true);
      mapping.sourceLines.nextPos(sourceCursor, true);
    }
  });
  secret.cachedSourceMap = smg;
  return smg.toJSON();
};
Example #24
0
function xform(mapping) {
  var generator = new sourceMap.SourceMapGenerator({
    file: "foo.js",
    sourceRoot: "http://example.com/"
  });

  generator.addMapping(mapping);

  babel.transform("a=1", {
    sourceMaps: true,
    inputSourceMap: JSON.parse(generator.toString()),
  });
}
Example #25
0
const getOldSourceMap = (mappings, { sourceRoot, source, file }) => {
    const oldSourceMap = new sourceMap.SourceMapGenerator({
        file,
        sourceRoot
    });

    mappings.forEach(mapping => {
        mapping.source = source;
        oldSourceMap.addMapping(mapping);
    });

    return oldSourceMap.toJSON();
};
Example #26
0
function applySourceMap(
  generatedId: string,
  url: string,
  code: string,
  mappings: Object
) {
  const generator = new SourceMapGenerator({ file: url });
  mappings.forEach(mapping => generator.addMapping(mapping));
  generator.setSourceContent(url, code);

  const map = createConsumer(generator.toJSON());
  setSourceMap(generatedId, Promise.resolve(map));
}
Example #27
0
exports.concatenateSourceMaps = function(sourceFilename, mapsWithOffsets, outPath) {
  var generated = new sourceMap.SourceMapGenerator({
    file: sourceFilename
  });

  mapsWithOffsets.forEach(function(pair) {
    var offset = pair[0];
    var mapSource = pair[1];
    var map;
    try {
      map = JSON.parse(mapSource);
    } catch (error) {
      throw new Error(mapSource + ": Invalid JSON");
    }

    // this is odd, sourceRoot is redundant (and causes doubling)
    map.sourceRoot = '';

    wrapSourceMap(map).eachMapping(function(mapping) {
      if (mapping.source.match(/^@traceur/)) {
        return;
      }

      generated.addMapping({
        generated: {
          line: offset + mapping.generatedLine,
          column: mapping.generatedColumn
        },
        original: {
          line: mapping.originalLine,
          column: mapping.originalColumn
        },
        source: mapping.source
      });

      originalLastLine = mapping.generatedLine;
    });
  });

  if (outPath) {
    // convert from library internals format to canonical
    var normalized = JSON.parse(JSON.stringify(generated));
    // convert paths to relative
    normalized.sources = normalized.sources.map(function(source) {
      return path.relative(outPath, source);
    });
    return JSON.stringify(normalized);
  }

  return generated.toString();
};
Example #28
0
function withSourceMap(src, compiled, name) {

  var compiledLines = compiled.split('\n');
  var generator = new SourceMapGenerator({file: name + '.js'});

  compiledLines.forEach(function(l, lineno) {
    var m = l.match(/^jade(_|\.)debug\.unshift\(new jade\.DebugItem\( ([0-9]+)/);
    // Check for older jade debug line format
    if (!m) m = l.match(/^(pug|jade)(_|\.)debug\.unshift\(\{ lineno: ([0-9]+)/);
    if (m) {
      var originalLine = Number(m[2]);
      var generatedLine = lineno + 2;

      if (originalLine > 0) {
        generator.addMapping({
          generated: {
            line: generatedLine,
            column: 0
          },
          source: name,
          original: {
            line: originalLine,
            column: 0
          }
        });
      }
    }

    var debugRe = /(pug|jade)(_|\.)debug\.(shift|unshift)\([^;]*\);/;
    var match;
    while(match = l.match(debugRe)) {
      l = replaceMatchWith(match, '');
    }
    compiledLines[lineno] =l;
  });

  // Remove jade debug lines at beginning and end of compiled version
  if (/var jade_debug = /.test(compiledLines[1])) compiledLines[1] = '';
  if (/try \{/.test(compiledLines[2])) compiledLines[2] = '';
  var l = compiledLines.length;
  if (/\} catch \(err\) \{/.test(compiledLines[l-4])) {
    compiledLines[l-2] = compiledLines[l-3] = compiledLines[l-4] = '';
  }

  generator.setSourceContent(name, src);

  var map = convert.fromJSON(generator.toString());
  compiledLines.push(map.toComment());
  return compiledLines.join('\n');
}
Example #29
0
export default function generate(pundle: Pundle, contents: Array<File>, requires: Array<string>, givenConfig: Object) {
  let lines = 0
  const config = Helpers.fillConfig(givenConfig)

  const output = []
  const sourceMap = new SourceMapGenerator({
    skipValidation: true,
  })

  if (config.wrapper === 'normal') {
    output.push(WrapperNormal)
    lines += Helpers.getLinesCount(WrapperNormal)
  } else if (config.wrapper === 'hmr') {
    output.push(WrapperHMR)
    lines += Helpers.getLinesCount(WrapperHMR)
  } else {
    lines = 1
  }
  for (const file of (contents: Array<File>)) {
    const fileContents = file.contents.trim()
    const entry = `__sb_pundle_register('${pundle.getUniquePathID(file.filePath)}', function(module, exports) {\n${fileContents}\n});`
    output.push(entry)

    if (!config.sourceMap) {
      continue
    }

    const entryPath = file.filePath.replace('$root', `$${config.projectName}`)
    const entryMap = new SourceMapConsumer(file.sourceMap)
    for (const mapping of entryMap._generatedMappings) {
      sourceMap.addMapping({
        source: entryPath,
        original: { line: mapping.originalLine, column: mapping.originalColumn },
        generated: { line: lines + mapping.generatedLine, column: mapping.generatedColumn },
      })
    }
    lines += Helpers.getLinesCount(fileContents)
    lines ++
    sourceMap.setSourceContent(entryPath, file.source)
  }
  for (const entry of (requires: Array<string>)) {
    output.push(`__require('${pundle.getUniquePathID(entry)}')`)
  }

  return {
    contents: output.join(''),
    sourceMap: config.sourceMap ? sourceMap.toJSON() : null,
  }
}
    function() {
      var inFile = grunt.file.read(this.data.source);
      var inMap = grunt.file.read(this.data.source + '.map');
      var inLines = inFile.split('\n');
      var i = 0;

      // Discover copyright header
      while (inLines[i].length < 2 || inLines[i].substring(0, 2) == '//') {
        i++;
      }

      // Fix mapping footer
      var postamble = this.data.postamble;
      if (inLines[inLines.length - 1].substring(0, 21) == '//# sourceMappingURL=') {
        postamble += '\n//# sourceMappingURL=' + this.target + '.map';
      }

      if (i > 0) {
        var banner = inLines.slice(0, i).join('\n') + '\n';
      } else {
        var banner = '';
      }

      var source = inLines.slice(i, inLines.length - 1).join('\n');

      grunt.file.write(this.target, banner + this.data.preamble + source + postamble);
      var preLines = this.data.preamble.split('\n');
      var lineDelta = preLines.length;
      if (this.data.preamble[this.data.preamble.length - 1] == '\n') {
        var charDelta = 0;
      } else {
        var charDelta = preLines[lineDelta - 1].length;
        lineDelta -= 1;
      }
      var inMapConsumer = new sourceMap.SourceMapConsumer(inMap);
      var outMapGenerator = new sourceMap.SourceMapGenerator({file: this.target});
      inMapConsumer.eachMapping(function(mapping) {
        if (mapping.generatedLine == i + 1) {
          mapping.generatedColumn += charDelta;
        }
        mapping.generatedLine += lineDelta;
        outMapGenerator.addMapping(
          {generated: {line: mapping.generatedLine, column: mapping.generatedColumn},
          original: {line: mapping.originalLine, column: mapping.originalColumn},
          source: mapping.source, name: mapping.name});
      });
      grunt.file.write(this.target + '.map', outMapGenerator.toString());
    });