check-publish.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 getAllowModules = require("./get-allow-modules")
  8. const getConvertPath = require("./get-convert-path")
  9. const getNpmignore = require("./get-npmignore")
  10. const getPackageJson = require("./get-package-json")
  11. /**
  12. * Checks whether or not each requirement target is published via package.json.
  13. *
  14. * It reads package.json and checks the target exists in `dependencies`.
  15. *
  16. * @param {RuleContext} context - A context to report.
  17. * @param {string} filePath - The current file path.
  18. * @param {ImportTarget[]} targets - A list of target information to check.
  19. * @returns {void}
  20. */
  21. module.exports = function checkForPublish(context, filePath, targets) {
  22. const packageInfo = getPackageJson(filePath)
  23. if (!packageInfo) {
  24. return
  25. }
  26. const allowed = new Set(getAllowModules(context))
  27. const convertPath = getConvertPath(context)
  28. const basedir = path.dirname(packageInfo.filePath)
  29. // eslint-disable-next-line func-style
  30. const toRelative = fullPath => {
  31. const retv = path.relative(basedir, fullPath).replace(/\\/gu, "/")
  32. return convertPath(retv)
  33. }
  34. const npmignore = getNpmignore(filePath)
  35. const devDependencies = new Set(
  36. Object.keys(packageInfo.devDependencies || {})
  37. )
  38. const dependencies = new Set(
  39. [].concat(
  40. Object.keys(packageInfo.dependencies || {}),
  41. Object.keys(packageInfo.peerDependencies || {}),
  42. Object.keys(packageInfo.optionalDependencies || {})
  43. )
  44. )
  45. if (!npmignore.match(toRelative(filePath))) {
  46. // This file is published, so this cannot import private files.
  47. for (const target of targets) {
  48. const isPrivateFile =
  49. target.moduleName == null &&
  50. npmignore.match(toRelative(target.filePath))
  51. const isDevPackage =
  52. target.moduleName != null &&
  53. devDependencies.has(target.moduleName) &&
  54. !dependencies.has(target.moduleName) &&
  55. !allowed.has(target.moduleName)
  56. if (isPrivateFile || isDevPackage) {
  57. context.report({
  58. node: target.node,
  59. loc: target.node.loc,
  60. message: '"{{name}}" is not published.',
  61. data: { name: target.moduleName || target.name },
  62. })
  63. }
  64. }
  65. }
  66. }