parse.js 2.1 KB

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