prefer-node-protocol.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict';
  2. const isBuiltinModule = require('is-builtin-module');
  3. const {matches, STATIC_REQUIRE_SOURCE_SELECTOR} = require('./selectors/index.js');
  4. const MESSAGE_ID = 'prefer-node-protocol';
  5. const messages = {
  6. [MESSAGE_ID]: 'Prefer `node:{{moduleName}}` over `{{moduleName}}`.',
  7. };
  8. const importExportSourceSelector = [
  9. ':matches(ImportDeclaration, ExportNamedDeclaration, ImportExpression)',
  10. ' > ',
  11. 'Literal.source',
  12. ].join('');
  13. /** @param {import('eslint').Rule.RuleContext} context */
  14. const create = context => {
  15. const {checkRequire} = {
  16. checkRequire: false,
  17. ...context.options[0],
  18. };
  19. const selectors = [importExportSourceSelector];
  20. if (checkRequire) {
  21. selectors.push(STATIC_REQUIRE_SOURCE_SELECTOR);
  22. }
  23. return {
  24. [matches(selectors)](node) {
  25. const {value} = node;
  26. if (
  27. typeof value !== 'string'
  28. || value.startsWith('node:')
  29. || !isBuiltinModule(value)
  30. ) {
  31. return;
  32. }
  33. const firstCharacterIndex = node.range[0] + 1;
  34. return {
  35. node,
  36. messageId: MESSAGE_ID,
  37. data: {moduleName: value},
  38. /** @param {import('eslint').Rule.RuleFixer} fixer */
  39. fix: fixer => fixer.insertTextBeforeRange([firstCharacterIndex, firstCharacterIndex], 'node:'),
  40. };
  41. },
  42. };
  43. };
  44. const schema = [
  45. {
  46. type: 'object',
  47. additionalProperties: false,
  48. properties: {
  49. checkRequire: {
  50. type: 'boolean',
  51. default: false,
  52. },
  53. },
  54. },
  55. ];
  56. /** @type {import('eslint').Rule.RuleModule} */
  57. module.exports = {
  58. create,
  59. meta: {
  60. type: 'suggestion',
  61. docs: {
  62. description: 'Prefer using the `node:` protocol when importing Node.js builtin modules.',
  63. },
  64. fixable: 'code',
  65. schema,
  66. messages,
  67. },
  68. };