All files / src node-base.js

100% Statements 16/16
75% Branches 6/8
100% Functions 2/2
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198                              1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x   1x                   1x       2x                                                                                                                                                                                                                                                                                       2x                        
/* eslint-disable node/no-process-env -- Simple NODE_ENV access */
 
/**
 * Module notes: This config handles two types of Node projects: ESM and
 * CommonJS.
 * - ESM projects will have a type of `module` in their package.json and are
 *   expected to still be using .js file extensions. These projects may have
 *   scripts or configuration files run by CommonJS tools (like Jest and
 *   ESLint), which will have .cjs file extensions. Overrides
 * - CommonJS projects are expected to use .js file extensions for all files,
 *   and all files will use commonJS modules
 */
 
'use strict'
 
const path = require('path')
 
const coreBestPractices = require('./rules/core-best-practices')
const coreEcmaScript = require('./rules/core-ecma-script')
const corePossibleErrors = require('./rules/core-possible-errors')
const coreStylisticIssues = require('./rules/core-stylistic-issues')
const coreVariables = require('./rules/core-variables')
 
const pluginImport = require('./rules/plugin-import')
const pluginJest = require('./rules/plugin-jest')
const pluginJestFormatting = require('./rules/plugin-jest-formatting')
const pluginNode = require('./rules/plugin-node')
const pluginTypescript = require('./rules/plugin-typescript')
 
const envRuleSeverities = require('./rule-severities')
 
const { NODE_ENV } = process.env
 
/**
 * Base configs for Node.js projects
 * @param {Object} options
 * @param {Record<string, unknown>} [options.rules]
 * @param {'module' | 'script'} [options.sourceType]
 * @param {string[]} [options.tsconfigs]
 * @returns
 */
module.exports = ({
  rules = {},
  sourceType = 'module',
  tsconfigs = ['./tsconfig.json'],
} = {}) => ({
  // Node plugin will check package.json type field and set correct Node
  // globals, sourceType, and overrides for .cjs files
  extends: ['plugin:node/recommended'],
 
  // Default expectation is a single config at root of project, with overrides
  // for directory and file customizations
  root: true,
 
  // Project custom ignore patterns, defaults to ignoring build directories
  // and forcing linting of dot files and directories
  ignorePatterns: ['!.*', 'public/*', 'dist/*'],
 
  // Provides warnings for eslint-disable directives that aren't necessary
  reportUnusedDisableDirectives: true,
 
  parser: '@typescript-eslint/parser', // All in on TS
  parserOptions: {
    ecmaVersion: 12,
    ecmaFeatures: {},
    // Projects must provide a TS config, this needs to be configurable to support
    // applications possibly including multiple tsConfigs for Cypress
    project: tsconfigs,
    extraFileExtensions: ['.cjs'],
  },
 
  plugins: ['@typescript-eslint', 'import', 'prettier'],
 
  settings: {
    // Increase import cache lifetime to 60s
    'import/cache': 60,
 
    // Mark `@/..` imports as "internal", used by the `import/order` rule
    'import/internal-regex': /^@\//,
 
    // Use Node resolver upgraded with `@` alias support
    'import/resolver': path.resolve(__dirname, 'resolver'),
 
    // ℹ️ Import plugin TS configs apply to all projects, ref plugin:import/typescript
 
    // Extensions that will be parsed to check for exports, including JS, TS,
    // React extenions, Node ESM, and type definitions
    'import/extensions': ['.cjs', '.js', '.mjs', '.ts', '.d.ts'],
 
    // Ensure that types are considered external imports
    'import/external-module-folders': ['node_modules', 'node_modules/@types'],
  },
 
  env: {
    es6: true,
  },
 
  rules: envRuleSeverities(NODE_ENV, {
    // --- ESLint core rules configuration ---
    ...coreBestPractices,
    ...coreEcmaScript,
    ...corePossibleErrors,
    ...coreStylisticIssues,
    ...coreVariables,
 
    // --- Plugin import rules ---
    ...pluginImport,
    ...pluginNode,
    ...pluginTypescript,
 
    ...sourceTypeRules(sourceType),
 
    // ⓘ Prettier formatting enforcement enabled by Prettier *plugin*
    'prettier/prettier': 'error',
    // Core rules that conflict with Prettier not disabled by eslint-config-prettier
    'arrow-body-style': 'off',
    'prefer-arrow-callback': 'off',
 
    // Custom project rules have priority over package rules
    ...rules,
  }),
 
  // --------------------------------------------------------
  // File overrides (Override directories, then extensions, then files)
  overrides: [
    // --- 1️⃣ Source directory --------------------------
    {
      files: ['src/**/*'],
 
      rules: {
        // ℹ️ Prevent forgotten console.logs only needed in project source
        // code
        'no-console': NODE_ENV === 'test' ? 'error' : 'warn',
 
        // ℹ️ In project source code ensure that access to process.env is
        // controlled.
        'node/no-process-env': 'error',
 
        // ℹ️ Imported modules in project source need to be declared as
        // dependencies to ensure they're available in production
        'import/no-extraneous-dependencies': [
          'error',
          // Allow imports from devDependencies in story and test files
          { devDependencies: ['**/*.{spec}.{cjs,mjs,js}'] },
        ],
      },
    },
 
    // --- ✅ Test files --------------------------
    {
      files: ['*.spec.js'],
 
      plugins: ['jest', 'jest-formatting'],
      env: { jest: true },
 
      rules: {
        // In Jest test files allow defining `jest.mock()` calls before imports
        // Under the hood Jest hoists these to the top of the file and it helps
        // visually distinguish modules that are being replaced with mocks
        'import/first': 'off',
        ...pluginJest,
        ...pluginJestFormatting,
      },
    },
 
    // --- 💾 CommonJS files --------------------------
    {
      files: ['*.cjs'], // Only for files *opted* into CJS *inside* an ESM project
      rules: {
        '@typescript-eslint/no-var-requires': 'off',
        'import/extensions': ['error', 'ignorePackages'],
      },
    },
  ],
})
 
/**
 * Compute source type dependent rules applied to all .js files.
 * @param {'module' | 'script'} sourceType
 * @returns {Record<string, unknown>}
 * @remarks
 * These rules are "temporary" until ESM is supported by all tools, then the
 * rules for module source type can be used all the time
 */
function sourceTypeRules(sourceType) {
  return sourceType === 'module'
    ? {
        // ESM projects must specify all import extensions
        'import/extensions': ['error', 'ignorePackages'],
        // ESM requires full import paths (override default noUselessIndex)
        'import/no-useless-path-segments': 'error',
      }
    : {
        // Legacy CJS projects still use require() in .js files
        '@typescript-eslint/no-var-requires': 'off',
      }
}