You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
2.0 KiB

4 years ago
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const source_map_1 = require("source-map");
  4. const hash = require('hash-sum');
  5. const cache = require('lru-cache')(100);
  6. const splitRE = /\r?\n/g;
  7. const emptyRE = /^(?:\/\/)?\s*$/;
  8. function parse(options) {
  9. const { source, filename = '', compiler, compilerParseOptions = { pad: 'line' }, sourceRoot = '', needMap = true } = options;
  10. const cacheKey = hash(filename + source);
  11. let output = cache.get(cacheKey);
  12. if (output)
  13. return output;
  14. output = compiler.parseComponent(source, compilerParseOptions);
  15. if (needMap) {
  16. if (output.script && !output.script.src) {
  17. output.script.map = generateSourceMap(filename, source, output.script.content, sourceRoot, compilerParseOptions.pad);
  18. }
  19. if (output.styles) {
  20. output.styles.forEach(style => {
  21. if (!style.src) {
  22. style.map = generateSourceMap(filename, source, style.content, sourceRoot, compilerParseOptions.pad);
  23. }
  24. });
  25. }
  26. }
  27. cache.set(cacheKey, output);
  28. return output;
  29. }
  30. exports.parse = parse;
  31. function generateSourceMap(filename, source, generated, sourceRoot, pad) {
  32. const map = new source_map_1.SourceMapGenerator({
  33. file: filename.replace(/\\/g, '/'),
  34. sourceRoot: sourceRoot.replace(/\\/g, '/')
  35. });
  36. let offset = 0;
  37. if (!pad) {
  38. offset =
  39. source
  40. .split(generated)
  41. .shift()
  42. .split(splitRE).length - 1;
  43. }
  44. map.setSourceContent(filename, source);
  45. generated.split(splitRE).forEach((line, index) => {
  46. if (!emptyRE.test(line)) {
  47. map.addMapping({
  48. source: filename,
  49. original: {
  50. line: index + 1 + offset,
  51. column: 0
  52. },
  53. generated: {
  54. line: index + 1,
  55. column: 0
  56. }
  57. });
  58. }
  59. });
  60. return JSON.parse(map.toString());
  61. }