console.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.rewriteConsoleExpr = void 0;
  7. const magic_string_1 = __importDefault(require("magic-string"));
  8. const utils_1 = require("../utils");
  9. function rewriteConsoleExpr(method, id, filename, code, sourceMap = false) {
  10. filename = (0, utils_1.normalizePath)(filename);
  11. const re = /(console\.(log|info|debug|warn|error))\(([^)]+)\)/g;
  12. const locate = getLocator(code);
  13. const s = new magic_string_1.default(code);
  14. let match;
  15. while ((match = re.exec(code))) {
  16. const [, expr, type] = match;
  17. s.overwrite(match.index, match.index + expr.length + 1, method + `('${type}','at ${filename}:${locate(match.index).line + 1}',`);
  18. }
  19. return {
  20. code: s.toString(),
  21. map: sourceMap ? s.generateMap({ source: id, hires: true }) : null,
  22. };
  23. }
  24. exports.rewriteConsoleExpr = rewriteConsoleExpr;
  25. function getLocator(source) {
  26. const originalLines = source.split('\n');
  27. const lineOffsets = [];
  28. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  29. lineOffsets.push(pos);
  30. pos += originalLines[i].length + 1;
  31. }
  32. return function locate(index) {
  33. let i = 0;
  34. let j = lineOffsets.length;
  35. while (i < j) {
  36. const m = (i + j) >> 1;
  37. if (index < lineOffsets[m]) {
  38. j = m;
  39. }
  40. else {
  41. i = m + 1;
  42. }
  43. }
  44. const line = i - 1;
  45. const column = index - lineOffsets[line];
  46. return { line, column };
  47. };
  48. }