mapping-entry.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. var path = require("path");
  4. /**
  5. * Converts an absolute baseUrl and paths to an array of absolute mapping entries.
  6. * The array is sorted by longest prefix.
  7. * Having an array with entries allows us to keep a sorting order rather than
  8. * sort by keys each time we use the mappings.
  9. * @param absoluteBaseUrl
  10. * @param paths
  11. * @param addMatchAll
  12. */
  13. function getAbsoluteMappingEntries(absoluteBaseUrl, paths, addMatchAll) {
  14. // Resolve all paths to absolute form once here, and sort them by
  15. // longest prefix once here, this saves time on each request later.
  16. // We need to put them in an array to preseve the sorting order.
  17. var sortedKeys = sortByLongestPrefix(Object.keys(paths));
  18. var absolutePaths = [];
  19. for (var _i = 0, sortedKeys_1 = sortedKeys; _i < sortedKeys_1.length; _i++) {
  20. var key = sortedKeys_1[_i];
  21. absolutePaths.push({
  22. pattern: key,
  23. paths: paths[key].map(function (pathToResolve) {
  24. return path.join(absoluteBaseUrl, pathToResolve);
  25. })
  26. });
  27. }
  28. // If there is no match-all path specified in the paths section of tsconfig, then try to match
  29. // all paths relative to baseUrl, this is how typescript works.
  30. if (!paths["*"] && addMatchAll) {
  31. absolutePaths.push({
  32. pattern: "*",
  33. paths: [absoluteBaseUrl.replace(/\/$/, "") + "/*"]
  34. });
  35. }
  36. return absolutePaths;
  37. }
  38. exports.getAbsoluteMappingEntries = getAbsoluteMappingEntries;
  39. /**
  40. * Sort path patterns.
  41. * If a module name can be matched with multiple patterns then pattern with the longest prefix will be picked.
  42. */
  43. function sortByLongestPrefix(arr) {
  44. return arr
  45. .concat()
  46. .sort(function (a, b) { return getPrefixLength(b) - getPrefixLength(a); });
  47. }
  48. function getPrefixLength(pattern) {
  49. var prefixLength = pattern.indexOf("*");
  50. return pattern.substr(0, prefixLength).length;
  51. }