import-target.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * @author Toru Nagashima
  3. * See LICENSE file in root directory for full license.
  4. */
  5. "use strict"
  6. const path = require("path")
  7. const resolve = require("resolve")
  8. /**
  9. * Resolve the given id to file paths.
  10. * @param {boolean} isModule The flag which indicates this id is a module.
  11. * @param {string} id The id to resolve.
  12. * @param {object} options The options of node-resolve module.
  13. * It requires `options.basedir`.
  14. * @returns {string|null} The resolved path.
  15. */
  16. function getFilePath(isModule, id, options) {
  17. try {
  18. return resolve.sync(id, options)
  19. } catch (_err) {
  20. if (isModule) {
  21. return null
  22. }
  23. return path.resolve(options.basedir, id)
  24. }
  25. }
  26. /**
  27. * Gets the module name of a given path.
  28. *
  29. * e.g. `eslint/lib/ast-utils` -> `eslint`
  30. *
  31. * @param {string} nameOrPath - A path to get.
  32. * @returns {string} The module name of the path.
  33. */
  34. function getModuleName(nameOrPath) {
  35. let end = nameOrPath.indexOf("/")
  36. if (end !== -1 && nameOrPath[0] === "@") {
  37. end = nameOrPath.indexOf("/", 1 + end)
  38. }
  39. return end === -1 ? nameOrPath : nameOrPath.slice(0, end)
  40. }
  41. /**
  42. * Information of an import target.
  43. */
  44. module.exports = class ImportTarget {
  45. /**
  46. * Initialize this instance.
  47. * @param {ASTNode} node - The node of a `require()` or a module declaraiton.
  48. * @param {string} name - The name of an import target.
  49. * @param {object} options - The options of `node-resolve` module.
  50. */
  51. constructor(node, name, options) {
  52. const isModule = !/^(?:[./\\]|\w+:)/u.test(name)
  53. /**
  54. * The node of a `require()` or a module declaraiton.
  55. * @type {ASTNode}
  56. */
  57. this.node = node
  58. /**
  59. * The name of this import target.
  60. * @type {string}
  61. */
  62. this.name = name
  63. /**
  64. * The full path of this import target.
  65. * If the target is a module and it does not exist then this is `null`.
  66. * @type {string|null}
  67. */
  68. this.filePath = getFilePath(isModule, name, options)
  69. /**
  70. * The module name of this import target.
  71. * If the target is a relative path then this is `null`.
  72. * @type {string|null}
  73. */
  74. this.moduleName = isModule ? getModuleName(name) : null
  75. }
  76. }