bahlint 28.58.6934

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (420) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +370 -0
  3. package/bin/eslint.js +195 -0
  4. package/conf/ecma-version.js +16 -0
  5. package/conf/globals.js +169 -0
  6. package/conf/replacements.json +26 -0
  7. package/conf/rule-type-list.json +91 -0
  8. package/lib/api.js +39 -0
  9. package/lib/cli-engine/formatters/formatters-meta.json +22 -0
  10. package/lib/cli-engine/formatters/gasoline.js +168 -0
  11. package/lib/cli-engine/formatters/html.js +359 -0
  12. package/lib/cli-engine/formatters/json-with-metadata.js +16 -0
  13. package/lib/cli-engine/formatters/json.js +13 -0
  14. package/lib/cli-engine/formatters/stylish.js +153 -0
  15. package/lib/cli-engine/hash.js +35 -0
  16. package/lib/cli-engine/lint-result-cache.js +220 -0
  17. package/lib/cli.js +607 -0
  18. package/lib/config/config-loader.js +683 -0
  19. package/lib/config/config.js +674 -0
  20. package/lib/config/default-config.js +78 -0
  21. package/lib/config/flat-config-array.js +217 -0
  22. package/lib/config/flat-config-schema.js +598 -0
  23. package/lib/config-api.js +12 -0
  24. package/lib/eslint/eslint-helpers.js +1462 -0
  25. package/lib/eslint/eslint.js +1364 -0
  26. package/lib/eslint/index.js +7 -0
  27. package/lib/eslint/worker.js +173 -0
  28. package/lib/languages/js/index.js +336 -0
  29. package/lib/languages/js/source-code/index.js +7 -0
  30. package/lib/languages/js/source-code/source-code.js +1178 -0
  31. package/lib/languages/js/source-code/token-store/backward-token-comment-cursor.js +61 -0
  32. package/lib/languages/js/source-code/token-store/backward-token-cursor.js +57 -0
  33. package/lib/languages/js/source-code/token-store/cursor.js +76 -0
  34. package/lib/languages/js/source-code/token-store/cursors.js +120 -0
  35. package/lib/languages/js/source-code/token-store/decorative-cursor.js +38 -0
  36. package/lib/languages/js/source-code/token-store/filter-cursor.js +42 -0
  37. package/lib/languages/js/source-code/token-store/forward-token-comment-cursor.js +65 -0
  38. package/lib/languages/js/source-code/token-store/forward-token-cursor.js +62 -0
  39. package/lib/languages/js/source-code/token-store/index.js +695 -0
  40. package/lib/languages/js/source-code/token-store/limit-cursor.js +39 -0
  41. package/lib/languages/js/source-code/token-store/padded-token-cursor.js +45 -0
  42. package/lib/languages/js/source-code/token-store/skip-cursor.js +41 -0
  43. package/lib/languages/js/source-code/token-store/utils.js +131 -0
  44. package/lib/languages/js/validate-language-options.js +196 -0
  45. package/lib/linter/apply-disable-directives.js +583 -0
  46. package/lib/linter/code-path-analysis/code-path-analyzer.js +828 -0
  47. package/lib/linter/code-path-analysis/code-path-segment.js +262 -0
  48. package/lib/linter/code-path-analysis/code-path-state.js +2370 -0
  49. package/lib/linter/code-path-analysis/code-path.js +332 -0
  50. package/lib/linter/code-path-analysis/debug-helpers.js +223 -0
  51. package/lib/linter/code-path-analysis/fork-context.js +374 -0
  52. package/lib/linter/code-path-analysis/id-generator.js +44 -0
  53. package/lib/linter/esquery.js +332 -0
  54. package/lib/linter/file-context.js +88 -0
  55. package/lib/linter/file-report.js +604 -0
  56. package/lib/linter/index.js +11 -0
  57. package/lib/linter/interpolate.js +50 -0
  58. package/lib/linter/linter.js +1614 -0
  59. package/lib/linter/rule-fixer.js +199 -0
  60. package/lib/linter/source-code-fixer.js +154 -0
  61. package/lib/linter/source-code-traverser.js +333 -0
  62. package/lib/linter/source-code-visitor.js +81 -0
  63. package/lib/linter/timing.js +209 -0
  64. package/lib/linter/vfile.js +115 -0
  65. package/lib/options.js +416 -0
  66. package/lib/rule-tester/index.js +7 -0
  67. package/lib/rule-tester/rule-tester.js +1817 -0
  68. package/lib/rules/accessor-pairs.js +420 -0
  69. package/lib/rules/array-bracket-newline.js +291 -0
  70. package/lib/rules/array-bracket-spacing.js +301 -0
  71. package/lib/rules/array-callback-return.js +493 -0
  72. package/lib/rules/array-element-newline.js +374 -0
  73. package/lib/rules/arrow-body-style.js +418 -0
  74. package/lib/rules/arrow-parens.js +237 -0
  75. package/lib/rules/arrow-spacing.js +188 -0
  76. package/lib/rules/block-scoped-var.js +137 -0
  77. package/lib/rules/block-spacing.js +202 -0
  78. package/lib/rules/brace-style.js +278 -0
  79. package/lib/rules/callback-return.js +216 -0
  80. package/lib/rules/camelcase.js +422 -0
  81. package/lib/rules/capitalized-comments.js +325 -0
  82. package/lib/rules/class-methods-use-this.js +250 -0
  83. package/lib/rules/comma-dangle.js +424 -0
  84. package/lib/rules/comma-spacing.js +205 -0
  85. package/lib/rules/comma-style.js +391 -0
  86. package/lib/rules/complexity.js +201 -0
  87. package/lib/rules/computed-property-spacing.js +251 -0
  88. package/lib/rules/consistent-return.js +221 -0
  89. package/lib/rules/consistent-this.js +179 -0
  90. package/lib/rules/constructor-super.js +453 -0
  91. package/lib/rules/curly.js +425 -0
  92. package/lib/rules/default-case-last.js +51 -0
  93. package/lib/rules/default-case.js +103 -0
  94. package/lib/rules/default-param-last.js +78 -0
  95. package/lib/rules/dot-location.js +138 -0
  96. package/lib/rules/dot-notation.js +216 -0
  97. package/lib/rules/eol-last.js +135 -0
  98. package/lib/rules/eqeqeq.js +210 -0
  99. package/lib/rules/for-direction.js +168 -0
  100. package/lib/rules/func-call-spacing.js +281 -0
  101. package/lib/rules/func-name-matching.js +338 -0
  102. package/lib/rules/func-names.js +194 -0
  103. package/lib/rules/func-style.js +221 -0
  104. package/lib/rules/function-call-argument-newline.js +166 -0
  105. package/lib/rules/function-paren-newline.js +368 -0
  106. package/lib/rules/generator-star-spacing.js +246 -0
  107. package/lib/rules/getter-return.js +242 -0
  108. package/lib/rules/global-require.js +117 -0
  109. package/lib/rules/grouped-accessor-pairs.js +268 -0
  110. package/lib/rules/guard-for-in.js +85 -0
  111. package/lib/rules/handle-callback-err.js +122 -0
  112. package/lib/rules/id-blacklist.js +241 -0
  113. package/lib/rules/id-denylist.js +223 -0
  114. package/lib/rules/id-length.js +217 -0
  115. package/lib/rules/id-match.js +363 -0
  116. package/lib/rules/implicit-arrow-linebreak.js +125 -0
  117. package/lib/rules/indent-legacy.js +1369 -0
  118. package/lib/rules/indent.js +2334 -0
  119. package/lib/rules/index.js +332 -0
  120. package/lib/rules/init-declarations.js +172 -0
  121. package/lib/rules/jsx-quotes.js +128 -0
  122. package/lib/rules/key-spacing.js +822 -0
  123. package/lib/rules/keyword-spacing.js +701 -0
  124. package/lib/rules/line-comment-position.js +157 -0
  125. package/lib/rules/linebreak-style.js +135 -0
  126. package/lib/rules/lines-around-comment.js +581 -0
  127. package/lib/rules/lines-around-directive.js +249 -0
  128. package/lib/rules/lines-between-class-members.js +358 -0
  129. package/lib/rules/logical-assignment-operators.js +688 -0
  130. package/lib/rules/max-classes-per-file.js +90 -0
  131. package/lib/rules/max-depth.js +159 -0
  132. package/lib/rules/max-len.js +497 -0
  133. package/lib/rules/max-lines-per-function.js +238 -0
  134. package/lib/rules/max-lines.js +189 -0
  135. package/lib/rules/max-nested-callbacks.js +115 -0
  136. package/lib/rules/max-params.js +148 -0
  137. package/lib/rules/max-statements-per-line.js +224 -0
  138. package/lib/rules/max-statements.js +188 -0
  139. package/lib/rules/multiline-comment-style.js +652 -0
  140. package/lib/rules/multiline-ternary.js +257 -0
  141. package/lib/rules/new-cap.js +277 -0
  142. package/lib/rules/new-parens.js +120 -0
  143. package/lib/rules/newline-after-var.js +307 -0
  144. package/lib/rules/newline-before-return.js +242 -0
  145. package/lib/rules/newline-per-chained-call.js +159 -0
  146. package/lib/rules/no-alert.js +149 -0
  147. package/lib/rules/no-array-constructor.js +195 -0
  148. package/lib/rules/no-async-promise-executor.js +45 -0
  149. package/lib/rules/no-await-in-loop.js +115 -0
  150. package/lib/rules/no-bitwise.js +145 -0
  151. package/lib/rules/no-buffer-constructor.js +74 -0
  152. package/lib/rules/no-caller.js +52 -0
  153. package/lib/rules/no-case-declarations.js +80 -0
  154. package/lib/rules/no-catch-shadow.js +96 -0
  155. package/lib/rules/no-class-assign.js +66 -0
  156. package/lib/rules/no-compare-neg-zero.js +74 -0
  157. package/lib/rules/no-cond-assign.js +175 -0
  158. package/lib/rules/no-confusing-arrow.js +127 -0
  159. package/lib/rules/no-console.js +221 -0
  160. package/lib/rules/no-const-assign.js +73 -0
  161. package/lib/rules/no-constant-binary-expression.js +603 -0
  162. package/lib/rules/no-constant-condition.js +177 -0
  163. package/lib/rules/no-constructor-return.js +62 -0
  164. package/lib/rules/no-continue.js +38 -0
  165. package/lib/rules/no-control-regex.js +142 -0
  166. package/lib/rules/no-debugger.js +41 -0
  167. package/lib/rules/no-delete-var.js +42 -0
  168. package/lib/rules/no-div-regex.js +60 -0
  169. package/lib/rules/no-dupe-args.js +92 -0
  170. package/lib/rules/no-dupe-class-members.js +117 -0
  171. package/lib/rules/no-dupe-else-if.js +145 -0
  172. package/lib/rules/no-dupe-keys.js +165 -0
  173. package/lib/rules/no-duplicate-case.js +78 -0
  174. package/lib/rules/no-duplicate-imports.js +368 -0
  175. package/lib/rules/no-else-return.js +450 -0
  176. package/lib/rules/no-empty-character-class.js +83 -0
  177. package/lib/rules/no-empty-function.js +236 -0
  178. package/lib/rules/no-empty-pattern.js +85 -0
  179. package/lib/rules/no-empty-static-block.js +73 -0
  180. package/lib/rules/no-empty.js +153 -0
  181. package/lib/rules/no-eq-null.js +51 -0
  182. package/lib/rules/no-eval.js +295 -0
  183. package/lib/rules/no-ex-assign.js +57 -0
  184. package/lib/rules/no-extend-native.js +180 -0
  185. package/lib/rules/no-extra-bind.js +224 -0
  186. package/lib/rules/no-extra-boolean-cast.js +420 -0
  187. package/lib/rules/no-extra-label.js +169 -0
  188. package/lib/rules/no-extra-parens.js +1669 -0
  189. package/lib/rules/no-extra-semi.js +167 -0
  190. package/lib/rules/no-fallthrough.js +260 -0
  191. package/lib/rules/no-floating-decimal.js +99 -0
  192. package/lib/rules/no-func-assign.js +77 -0
  193. package/lib/rules/no-global-assign.js +101 -0
  194. package/lib/rules/no-implicit-coercion.js +468 -0
  195. package/lib/rules/no-implicit-globals.js +187 -0
  196. package/lib/rules/no-implied-eval.js +170 -0
  197. package/lib/rules/no-import-assign.js +227 -0
  198. package/lib/rules/no-inline-comments.js +115 -0
  199. package/lib/rules/no-inner-declarations.js +147 -0
  200. package/lib/rules/no-invalid-regexp.js +244 -0
  201. package/lib/rules/no-invalid-this.js +178 -0
  202. package/lib/rules/no-irregular-whitespace.js +292 -0
  203. package/lib/rules/no-iterator.js +48 -0
  204. package/lib/rules/no-label-var.js +78 -0
  205. package/lib/rules/no-labels.js +156 -0
  206. package/lib/rules/no-lone-blocks.js +140 -0
  207. package/lib/rules/no-lonely-if.js +126 -0
  208. package/lib/rules/no-loop-func.js +267 -0
  209. package/lib/rules/no-loss-of-precision.js +249 -0
  210. package/lib/rules/no-magic-numbers.js +365 -0
  211. package/lib/rules/no-misleading-character-class.js +595 -0
  212. package/lib/rules/no-mixed-operators.js +253 -0
  213. package/lib/rules/no-mixed-requires.js +267 -0
  214. package/lib/rules/no-mixed-spaces-and-tabs.js +148 -0
  215. package/lib/rules/no-multi-assign.js +66 -0
  216. package/lib/rules/no-multi-spaces.js +179 -0
  217. package/lib/rules/no-multi-str.js +67 -0
  218. package/lib/rules/no-multiple-empty-lines.js +210 -0
  219. package/lib/rules/no-native-reassign.js +114 -0
  220. package/lib/rules/no-negated-condition.js +100 -0
  221. package/lib/rules/no-negated-in-lhs.js +59 -0
  222. package/lib/rules/no-nested-ternary.js +46 -0
  223. package/lib/rules/no-new-func.js +96 -0
  224. package/lib/rules/no-new-native-nonconstructor.js +70 -0
  225. package/lib/rules/no-new-object.js +76 -0
  226. package/lib/rules/no-new-require.js +67 -0
  227. package/lib/rules/no-new-symbol.js +74 -0
  228. package/lib/rules/no-new-wrappers.js +62 -0
  229. package/lib/rules/no-new.js +42 -0
  230. package/lib/rules/no-nonoctal-decimal-escape.js +176 -0
  231. package/lib/rules/no-obj-calls.js +99 -0
  232. package/lib/rules/no-object-constructor.js +124 -0
  233. package/lib/rules/no-octal-escape.js +53 -0
  234. package/lib/rules/no-octal.js +42 -0
  235. package/lib/rules/no-param-reassign.js +248 -0
  236. package/lib/rules/no-path-concat.js +79 -0
  237. package/lib/rules/no-plusplus.js +102 -0
  238. package/lib/rules/no-process-env.js +68 -0
  239. package/lib/rules/no-process-exit.js +67 -0
  240. package/lib/rules/no-promise-executor-return.js +264 -0
  241. package/lib/rules/no-proto.js +45 -0
  242. package/lib/rules/no-prototype-builtins.js +181 -0
  243. package/lib/rules/no-redeclare.js +173 -0
  244. package/lib/rules/no-regex-spaces.js +219 -0
  245. package/lib/rules/no-restricted-exports.js +227 -0
  246. package/lib/rules/no-restricted-globals.js +266 -0
  247. package/lib/rules/no-restricted-imports.js +892 -0
  248. package/lib/rules/no-restricted-modules.js +249 -0
  249. package/lib/rules/no-restricted-properties.js +233 -0
  250. package/lib/rules/no-restricted-syntax.js +74 -0
  251. package/lib/rules/no-return-assign.js +87 -0
  252. package/lib/rules/no-return-await.js +162 -0
  253. package/lib/rules/no-script-url.js +68 -0
  254. package/lib/rules/no-self-assign.js +186 -0
  255. package/lib/rules/no-self-compare.js +77 -0
  256. package/lib/rules/no-sequences.js +158 -0
  257. package/lib/rules/no-setter-return.js +224 -0
  258. package/lib/rules/no-shadow-restricted-names.js +113 -0
  259. package/lib/rules/no-shadow.js +624 -0
  260. package/lib/rules/no-spaced-func.js +105 -0
  261. package/lib/rules/no-sparse-arrays.js +68 -0
  262. package/lib/rules/no-sync.js +81 -0
  263. package/lib/rules/no-tabs.js +110 -0
  264. package/lib/rules/no-template-curly-in-string.js +45 -0
  265. package/lib/rules/no-ternary.js +38 -0
  266. package/lib/rules/no-this-before-super.js +365 -0
  267. package/lib/rules/no-throw-literal.js +46 -0
  268. package/lib/rules/no-trailing-spaces.js +227 -0
  269. package/lib/rules/no-unassigned-vars.js +80 -0
  270. package/lib/rules/no-undef-init.js +101 -0
  271. package/lib/rules/no-undef.js +84 -0
  272. package/lib/rules/no-undefined.js +85 -0
  273. package/lib/rules/no-underscore-dangle.js +383 -0
  274. package/lib/rules/no-unexpected-multiline.js +130 -0
  275. package/lib/rules/no-unmodified-loop-condition.js +360 -0
  276. package/lib/rules/no-unneeded-ternary.js +232 -0
  277. package/lib/rules/no-unreachable-loop.js +190 -0
  278. package/lib/rules/no-unreachable.js +300 -0
  279. package/lib/rules/no-unsafe-finally.js +119 -0
  280. package/lib/rules/no-unsafe-negation.js +152 -0
  281. package/lib/rules/no-unsafe-optional-chaining.js +221 -0
  282. package/lib/rules/no-unused-expressions.js +227 -0
  283. package/lib/rules/no-unused-labels.js +158 -0
  284. package/lib/rules/no-unused-private-class-members.js +219 -0
  285. package/lib/rules/no-unused-vars.js +1739 -0
  286. package/lib/rules/no-use-before-define.js +446 -0
  287. package/lib/rules/no-useless-assignment.js +657 -0
  288. package/lib/rules/no-useless-backreference.js +263 -0
  289. package/lib/rules/no-useless-call.js +95 -0
  290. package/lib/rules/no-useless-catch.js +57 -0
  291. package/lib/rules/no-useless-computed-key.js +204 -0
  292. package/lib/rules/no-useless-concat.js +121 -0
  293. package/lib/rules/no-useless-constructor.js +262 -0
  294. package/lib/rules/no-useless-escape.js +406 -0
  295. package/lib/rules/no-useless-rename.js +202 -0
  296. package/lib/rules/no-useless-return.js +401 -0
  297. package/lib/rules/no-var.js +367 -0
  298. package/lib/rules/no-void.js +69 -0
  299. package/lib/rules/no-warning-comments.js +209 -0
  300. package/lib/rules/no-whitespace-before-property.js +150 -0
  301. package/lib/rules/no-with.js +37 -0
  302. package/lib/rules/nonblock-statement-body-position.js +164 -0
  303. package/lib/rules/object-curly-newline.js +383 -0
  304. package/lib/rules/object-curly-spacing.js +369 -0
  305. package/lib/rules/object-property-newline.js +151 -0
  306. package/lib/rules/object-shorthand.js +652 -0
  307. package/lib/rules/one-var-declaration-per-line.js +117 -0
  308. package/lib/rules/one-var.js +717 -0
  309. package/lib/rules/operator-assignment.js +270 -0
  310. package/lib/rules/operator-linebreak.js +315 -0
  311. package/lib/rules/padded-blocks.js +366 -0
  312. package/lib/rules/padding-line-between-statements.js +612 -0
  313. package/lib/rules/prefer-arrow-callback.js +437 -0
  314. package/lib/rules/prefer-const.js +546 -0
  315. package/lib/rules/prefer-destructuring.js +332 -0
  316. package/lib/rules/prefer-exponentiation-operator.js +235 -0
  317. package/lib/rules/prefer-named-capture-group.js +197 -0
  318. package/lib/rules/prefer-numeric-literals.js +157 -0
  319. package/lib/rules/prefer-object-has-own.js +148 -0
  320. package/lib/rules/prefer-object-spread.js +319 -0
  321. package/lib/rules/prefer-promise-reject-errors.js +154 -0
  322. package/lib/rules/prefer-reflect.js +150 -0
  323. package/lib/rules/prefer-regex-literals.js +605 -0
  324. package/lib/rules/prefer-rest-params.js +117 -0
  325. package/lib/rules/prefer-spread.js +91 -0
  326. package/lib/rules/prefer-template.js +347 -0
  327. package/lib/rules/preserve-caught-error.js +535 -0
  328. package/lib/rules/quote-props.js +394 -0
  329. package/lib/rules/quotes.js +416 -0
  330. package/lib/rules/radix.js +193 -0
  331. package/lib/rules/require-atomic-updates.js +365 -0
  332. package/lib/rules/require-await.js +184 -0
  333. package/lib/rules/require-unicode-regexp.js +317 -0
  334. package/lib/rules/require-yield.js +86 -0
  335. package/lib/rules/rest-spread-spacing.js +150 -0
  336. package/lib/rules/semi-spacing.js +297 -0
  337. package/lib/rules/semi-style.js +218 -0
  338. package/lib/rules/semi.js +476 -0
  339. package/lib/rules/sort-imports.js +319 -0
  340. package/lib/rules/sort-keys.js +268 -0
  341. package/lib/rules/sort-vars.js +140 -0
  342. package/lib/rules/space-before-blocks.js +232 -0
  343. package/lib/rules/space-before-function-paren.js +202 -0
  344. package/lib/rules/space-in-parens.js +374 -0
  345. package/lib/rules/space-infix-ops.js +249 -0
  346. package/lib/rules/space-unary-ops.js +400 -0
  347. package/lib/rules/spaced-comment.js +447 -0
  348. package/lib/rules/strict.js +314 -0
  349. package/lib/rules/switch-colon-spacing.js +158 -0
  350. package/lib/rules/symbol-description.js +70 -0
  351. package/lib/rules/template-curly-spacing.js +168 -0
  352. package/lib/rules/template-tag-spacing.js +121 -0
  353. package/lib/rules/unicode-bom.js +73 -0
  354. package/lib/rules/use-isnan.js +268 -0
  355. package/lib/rules/utils/ast-utils.js +2828 -0
  356. package/lib/rules/utils/char-source.js +247 -0
  357. package/lib/rules/utils/fix-tracker.js +125 -0
  358. package/lib/rules/utils/keywords.js +67 -0
  359. package/lib/rules/utils/lazy-loading-rule-map.js +118 -0
  360. package/lib/rules/utils/regular-expressions.js +58 -0
  361. package/lib/rules/utils/unicode/index.js +16 -0
  362. package/lib/rules/utils/unicode/is-combining-character.js +13 -0
  363. package/lib/rules/utils/unicode/is-emoji-modifier.js +13 -0
  364. package/lib/rules/utils/unicode/is-regional-indicator-symbol.js +13 -0
  365. package/lib/rules/utils/unicode/is-surrogate-pair.js +14 -0
  366. package/lib/rules/valid-typeof.js +171 -0
  367. package/lib/rules/vars-on-top.js +165 -0
  368. package/lib/rules/wrap-iife.js +238 -0
  369. package/lib/rules/wrap-regex.js +91 -0
  370. package/lib/rules/yield-star-spacing.js +158 -0
  371. package/lib/rules/yoda.js +362 -0
  372. package/lib/services/parser-service.js +64 -0
  373. package/lib/services/processor-service.js +100 -0
  374. package/lib/services/suppressions-service.js +302 -0
  375. package/lib/services/warning-service.js +87 -0
  376. package/lib/shared/ajv.js +34 -0
  377. package/lib/shared/assert.js +21 -0
  378. package/lib/shared/ast-utils.js +30 -0
  379. package/lib/shared/deep-merge-arrays.js +62 -0
  380. package/lib/shared/directives.js +16 -0
  381. package/lib/shared/flags.js +89 -0
  382. package/lib/shared/logging.js +38 -0
  383. package/lib/shared/naming.js +109 -0
  384. package/lib/shared/option-utils.js +63 -0
  385. package/lib/shared/relative-module-resolver.js +28 -0
  386. package/lib/shared/runtime-info.js +177 -0
  387. package/lib/shared/serialization.js +78 -0
  388. package/lib/shared/severity.js +49 -0
  389. package/lib/shared/stats.js +30 -0
  390. package/lib/shared/string-utils.js +58 -0
  391. package/lib/shared/text-table.js +68 -0
  392. package/lib/shared/translate-cli-options.js +223 -0
  393. package/lib/shared/traverser.js +202 -0
  394. package/lib/types/config-api.d.ts +12 -0
  395. package/lib/types/index.d.ts +1482 -0
  396. package/lib/types/rules.d.ts +5603 -0
  397. package/lib/types/universal.d.ts +6 -0
  398. package/lib/types/use-at-your-own-risk.d.ts +34 -0
  399. package/lib/universal.js +10 -0
  400. package/lib/unsupported-api.js +26 -0
  401. package/messages/all-files-ignored.js +16 -0
  402. package/messages/all-matched-files-ignored.js +21 -0
  403. package/messages/config-file-missing.js +16 -0
  404. package/messages/config-plugin-missing.js +14 -0
  405. package/messages/config-serialize-function.js +30 -0
  406. package/messages/eslintrc-incompat.js +117 -0
  407. package/messages/eslintrc-plugins.js +27 -0
  408. package/messages/extend-config-missing.js +13 -0
  409. package/messages/failed-to-read-json.js +11 -0
  410. package/messages/file-not-found.js +10 -0
  411. package/messages/invalid-rule-options.js +17 -0
  412. package/messages/invalid-rule-severity.js +13 -0
  413. package/messages/no-config-found.js +15 -0
  414. package/messages/plugin-conflict.js +22 -0
  415. package/messages/plugin-invalid.js +16 -0
  416. package/messages/plugin-missing.js +19 -0
  417. package/messages/print-config-with-directory-path.js +8 -0
  418. package/messages/shared.js +23 -0
  419. package/messages/whitespace-found.js +11 -0
  420. package/package.json +220 -0
@@ -0,0 +1,1817 @@
1
+ /**
2
+ * @fileoverview Mocha/Jest test wrapper
3
+ * @author Ilya Volodin
4
+ */
5
+ "use strict";
6
+
7
+ /* globals describe, it -- Mocha globals */
8
+
9
+ //------------------------------------------------------------------------------
10
+ // Requirements
11
+ //------------------------------------------------------------------------------
12
+
13
+ const assert = require("node:assert"),
14
+ util = require("node:util"),
15
+ path = require("node:path"),
16
+ equal = require("fast-deep-equal"),
17
+ Traverser = require("../shared/traverser"),
18
+ { Config } = require("../config/config"),
19
+ { Linter, SourceCodeFixer } = require("../linter"),
20
+ { interpolate, getPlaceholderMatcher } = require("../linter/interpolate"),
21
+ stringify = require("json-stable-stringify-without-jsonify"),
22
+ { isSerializable } = require("../shared/serialization");
23
+
24
+ const { FlatConfigArray } = require("../config/flat-config-array");
25
+ const {
26
+ defaultConfig,
27
+ defaultRuleTesterConfig,
28
+ } = require("../config/default-config");
29
+
30
+ const ajv = require("../shared/ajv")({ strictDefaults: true });
31
+
32
+ const parserSymbol = Symbol.for("eslint.RuleTester.parser");
33
+ const { ConfigArraySymbol } = require("@eslint/config-array");
34
+
35
+ const jslang = require("../languages/js");
36
+ const { SourceCode } = require("../languages/js/source-code");
37
+
38
+ //------------------------------------------------------------------------------
39
+ // Typedefs
40
+ //------------------------------------------------------------------------------
41
+
42
+ /** @import { LanguageOptions, RuleDefinition } from "@eslint/core" */
43
+
44
+ /** @typedef {import("../types").Linter.Parser} Parser */
45
+
46
+ /**
47
+ * A test case that is expected to pass lint.
48
+ * @typedef {Object} ValidTestCase
49
+ * @property {string} [name] Name for the test case.
50
+ * @property {string} code Code for the test case.
51
+ * @property {any[]} [options] Options for the test case.
52
+ * @property {Function} [before] Function to execute before testing the case.
53
+ * @property {Function} [after] Function to execute after testing the case regardless of its result.
54
+ * @property {LanguageOptions} [languageOptions] The language options to use in the test case.
55
+ * @property {{ [name: string]: any }} [settings] Settings for the test case.
56
+ * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames.
57
+ * @property {boolean} [only] Run only this test case or the subset of test cases with this property.
58
+ */
59
+
60
+ /**
61
+ * A test case that is expected to fail lint.
62
+ * @typedef {Object} InvalidTestCase
63
+ * @property {string} [name] Name for the test case.
64
+ * @property {string} code Code for the test case.
65
+ * @property {number | Array<TestCaseError | string | RegExp>} errors Expected errors.
66
+ * @property {string | null} [output] The expected code after autofixes are applied. If set to `null`, the test runner will assert that no autofix is suggested.
67
+ * @property {any[]} [options] Options for the test case.
68
+ * @property {Function} [before] Function to execute before testing the case.
69
+ * @property {Function} [after] Function to execute after testing the case regardless of its result.
70
+ * @property {{ [name: string]: any }} [settings] Settings for the test case.
71
+ * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames.
72
+ * @property {LanguageOptions} [languageOptions] The language options to use in the test case.
73
+ * @property {boolean} [only] Run only this test case or the subset of test cases with this property.
74
+ */
75
+
76
+ /**
77
+ * A description of a reported error used in a rule tester test.
78
+ * @typedef {Object} TestCaseError
79
+ * @property {string | RegExp} [message] Message.
80
+ * @property {string} [messageId] Message ID.
81
+ * @property {{ [name: string]: string }} [data] The data used to fill the message template.
82
+ * @property {number} [line] The 1-based line number of the reported start location.
83
+ * @property {number} [column] The 1-based column number of the reported start location.
84
+ * @property {number} [endLine] The 1-based line number of the reported end location.
85
+ * @property {number} [endColumn] The 1-based column number of the reported end location.
86
+ */
87
+
88
+ //------------------------------------------------------------------------------
89
+ // Private Members
90
+ //------------------------------------------------------------------------------
91
+
92
+ /*
93
+ * testerDefaultConfig must not be modified as it allows to reset the tester to
94
+ * the initial default configuration
95
+ */
96
+ const testerDefaultConfig = { rules: {} };
97
+
98
+ /*
99
+ * RuleTester uses this config as its default. This can be overwritten via
100
+ * setDefaultConfig().
101
+ */
102
+ let sharedDefaultConfig = { rules: {} };
103
+
104
+ /*
105
+ * List every parameters possible on a test case that are not related to eslint
106
+ * configuration
107
+ */
108
+ const RuleTesterParameters = [
109
+ "name",
110
+ "code",
111
+ "filename",
112
+ "options",
113
+ "before",
114
+ "after",
115
+ "errors",
116
+ "output",
117
+ "only",
118
+ ];
119
+
120
+ /*
121
+ * All allowed property names in error objects.
122
+ */
123
+ const errorObjectParameters = new Set([
124
+ "message",
125
+ "messageId",
126
+ "data",
127
+ "line",
128
+ "column",
129
+ "endLine",
130
+ "endColumn",
131
+ "suggestions",
132
+ ]);
133
+ const friendlyErrorObjectParameterList = `[${[...errorObjectParameters].map(key => `'${key}'`).join(", ")}]`;
134
+
135
+ /*
136
+ * All allowed property names in suggestion objects.
137
+ */
138
+ const suggestionObjectParameters = new Set([
139
+ "desc",
140
+ "messageId",
141
+ "data",
142
+ "output",
143
+ ]);
144
+ const friendlySuggestionObjectParameterList = `[${[...suggestionObjectParameters].map(key => `'${key}'`).join(", ")}]`;
145
+
146
+ const forbiddenMethods = [
147
+ "applyInlineConfig",
148
+ "applyLanguageOptions",
149
+ "finalize",
150
+ ];
151
+
152
+ /** @type {Map<string,WeakSet>} */
153
+ const forbiddenMethodCalls = new Map(
154
+ forbiddenMethods.map(methodName => [methodName, new WeakSet()]),
155
+ );
156
+
157
+ const hasOwnProperty = Function.call.bind(Object.hasOwnProperty);
158
+
159
+ /**
160
+ * Clones a given value deeply.
161
+ * Note: This ignores `parent` property.
162
+ * @param {any} x A value to clone.
163
+ * @returns {any} A cloned value.
164
+ */
165
+ function cloneDeeplyExcludesParent(x) {
166
+ if (typeof x === "object" && x !== null) {
167
+ if (Array.isArray(x)) {
168
+ return x.map(cloneDeeplyExcludesParent);
169
+ }
170
+
171
+ const retv = {};
172
+
173
+ for (const key in x) {
174
+ if (key !== "parent" && hasOwnProperty(x, key)) {
175
+ retv[key] = cloneDeeplyExcludesParent(x[key]);
176
+ }
177
+ }
178
+
179
+ return retv;
180
+ }
181
+
182
+ return x;
183
+ }
184
+
185
+ /**
186
+ * Freezes a given value deeply.
187
+ * @param {any} x A value to freeze.
188
+ * @param {Set<Object>} seenObjects Objects already seen during the traversal.
189
+ * @returns {void}
190
+ */
191
+ function freezeDeeply(x, seenObjects = new Set()) {
192
+ if (typeof x === "object" && x !== null) {
193
+ if (seenObjects.has(x)) {
194
+ return; // skip to avoid infinite recursion
195
+ }
196
+ seenObjects.add(x);
197
+
198
+ if (Array.isArray(x)) {
199
+ x.forEach(element => {
200
+ freezeDeeply(element, seenObjects);
201
+ });
202
+ } else {
203
+ for (const key in x) {
204
+ if (key !== "parent" && hasOwnProperty(x, key)) {
205
+ freezeDeeply(x[key], seenObjects);
206
+ }
207
+ }
208
+ }
209
+ Object.freeze(x);
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Replace control characters by `\u00xx` form.
215
+ * @param {string} text The text to sanitize.
216
+ * @returns {string} The sanitized text.
217
+ */
218
+ function sanitize(text) {
219
+ if (typeof text !== "string") {
220
+ return "";
221
+ }
222
+ return text.replace(
223
+ /[\u0000-\u0009\u000b-\u001a]/gu, // eslint-disable-line no-control-regex -- Escaping controls
224
+ c => `\\u${c.codePointAt(0).toString(16).padStart(4, "0")}`,
225
+ );
226
+ }
227
+
228
+ /**
229
+ * Define `start`/`end` properties as throwing error.
230
+ * @param {string} objName Object name used for error messages.
231
+ * @param {ASTNode} node The node to define.
232
+ * @returns {void}
233
+ */
234
+ function defineStartEndAsError(objName, node) {
235
+ Object.defineProperties(node, {
236
+ start: {
237
+ get() {
238
+ throw new Error(
239
+ `Use ${objName}.range[0] instead of ${objName}.start`,
240
+ );
241
+ },
242
+ configurable: true,
243
+ enumerable: false,
244
+ },
245
+ end: {
246
+ get() {
247
+ throw new Error(
248
+ `Use ${objName}.range[1] instead of ${objName}.end`,
249
+ );
250
+ },
251
+ configurable: true,
252
+ enumerable: false,
253
+ },
254
+ });
255
+ }
256
+
257
+ /**
258
+ * Define `start`/`end` properties of all nodes of the given AST as throwing error.
259
+ * @param {ASTNode} ast The root node to errorize `start`/`end` properties.
260
+ * @param {Object} [visitorKeys] Visitor keys to be used for traversing the given ast.
261
+ * @returns {void}
262
+ */
263
+ function defineStartEndAsErrorInTree(ast, visitorKeys) {
264
+ Traverser.traverse(ast, {
265
+ visitorKeys,
266
+ enter: defineStartEndAsError.bind(null, "node"),
267
+ });
268
+ ast.tokens.forEach(defineStartEndAsError.bind(null, "token"));
269
+ ast.comments.forEach(defineStartEndAsError.bind(null, "token"));
270
+ }
271
+
272
+ /**
273
+ * Wraps the given parser in order to intercept and modify return values from the `parse` and `parseForESLint` methods, for test purposes.
274
+ * In particular, to modify ast nodes, tokens and comments to throw on access to their `start` and `end` properties.
275
+ * @param {Parser} parser Parser object.
276
+ * @returns {Parser} Wrapped parser object.
277
+ */
278
+ function wrapParser(parser) {
279
+ if (typeof parser.parseForESLint === "function") {
280
+ return {
281
+ [parserSymbol]: parser,
282
+ parseForESLint(...args) {
283
+ const ret = parser.parseForESLint(...args);
284
+
285
+ defineStartEndAsErrorInTree(ret.ast, ret.visitorKeys);
286
+ return ret;
287
+ },
288
+ };
289
+ }
290
+
291
+ return {
292
+ [parserSymbol]: parser,
293
+ parse(...args) {
294
+ const ast = parser.parse(...args);
295
+
296
+ defineStartEndAsErrorInTree(ast);
297
+ return ast;
298
+ },
299
+ };
300
+ }
301
+
302
+ /**
303
+ * Function to replace forbidden `SourceCode` methods. Allows just one call per method.
304
+ * @param {string} methodName The name of the method to forbid.
305
+ * @param {Function} prototype The prototype with the original method to call.
306
+ * @returns {Function} The function that throws the error.
307
+ */
308
+ function throwForbiddenMethodError(methodName, prototype) {
309
+ const original = prototype[methodName];
310
+
311
+ return function (...args) {
312
+ const called = forbiddenMethodCalls.get(methodName);
313
+
314
+ /* eslint-disable no-invalid-this -- needed to operate as a method. */
315
+ if (!called.has(this)) {
316
+ called.add(this);
317
+
318
+ return original.apply(this, args);
319
+ }
320
+ /* eslint-enable no-invalid-this -- not needed past this point */
321
+
322
+ throw new Error(
323
+ `\`SourceCode#${methodName}()\` cannot be called inside a rule.`,
324
+ );
325
+ };
326
+ }
327
+
328
+ /**
329
+ * Extracts names of {{ placeholders }} from the reported message.
330
+ * @param {string} message Reported message
331
+ * @returns {string[]} Array of placeholder names
332
+ */
333
+ function getMessagePlaceholders(message) {
334
+ const matcher = getPlaceholderMatcher();
335
+
336
+ return Array.from(message.matchAll(matcher), ([, name]) => name.trim());
337
+ }
338
+
339
+ /**
340
+ * Returns the placeholders in the reported messages but
341
+ * only includes the placeholders available in the raw message and not in the provided data.
342
+ * @param {string} message The reported message
343
+ * @param {string} raw The raw message specified in the rule meta.messages
344
+ * @param {undefined|Record<unknown, unknown>} data The passed
345
+ * @returns {string[]} Missing placeholder names
346
+ */
347
+ function getUnsubstitutedMessagePlaceholders(message, raw, data = {}) {
348
+ const unsubstituted = getMessagePlaceholders(message);
349
+
350
+ if (unsubstituted.length === 0) {
351
+ return [];
352
+ }
353
+
354
+ // Remove false positives by only counting placeholders in the raw message, which were not provided in the data matcher or added with a data property
355
+ const known = getMessagePlaceholders(raw);
356
+ const provided = Object.keys(data);
357
+
358
+ return unsubstituted.filter(
359
+ name => known.includes(name) && !provided.includes(name),
360
+ );
361
+ }
362
+
363
+ const metaSchemaDescription = `
364
+ \t- If the rule has options, set \`meta.schema\` to an array or non-empty object to enable options validation.
365
+ \t- If the rule doesn't have options, omit \`meta.schema\` to enforce that no options can be passed to the rule.
366
+ \t- You can also set \`meta.schema\` to \`false\` to opt-out of options validation (not recommended).
367
+
368
+ \thttps://eslint.org/docs/latest/extend/custom-rules#options-schemas
369
+ `;
370
+
371
+ /*
372
+ * Ignored test case properties when checking for test case duplicates.
373
+ */
374
+ const duplicationIgnoredParameters = new Set(["name", "errors", "output"]);
375
+
376
+ /**
377
+ * Normalizes a test case item, ensuring it is an object with a 'code' property.
378
+ * If the item is not an object, it returns an object with the 'code' property set to the item.
379
+ * @param {any} item The test case item to normalize.
380
+ * @returns {Object} The normalized test case object.
381
+ */
382
+ function normalizeTestCase(item) {
383
+ return item && typeof item === "object" ? item : { code: item };
384
+ }
385
+
386
+ /**
387
+ * Asserts that the `errors` property of an invalid test case is valid.
388
+ * @param {number | string[]} errors The `errors` property of the invalid test case.
389
+ * @param {string} ruleName The name of the rule being tested.
390
+ * @param {Object} [assertionOptions] The assertion options for the test case.
391
+ * @returns {void}
392
+ */
393
+ function assertErrorsProperty(errors, ruleName, assertionOptions = {}) {
394
+ const isNumber = typeof errors === "number";
395
+ const isArray = Array.isArray(errors);
396
+
397
+ if (!isNumber && !isArray) {
398
+ if (errors === void 0) {
399
+ assert.fail(
400
+ `Did not specify errors for an invalid test of ${ruleName}`,
401
+ );
402
+ } else {
403
+ assert.fail(
404
+ `Invalid 'errors' property for invalid test of ${ruleName}: expected a number or an array but got ${
405
+ errors === null ? "null" : typeof errors
406
+ }`,
407
+ );
408
+ }
409
+ }
410
+
411
+ const { requireMessage = false, requireLocation = false } =
412
+ assertionOptions;
413
+
414
+ if (isArray) {
415
+ assert.ok(
416
+ errors.length !== 0,
417
+ "Invalid cases must have at least one error",
418
+ );
419
+
420
+ for (const [number, error] of errors.entries()) {
421
+ if (typeof error === "string" || error instanceof RegExp) {
422
+ // Just an error message.
423
+ assert.ok(
424
+ requireMessage !== "messageId" && !requireLocation,
425
+ `errors[${number}] should be an object when 'assertionOptions.requireMessage' is 'messageId' or 'assertionOptions.requireLocation' is true.`,
426
+ );
427
+ } else if (typeof error === "object" && error !== null) {
428
+ /*
429
+ * Error object.
430
+ * This may have a message, messageId, data, line, and/or column.
431
+ */
432
+
433
+ for (const propertyName of Object.keys(error)) {
434
+ assert.ok(
435
+ errorObjectParameters.has(propertyName),
436
+ `Invalid error property name '${propertyName}'. Expected one of ${friendlyErrorObjectParameterList}.`,
437
+ );
438
+ }
439
+
440
+ if (requireMessage === "message") {
441
+ assert.ok(
442
+ !hasOwnProperty(error, "messageId") &&
443
+ hasOwnProperty(error, "message"),
444
+ `errors[${number}] should specify 'message' (and not 'messageId') when 'assertionOptions.requireMessage' is 'message'.`,
445
+ );
446
+ } else if (requireMessage === "messageId") {
447
+ assert.ok(
448
+ !hasOwnProperty(error, "message") &&
449
+ hasOwnProperty(error, "messageId"),
450
+ `errors[${number}] should specify 'messageId' (and not 'message') when 'assertionOptions.requireMessage' is 'messageId'.`,
451
+ );
452
+ }
453
+
454
+ if (hasOwnProperty(error, "message")) {
455
+ assert.ok(
456
+ !hasOwnProperty(error, "messageId"),
457
+ `errors[${number}] should not specify both 'message' and 'messageId'.`,
458
+ );
459
+ assert.ok(
460
+ !hasOwnProperty(error, "data"),
461
+ `errors[${number}] should not specify both 'data' and 'message'.`,
462
+ );
463
+ } else {
464
+ assert.ok(
465
+ hasOwnProperty(error, "messageId"),
466
+ `errors[${number}] must specify either 'messageId' or 'message'.`,
467
+ );
468
+ }
469
+ } else {
470
+ assert.fail(
471
+ `errors[${number}] must be a string, RegExp, or an object.`,
472
+ );
473
+ }
474
+ }
475
+ } else {
476
+ assert.ok(
477
+ !requireMessage && !requireLocation,
478
+ "Invalid cases must have 'errors' value as an array",
479
+ );
480
+ assert.ok(
481
+ errors > 0,
482
+ "Invalid cases must have 'error' value greater than 0",
483
+ );
484
+ }
485
+ }
486
+
487
+ /**
488
+ * Check if this test case is a duplicate of one we have seen before.
489
+ * @param {Object} item test case object
490
+ * @param {Set<string>} seenTestCases set of serialized test cases we have seen so far (managed by this function)
491
+ * @returns {void}
492
+ */
493
+ function checkDuplicateTestCase(item, seenTestCases) {
494
+ if (!isSerializable(item)) {
495
+ /*
496
+ * If we can't serialize a test case (because it contains a function, RegExp, etc), skip the check.
497
+ * This might happen with properties like: options, plugins, settings, languageOptions.parser, languageOptions.parserOptions.
498
+ */
499
+ return;
500
+ }
501
+
502
+ const serializedTestCase = stringify(item, {
503
+ replacer(key, value) {
504
+ // "this" is the currently stringified object --> only ignore top-level properties
505
+ return item !== this || !duplicationIgnoredParameters.has(key)
506
+ ? value
507
+ : void 0;
508
+ },
509
+ });
510
+
511
+ assert(
512
+ !seenTestCases.has(serializedTestCase),
513
+ "detected duplicate test case",
514
+ );
515
+ seenTestCases.add(serializedTestCase);
516
+ }
517
+
518
+ /**
519
+ * Asserts that a rule is valid.
520
+ * A valid rule must be an object with a `create` method.
521
+ * @param {Object} rule The rule to check.
522
+ * @param {string} ruleName The name of the rule.
523
+ * @returns {void}
524
+ * @throws {AssertionError} If the rule is not valid.
525
+ */
526
+ function assertRule(rule, ruleName) {
527
+ assert.ok(
528
+ rule && typeof rule === "object" && typeof rule.create === "function",
529
+ `Rule ${ruleName} must be an object with a \`create\` method`,
530
+ );
531
+ }
532
+
533
+ /**
534
+ * Asserts that a test scenario object is valid.
535
+ * A valid test scenario object must have `valid` and `invalid` properties, both of
536
+ * which must be arrays.
537
+ * @param {Object} test The test scenario object to check.
538
+ * @param {string} ruleName The name of the rule being tested.
539
+ * @returns {void}
540
+ * @throws {AssertionError} If the test scenario object is not valid.
541
+ */
542
+ function assertTest(test, ruleName) {
543
+ assert.ok(
544
+ test && typeof test === "object",
545
+ `Test Scenarios for rule ${ruleName} : Could not find test scenario object`,
546
+ );
547
+
548
+ const hasValid = Array.isArray(test.valid);
549
+ const hasInvalid = Array.isArray(test.invalid);
550
+
551
+ assert.ok(
552
+ hasValid,
553
+ `Test Scenarios for rule ${ruleName} is invalid: Could not find any valid test scenarios`,
554
+ );
555
+
556
+ assert.ok(
557
+ hasInvalid,
558
+ `Test Scenarios for rule ${ruleName} is invalid: Could not find any invalid test scenarios`,
559
+ );
560
+ }
561
+
562
+ /**
563
+ * Asserts that the common properties of a valid/invalid test case have the correct types.
564
+ * @param {Object} item The test case object to check.
565
+ * @returns {void}
566
+ */
567
+ function assertTestCommonProperties(item) {
568
+ assert.ok(
569
+ typeof item.code === "string",
570
+ "Test case must specify a string value for 'code'",
571
+ );
572
+
573
+ // optional properties
574
+ if (item.name) {
575
+ assert.ok(
576
+ typeof item.name === "string",
577
+ "Optional test case property 'name' must be a string",
578
+ );
579
+ }
580
+ if (hasOwnProperty(item, "only")) {
581
+ assert.ok(
582
+ typeof item.only === "boolean",
583
+ "Optional test case property 'only' must be a boolean",
584
+ );
585
+ }
586
+ if (hasOwnProperty(item, "filename")) {
587
+ assert.ok(
588
+ typeof item.filename === "string",
589
+ "Optional test case property 'filename' must be a string",
590
+ );
591
+ }
592
+ if (hasOwnProperty(item, "options")) {
593
+ assert.ok(
594
+ Array.isArray(item.options),
595
+ "Optional test case property 'options' must be an array",
596
+ );
597
+ }
598
+ }
599
+
600
+ /**
601
+ * Asserts that a valid test case object is valid.
602
+ * A valid test case must specify a string value for 'code'.
603
+ * Optional properties are checked for correct types.
604
+ * @param {Object} item The valid test case object to check.
605
+ * @param {Set<string>} seenTestCases Set of serialized test cases to check for duplicates.
606
+ * @returns {void}
607
+ * @throws {AssertionError} If the test case is not valid.
608
+ */
609
+ function assertValidTestCase(item, seenTestCases) {
610
+ // must not have properties of invalid test cases
611
+ assert.ok(
612
+ item.errors === void 0,
613
+ "Valid test case must not have 'errors' property",
614
+ );
615
+ assert.ok(
616
+ item.output === void 0,
617
+ "Valid test case must not have 'output' property",
618
+ );
619
+
620
+ assertTestCommonProperties(item);
621
+ checkDuplicateTestCase(item, seenTestCases);
622
+ }
623
+
624
+ /**
625
+ * Asserts that the invalid test case object is valid.
626
+ * An invalid test case must specify a string value for 'code' and must have 'errors' property.
627
+ * Optional properties are checked for correct types.
628
+ * @param {Object} item The invalid test case object to check.
629
+ * @param {Set<string>} seenTestCases Set of serialized test cases to check for duplicates.
630
+ * @param {string} ruleName The name of the rule being tested.
631
+ * @param {Object} [assertionOptions] The assertion options for the test case.
632
+ * @returns {void}
633
+ * @throws {AssertionError} If the test case is not valid.
634
+ */
635
+ function assertInvalidTestCase(
636
+ item,
637
+ seenTestCases,
638
+ ruleName,
639
+ assertionOptions = {},
640
+ ) {
641
+ assertTestCommonProperties(item);
642
+
643
+ assertErrorsProperty(item.errors, ruleName, assertionOptions);
644
+
645
+ // 'output' is optional, but if it exists it must be a string or null
646
+ if (hasOwnProperty(item, "output")) {
647
+ assert.ok(
648
+ item.output === null || typeof item.output === "string",
649
+ "Test property 'output', if specified, must be a string or null. If no autofix is expected, then omit the 'output' property or set it to null.",
650
+ );
651
+ }
652
+
653
+ checkDuplicateTestCase(item, seenTestCases);
654
+ }
655
+
656
+ /**
657
+ * Gets the invocation location from the stack trace for later use.
658
+ * @param {Function} relative The function before the invocation point.
659
+ * @returns {string} The invocation location.
660
+ */
661
+ function getInvocationLocation(relative = getInvocationLocation) {
662
+ const dummyObject = {};
663
+ Error.captureStackTrace(dummyObject, relative);
664
+ const { stack } = dummyObject;
665
+
666
+ return stack.split("\n")[1].replace(/.*?\(/u, "").replace(/\)$/u, "");
667
+ }
668
+
669
+ //------------------------------------------------------------------------------
670
+ // Public Interface
671
+ //------------------------------------------------------------------------------
672
+
673
+ // default separators for testing
674
+ const DESCRIBE = Symbol("describe");
675
+ const IT = Symbol("it");
676
+ const IT_ONLY = Symbol("itOnly");
677
+
678
+ /**
679
+ * This is `it` default handler if `it` don't exist.
680
+ * @this {Mocha}
681
+ * @param {string} text The description of the test case.
682
+ * @param {Function} method The logic of the test case.
683
+ * @throws {Error} Any error upon execution of `method`.
684
+ * @returns {any} Returned value of `method`.
685
+ */
686
+ function itDefaultHandler(text, method) {
687
+ try {
688
+ return method.call(this);
689
+ } catch (err) {
690
+ if (err instanceof assert.AssertionError) {
691
+ err.message += ` (${util.inspect(err.actual)} ${err.operator} ${util.inspect(err.expected)})`;
692
+ }
693
+ throw err;
694
+ }
695
+ }
696
+
697
+ /**
698
+ * This is `describe` default handler if `describe` don't exist.
699
+ * @this {Mocha}
700
+ * @param {string} text The description of the test case.
701
+ * @param {Function} method The logic of the test case.
702
+ * @returns {any} Returned value of `method`.
703
+ */
704
+ function describeDefaultHandler(text, method) {
705
+ return method.call(this);
706
+ }
707
+
708
+ /**
709
+ * Mocha test wrapper.
710
+ */
711
+ class RuleTester {
712
+ /**
713
+ * Creates a new instance of RuleTester.
714
+ * @param {Object} [testerConfig] Optional, extra configuration for the tester
715
+ */
716
+ constructor(testerConfig = {}) {
717
+ /**
718
+ * The configuration to use for this tester. Combination of the tester
719
+ * configuration and the default configuration.
720
+ * @type {Object}
721
+ */
722
+ this.testerConfig = [
723
+ sharedDefaultConfig,
724
+ testerConfig,
725
+ { rules: { "rule-tester/validate-ast": "error" } },
726
+ ];
727
+
728
+ this.linter = new Linter({ configType: "flat" });
729
+ }
730
+
731
+ /**
732
+ * Set the configuration to use for all future tests
733
+ * @param {Object} config the configuration to use.
734
+ * @throws {TypeError} If non-object config.
735
+ * @returns {void}
736
+ */
737
+ static setDefaultConfig(config) {
738
+ if (typeof config !== "object" || config === null) {
739
+ throw new TypeError(
740
+ "RuleTester.setDefaultConfig: config must be an object",
741
+ );
742
+ }
743
+ sharedDefaultConfig = config;
744
+
745
+ // Make sure the rules object exists since it is assumed to exist later
746
+ sharedDefaultConfig.rules = sharedDefaultConfig.rules || {};
747
+ }
748
+
749
+ /**
750
+ * Get the current configuration used for all tests
751
+ * @returns {Object} the current configuration
752
+ */
753
+ static getDefaultConfig() {
754
+ return sharedDefaultConfig;
755
+ }
756
+
757
+ /**
758
+ * Reset the configuration to the initial configuration of the tester removing
759
+ * any changes made until now.
760
+ * @returns {void}
761
+ */
762
+ static resetDefaultConfig() {
763
+ sharedDefaultConfig = {
764
+ rules: {
765
+ ...testerDefaultConfig.rules,
766
+ },
767
+ };
768
+ }
769
+
770
+ /*
771
+ * If people use `mocha test.js --watch` command, `describe` and `it` function
772
+ * instances are different for each execution. So `describe` and `it` should get fresh instance
773
+ * always.
774
+ */
775
+ static get describe() {
776
+ return (
777
+ this[DESCRIBE] ||
778
+ (typeof describe === "function" ? describe : describeDefaultHandler)
779
+ );
780
+ }
781
+
782
+ static set describe(value) {
783
+ this[DESCRIBE] = value;
784
+ }
785
+
786
+ static get it() {
787
+ return this[IT] || (typeof it === "function" ? it : itDefaultHandler);
788
+ }
789
+
790
+ static set it(value) {
791
+ this[IT] = value;
792
+ }
793
+
794
+ /**
795
+ * Adds the `only` property to a test to run it in isolation.
796
+ * @param {string | ValidTestCase | InvalidTestCase} item A single test to run by itself.
797
+ * @returns {ValidTestCase | InvalidTestCase} The test with `only` set.
798
+ */
799
+ static only(item) {
800
+ if (typeof item === "string") {
801
+ return { code: item, only: true };
802
+ }
803
+
804
+ return { ...item, only: true };
805
+ }
806
+
807
+ static get itOnly() {
808
+ if (typeof this[IT_ONLY] === "function") {
809
+ return this[IT_ONLY];
810
+ }
811
+ if (
812
+ typeof this[IT] === "function" &&
813
+ typeof this[IT].only === "function"
814
+ ) {
815
+ return Function.bind.call(this[IT].only, this[IT]);
816
+ }
817
+ if (typeof it === "function" && typeof it.only === "function") {
818
+ return Function.bind.call(it.only, it);
819
+ }
820
+
821
+ if (
822
+ typeof this[DESCRIBE] === "function" ||
823
+ typeof this[IT] === "function"
824
+ ) {
825
+ throw new Error(
826
+ "Set `RuleTester.itOnly` to use `only` with a custom test framework.\n" +
827
+ "See https://eslint.org/docs/latest/integrate/nodejs-api#customizing-ruletester for more.",
828
+ );
829
+ }
830
+ if (typeof it === "function") {
831
+ throw new Error(
832
+ "The current test framework does not support exclusive tests with `only`.",
833
+ );
834
+ }
835
+ throw new Error(
836
+ "To use `only`, use RuleTester with a test framework that provides `it.only()` like Mocha.",
837
+ );
838
+ }
839
+
840
+ static set itOnly(value) {
841
+ this[IT_ONLY] = value;
842
+ }
843
+
844
+ /**
845
+ * Adds a new rule test to execute.
846
+ * @param {string} ruleName The name of the rule to run.
847
+ * @param {RuleDefinition} rule The rule to test.
848
+ * @param {{
849
+ * assertionOptions?: {
850
+ * requireMessage?: boolean | "message" | "messageId",
851
+ * requireLocation?: boolean
852
+ * requireData?: boolean | "error" | "suggestion"
853
+ * },
854
+ * valid: (ValidTestCase | string)[],
855
+ * invalid: InvalidTestCase[]
856
+ * }} test The collection of tests to run.
857
+ * @throws {TypeError|Error} If `rule` is not an object with a `create` method,
858
+ * or if non-object `test`, or if a required scenario of the given type is missing.
859
+ * @returns {void}
860
+ */
861
+ run(ruleName, rule, test) {
862
+ const testerConfig = this.testerConfig,
863
+ linter = this.linter,
864
+ ruleId = `rule-to-test/${ruleName}`;
865
+
866
+ assertRule(rule, ruleName);
867
+ assertTest(test, ruleName);
868
+
869
+ const invocationLocation = getInvocationLocation(this.run);
870
+
871
+ const baseConfig = [
872
+ {
873
+ plugins: {
874
+ // copy root plugin over
875
+ "@": {
876
+ /*
877
+ * Parsers are wrapped to detect more errors, so this needs
878
+ * to be a new object for each call to run(), otherwise the
879
+ * parsers will be wrapped multiple times.
880
+ */
881
+ parsers: {
882
+ ...defaultConfig[0].plugins["@"].parsers,
883
+ },
884
+
885
+ /*
886
+ * The rules key on the default plugin is a proxy to lazy-load
887
+ * just the rules that are needed. So, don't create a new object
888
+ * here, just use the default one to keep that performance
889
+ * enhancement.
890
+ */
891
+ rules: defaultConfig[0].plugins["@"].rules,
892
+ languages: defaultConfig[0].plugins["@"].languages,
893
+ },
894
+ "rule-to-test": {
895
+ rules: {
896
+ [ruleName]: Object.assign({}, rule, {
897
+ // Create a wrapper rule that freezes the `context` properties.
898
+ create(context) {
899
+ freezeDeeply(context.options);
900
+ freezeDeeply(context.settings);
901
+ freezeDeeply(context.parserOptions);
902
+
903
+ // freezeDeeply(context.languageOptions);
904
+
905
+ return rule.create(context);
906
+ },
907
+ }),
908
+ },
909
+ },
910
+ },
911
+ language: defaultConfig[0].language,
912
+ },
913
+ ...defaultRuleTesterConfig,
914
+ ];
915
+
916
+ /**
917
+ * Runs a hook on the given item when it's assigned to the given property
918
+ * @param {Object} item Item to run the hook on
919
+ * @param {string} prop The property having the hook assigned to
920
+ * @throws {Error} If the property is not a function or that function throws an error
921
+ * @returns {void}
922
+ * @private
923
+ */
924
+ function runHook(item, prop) {
925
+ if (hasOwnProperty(item, prop)) {
926
+ assert.strictEqual(
927
+ typeof item[prop],
928
+ "function",
929
+ `Optional test case property '${prop}' must be a function`,
930
+ );
931
+ item[prop]();
932
+ }
933
+ }
934
+ /**
935
+ * Run the rule for the given item
936
+ * @param {Object} item Item to run the rule against
937
+ * @throws {Error} If an invalid schema.
938
+ * @returns {Object} Eslint run result
939
+ * @private
940
+ */
941
+ function runRuleForItem(item) {
942
+ const code = item.code;
943
+ const filename = hasOwnProperty(item, "filename")
944
+ ? item.filename
945
+ : void 0;
946
+ const options = hasOwnProperty(item, "options") ? item.options : [];
947
+ const flatConfigArrayOptions = {
948
+ baseConfig,
949
+ };
950
+
951
+ if (filename) {
952
+ flatConfigArrayOptions.basePath =
953
+ path.parse(filename).root || void 0;
954
+ }
955
+
956
+ const configs = new FlatConfigArray(
957
+ testerConfig,
958
+ flatConfigArrayOptions,
959
+ );
960
+
961
+ /*
962
+ * Modify the returned config so that the parser is wrapped to catch
963
+ * access of the start/end properties. This method is called just
964
+ * once per code snippet being tested, so each test case gets a clean
965
+ * parser.
966
+ */
967
+ configs[ConfigArraySymbol.finalizeConfig] = function (...args) {
968
+ // can't do super here :(
969
+ const proto = Object.getPrototypeOf(this);
970
+ const calculatedConfig = proto[
971
+ ConfigArraySymbol.finalizeConfig
972
+ ].apply(this, args);
973
+
974
+ // wrap the parser to catch start/end property access
975
+ if (calculatedConfig.language === jslang) {
976
+ calculatedConfig.languageOptions.parser = wrapParser(
977
+ calculatedConfig.languageOptions.parser,
978
+ );
979
+ }
980
+
981
+ return calculatedConfig;
982
+ };
983
+
984
+ let output, beforeAST, afterAST;
985
+
986
+ /*
987
+ * Assumes everything on the item is a config except for the
988
+ * parameters used by this tester
989
+ */
990
+ const itemConfig = { ...item };
991
+
992
+ for (const parameter of RuleTesterParameters) {
993
+ delete itemConfig[parameter];
994
+ }
995
+
996
+ /*
997
+ * Create the config object from the tester config and this item
998
+ * specific configurations.
999
+ */
1000
+ configs.push(itemConfig);
1001
+
1002
+ configs.push({
1003
+ rules: {
1004
+ [ruleId]: [1, ...options],
1005
+ },
1006
+ });
1007
+
1008
+ let schema;
1009
+
1010
+ try {
1011
+ schema = Config.getRuleOptionsSchema(rule);
1012
+ } catch (err) {
1013
+ err.message += metaSchemaDescription;
1014
+ throw err;
1015
+ }
1016
+
1017
+ /*
1018
+ * Check and throw an error if the schema is an empty object (`schema:{}`), because such schema
1019
+ * doesn't validate or enforce anything and is therefore considered a possible error. If the intent
1020
+ * was to skip options validation, `schema:false` should be set instead (explicit opt-out).
1021
+ *
1022
+ * For this purpose, a schema object is considered empty if it doesn't have any own enumerable string-keyed
1023
+ * properties. While `ajv.compile()` does use enumerable properties from the prototype chain as well,
1024
+ * it caches compiled schemas by serializing only own enumerable properties, so it's generally not a good idea
1025
+ * to use inherited properties in schemas because schemas that differ only in inherited properties would end up
1026
+ * having the same cache entry that would be correct for only one of them.
1027
+ *
1028
+ * At this point, `schema` can only be an object or `null`.
1029
+ */
1030
+ if (schema && Object.keys(schema).length === 0) {
1031
+ throw new Error(
1032
+ `\`schema: {}\` is a no-op${metaSchemaDescription}`,
1033
+ );
1034
+ }
1035
+
1036
+ /*
1037
+ * Setup AST getters.
1038
+ * The goal is to check whether or not AST was modified when
1039
+ * running the rule under test.
1040
+ */
1041
+ configs.push({
1042
+ plugins: {
1043
+ "rule-tester": {
1044
+ rules: {
1045
+ "validate-ast": {
1046
+ create() {
1047
+ return {
1048
+ Program(node) {
1049
+ beforeAST =
1050
+ cloneDeeplyExcludesParent(node);
1051
+ },
1052
+ "Program:exit"(node) {
1053
+ afterAST = node;
1054
+ },
1055
+ };
1056
+ },
1057
+ },
1058
+ },
1059
+ },
1060
+ },
1061
+ });
1062
+
1063
+ if (schema) {
1064
+ ajv.validateSchema(schema);
1065
+
1066
+ if (ajv.errors) {
1067
+ const errors = ajv.errors
1068
+ .map(error => {
1069
+ const field =
1070
+ error.dataPath[0] === "."
1071
+ ? error.dataPath.slice(1)
1072
+ : error.dataPath;
1073
+
1074
+ return `\t${field}: ${error.message}`;
1075
+ })
1076
+ .join("\n");
1077
+
1078
+ throw new Error([
1079
+ `Schema for rule ${ruleName} is invalid:`,
1080
+ errors,
1081
+ ]);
1082
+ }
1083
+
1084
+ /*
1085
+ * `ajv.validateSchema` checks for errors in the structure of the schema (by comparing the schema against a "meta-schema"),
1086
+ * and it reports those errors individually. However, there are other types of schema errors that only occur when compiling
1087
+ * the schema (e.g. using invalid defaults in a schema), and only one of these errors can be reported at a time. As a result,
1088
+ * the schema is compiled here separately from checking for `validateSchema` errors.
1089
+ */
1090
+ try {
1091
+ ajv.compile(schema);
1092
+ } catch (err) {
1093
+ throw new Error(
1094
+ `Schema for rule ${ruleName} is invalid: ${err.message}`,
1095
+ {
1096
+ cause: err,
1097
+ },
1098
+ );
1099
+ }
1100
+ }
1101
+
1102
+ // check for validation errors
1103
+ try {
1104
+ configs.normalizeSync();
1105
+ configs.getConfig("test.js");
1106
+ } catch (error) {
1107
+ error.message = `ESLint configuration in rule-tester is invalid: ${error.message}`;
1108
+ throw error;
1109
+ }
1110
+
1111
+ // Verify the code.
1112
+ const { applyLanguageOptions, applyInlineConfig, finalize } =
1113
+ SourceCode.prototype;
1114
+ let messages;
1115
+
1116
+ try {
1117
+ forbiddenMethods.forEach(methodName => {
1118
+ SourceCode.prototype[methodName] =
1119
+ throwForbiddenMethodError(
1120
+ methodName,
1121
+ SourceCode.prototype,
1122
+ );
1123
+ });
1124
+
1125
+ messages = linter.verify(code, configs, filename);
1126
+ } finally {
1127
+ SourceCode.prototype.applyInlineConfig = applyInlineConfig;
1128
+ SourceCode.prototype.applyLanguageOptions =
1129
+ applyLanguageOptions;
1130
+ SourceCode.prototype.finalize = finalize;
1131
+ }
1132
+
1133
+ const fatalErrorMessage = messages.find(m => m.fatal);
1134
+
1135
+ assert(
1136
+ !fatalErrorMessage,
1137
+ `A fatal parsing error occurred: ${fatalErrorMessage && fatalErrorMessage.message}`,
1138
+ );
1139
+
1140
+ // Verify if autofix makes a syntax error or not.
1141
+ if (messages.some(m => m.fix)) {
1142
+ output = SourceCodeFixer.applyFixes(code, messages).output;
1143
+ const errorMessageInFix = linter
1144
+ .verify(output, configs, filename)
1145
+ .find(m => m.fatal);
1146
+
1147
+ assert(
1148
+ !errorMessageInFix,
1149
+ [
1150
+ "A fatal parsing error occurred in autofix.",
1151
+ `Error: ${errorMessageInFix && errorMessageInFix.message}`,
1152
+ "Autofix output:",
1153
+ output,
1154
+ ].join("\n"),
1155
+ );
1156
+ } else {
1157
+ output = code;
1158
+ }
1159
+
1160
+ return {
1161
+ messages,
1162
+ output,
1163
+ beforeAST,
1164
+ afterAST: cloneDeeplyExcludesParent(afterAST),
1165
+ configs,
1166
+ filename,
1167
+ };
1168
+ }
1169
+
1170
+ /**
1171
+ * Check if the AST was changed
1172
+ * @param {ASTNode} beforeAST AST node before running
1173
+ * @param {ASTNode} afterAST AST node after running
1174
+ * @returns {void}
1175
+ * @private
1176
+ */
1177
+ function assertASTDidntChange(beforeAST, afterAST) {
1178
+ if (!equal(beforeAST, afterAST)) {
1179
+ assert.fail("Rule should not modify AST.");
1180
+ }
1181
+ }
1182
+
1183
+ /**
1184
+ * Check if the template is valid or not
1185
+ * all valid cases go through this
1186
+ * @param {Object} item Item to run the rule against
1187
+ * @returns {void}
1188
+ * @private
1189
+ */
1190
+ function testValidTemplate(item) {
1191
+ const result = runRuleForItem(item);
1192
+ const messages = result.messages;
1193
+
1194
+ assert.strictEqual(
1195
+ messages.length,
1196
+ 0,
1197
+ util.format(
1198
+ "Should have no errors but had %d: %s",
1199
+ messages.length,
1200
+ util.inspect(messages),
1201
+ ),
1202
+ );
1203
+
1204
+ assertASTDidntChange(result.beforeAST, result.afterAST);
1205
+ }
1206
+
1207
+ /**
1208
+ * Asserts that the message matches its expected value. If the expected
1209
+ * value is a regular expression, it is checked against the actual
1210
+ * value.
1211
+ * @param {string} actual Actual value
1212
+ * @param {string|RegExp} expected Expected value
1213
+ * @returns {void}
1214
+ * @private
1215
+ */
1216
+ function assertMessageMatches(actual, expected) {
1217
+ if (expected instanceof RegExp) {
1218
+ // assert.js doesn't have a built-in RegExp match function
1219
+ assert.ok(
1220
+ expected.test(actual),
1221
+ `Expected '${actual}' to match ${expected}`,
1222
+ );
1223
+ } else {
1224
+ assert.strictEqual(actual, expected);
1225
+ }
1226
+ }
1227
+
1228
+ /**
1229
+ * Check if the template is invalid or not
1230
+ * all invalid cases go through this.
1231
+ * @param {Object} item Item to run the rule against
1232
+ * @returns {void}
1233
+ * @private
1234
+ * @throws {Error} If the test case is invalid or has an invalid error.
1235
+ */
1236
+ function testInvalidTemplate(item) {
1237
+ const {
1238
+ requireMessage = false,
1239
+ requireLocation = false,
1240
+ requireData = false,
1241
+ } = test.assertionOptions ?? {};
1242
+
1243
+ const ruleHasMetaMessages =
1244
+ hasOwnProperty(rule, "meta") &&
1245
+ hasOwnProperty(rule.meta, "messages");
1246
+ const friendlyIDList = ruleHasMetaMessages
1247
+ ? `[${Object.keys(rule.meta.messages)
1248
+ .map(key => `'${key}'`)
1249
+ .join(", ")}]`
1250
+ : null;
1251
+
1252
+ assert.ok(
1253
+ ruleHasMetaMessages || requireMessage !== "messageId",
1254
+ `Assertion options can not use 'requireMessage: "messageId"' if rule under test doesn't define 'meta.messages'.`,
1255
+ );
1256
+
1257
+ const result = runRuleForItem(item);
1258
+ const messages = result.messages;
1259
+
1260
+ for (const message of messages) {
1261
+ if (hasOwnProperty(message, "suggestions")) {
1262
+ /** @type {Map<string, number>} */
1263
+ const seenMessageIndices = new Map();
1264
+
1265
+ for (let i = 0; i < message.suggestions.length; i += 1) {
1266
+ const suggestionMessage = message.suggestions[i].desc;
1267
+ const previous =
1268
+ seenMessageIndices.get(suggestionMessage);
1269
+
1270
+ assert.ok(
1271
+ !seenMessageIndices.has(suggestionMessage),
1272
+ `Suggestion message '${suggestionMessage}' reported from suggestion ${i} was previously reported by suggestion ${previous}. Suggestion messages should be unique within an error.`,
1273
+ );
1274
+ seenMessageIndices.set(suggestionMessage, i);
1275
+ }
1276
+ }
1277
+ }
1278
+
1279
+ if (typeof item.errors === "number") {
1280
+ assert.strictEqual(
1281
+ messages.length,
1282
+ item.errors,
1283
+ util.format(
1284
+ "Should have %d error%s but had %d: %s",
1285
+ item.errors,
1286
+ item.errors === 1 ? "" : "s",
1287
+ messages.length,
1288
+ util.inspect(messages),
1289
+ ),
1290
+ );
1291
+ } else {
1292
+ assert.strictEqual(
1293
+ messages.length,
1294
+ item.errors.length,
1295
+ util.format(
1296
+ "Should have %d error%s but had %d: %s",
1297
+ item.errors.length,
1298
+ item.errors.length === 1 ? "" : "s",
1299
+ messages.length,
1300
+ util.inspect(messages),
1301
+ ),
1302
+ );
1303
+
1304
+ const hasMessageOfThisRule = messages.some(
1305
+ m => m.ruleId === ruleId,
1306
+ );
1307
+
1308
+ for (let i = 0, l = item.errors.length; i < l; i++) {
1309
+ try {
1310
+ const error = item.errors[i];
1311
+ const message = messages[i];
1312
+
1313
+ assert(
1314
+ hasMessageOfThisRule,
1315
+ "Error rule name should be the same as the name of the rule being tested",
1316
+ );
1317
+
1318
+ if (
1319
+ typeof error === "string" ||
1320
+ error instanceof RegExp
1321
+ ) {
1322
+ // Just an error message.
1323
+ assertMessageMatches(message.message, error);
1324
+ assert.ok(
1325
+ message.suggestions === void 0,
1326
+ `Error at index ${i} has suggestions. Please convert the test error into an object and specify 'suggestions' property on it to test suggestions.`,
1327
+ );
1328
+ } else if (
1329
+ typeof error === "object" &&
1330
+ error !== null
1331
+ ) {
1332
+ /*
1333
+ * Error object.
1334
+ * This may have a message, messageId, data, line, and/or column.
1335
+ */
1336
+
1337
+ if (hasOwnProperty(error, "message")) {
1338
+ assertMessageMatches(
1339
+ message.message,
1340
+ error.message,
1341
+ );
1342
+ } else if (hasOwnProperty(error, "messageId")) {
1343
+ assert.ok(
1344
+ ruleHasMetaMessages,
1345
+ "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'.",
1346
+ );
1347
+ if (
1348
+ !hasOwnProperty(
1349
+ rule.meta.messages,
1350
+ error.messageId,
1351
+ )
1352
+ ) {
1353
+ assert(
1354
+ false,
1355
+ `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`,
1356
+ );
1357
+ }
1358
+ assert.strictEqual(
1359
+ message.messageId,
1360
+ error.messageId,
1361
+ `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.`,
1362
+ );
1363
+
1364
+ const unsubstitutedPlaceholders =
1365
+ getUnsubstitutedMessagePlaceholders(
1366
+ message.message,
1367
+ rule.meta.messages[message.messageId],
1368
+ error.data,
1369
+ );
1370
+
1371
+ assert.ok(
1372
+ unsubstitutedPlaceholders.length === 0,
1373
+ `The reported message has ${unsubstitutedPlaceholders.length > 1 ? `unsubstituted placeholders: ${unsubstitutedPlaceholders.map(name => `'${name}'`).join(", ")}` : `an unsubstituted placeholder '${unsubstitutedPlaceholders[0]}'`}. Please provide the missing ${unsubstitutedPlaceholders.length > 1 ? "values" : "value"} via the 'data' property in the context.report() call.`,
1374
+ );
1375
+
1376
+ if (hasOwnProperty(error, "data")) {
1377
+ /*
1378
+ * if data was provided, then directly compare the returned message to a synthetic
1379
+ * interpolated message using the same message ID and data provided in the test.
1380
+ * See https://github.com/eslint/eslint/issues/9890 for context.
1381
+ */
1382
+ const unformattedOriginalMessage =
1383
+ rule.meta.messages[error.messageId];
1384
+ const rehydratedMessage = interpolate(
1385
+ unformattedOriginalMessage,
1386
+ error.data,
1387
+ );
1388
+
1389
+ assert.strictEqual(
1390
+ message.message,
1391
+ rehydratedMessage,
1392
+ `Hydrated message "${rehydratedMessage}" does not match "${message.message}"`,
1393
+ );
1394
+ } else {
1395
+ const requiresDataProperty =
1396
+ requireData === true ||
1397
+ requireData === "error";
1398
+ const hasPlaceholders =
1399
+ getMessagePlaceholders(
1400
+ rule.meta.messages[error.messageId],
1401
+ ).length > 0;
1402
+ assert.ok(
1403
+ !requiresDataProperty ||
1404
+ !hasPlaceholders,
1405
+ `Error should specify the 'data' property as the referenced message has placeholders.`,
1406
+ );
1407
+ }
1408
+ }
1409
+
1410
+ const locationProperties = [
1411
+ "line",
1412
+ "column",
1413
+ "endLine",
1414
+ "endColumn",
1415
+ ];
1416
+ const actualLocation = {};
1417
+ const expectedLocation = {};
1418
+
1419
+ for (const key of locationProperties) {
1420
+ if (hasOwnProperty(error, key)) {
1421
+ actualLocation[key] = message[key];
1422
+ expectedLocation[key] = error[key];
1423
+ }
1424
+ }
1425
+
1426
+ if (requireLocation) {
1427
+ const missingKeys = locationProperties.filter(
1428
+ key =>
1429
+ !hasOwnProperty(error, key) &&
1430
+ hasOwnProperty(message, key),
1431
+ );
1432
+ assert.ok(
1433
+ missingKeys.length === 0,
1434
+ `Error is missing expected location properties: ${missingKeys.join(", ")}`,
1435
+ );
1436
+ }
1437
+
1438
+ if (Object.keys(expectedLocation).length > 0) {
1439
+ assert.deepStrictEqual(
1440
+ actualLocation,
1441
+ expectedLocation,
1442
+ "Actual error location does not match expected error location.",
1443
+ );
1444
+ }
1445
+
1446
+ assert.ok(
1447
+ !message.suggestions ||
1448
+ hasOwnProperty(error, "suggestions"),
1449
+ `Error at index ${i} has suggestions. Please specify 'suggestions' property on the test error object.`,
1450
+ );
1451
+ if (hasOwnProperty(error, "suggestions")) {
1452
+ // Support asserting there are no suggestions
1453
+ const expectsSuggestions = Array.isArray(
1454
+ error.suggestions,
1455
+ )
1456
+ ? error.suggestions.length > 0
1457
+ : Boolean(error.suggestions);
1458
+ const hasSuggestions =
1459
+ message.suggestions !== void 0;
1460
+
1461
+ if (!hasSuggestions && expectsSuggestions) {
1462
+ assert.ok(
1463
+ !error.suggestions,
1464
+ `Error should have suggestions on error with message: "${message.message}"`,
1465
+ );
1466
+ } else if (hasSuggestions) {
1467
+ assert.ok(
1468
+ expectsSuggestions,
1469
+ `Error should have no suggestions on error with message: "${message.message}"`,
1470
+ );
1471
+ if (typeof error.suggestions === "number") {
1472
+ assert.strictEqual(
1473
+ message.suggestions.length,
1474
+ error.suggestions,
1475
+ `Error should have ${error.suggestions} suggestions. Instead found ${message.suggestions.length} suggestions`,
1476
+ );
1477
+ } else if (
1478
+ Array.isArray(error.suggestions)
1479
+ ) {
1480
+ assert.strictEqual(
1481
+ message.suggestions.length,
1482
+ error.suggestions.length,
1483
+ `Error should have ${error.suggestions.length} suggestions. Instead found ${message.suggestions.length} suggestions`,
1484
+ );
1485
+
1486
+ error.suggestions.forEach(
1487
+ (expectedSuggestion, index) => {
1488
+ assert.ok(
1489
+ typeof expectedSuggestion ===
1490
+ "object" &&
1491
+ expectedSuggestion !==
1492
+ null,
1493
+ "Test suggestion in 'suggestions' array must be an object.",
1494
+ );
1495
+ Object.keys(
1496
+ expectedSuggestion,
1497
+ ).forEach(propertyName => {
1498
+ assert.ok(
1499
+ suggestionObjectParameters.has(
1500
+ propertyName,
1501
+ ),
1502
+ `Invalid suggestion property name '${propertyName}'. Expected one of ${friendlySuggestionObjectParameterList}.`,
1503
+ );
1504
+ });
1505
+
1506
+ const actualSuggestion =
1507
+ message.suggestions[index];
1508
+ const suggestionPrefix = `Error Suggestion at index ${index}:`;
1509
+
1510
+ if (
1511
+ hasOwnProperty(
1512
+ expectedSuggestion,
1513
+ "desc",
1514
+ )
1515
+ ) {
1516
+ assert.ok(
1517
+ !hasOwnProperty(
1518
+ expectedSuggestion,
1519
+ "data",
1520
+ ),
1521
+ `${suggestionPrefix} Test should not specify both 'desc' and 'data'.`,
1522
+ );
1523
+ assert.ok(
1524
+ !hasOwnProperty(
1525
+ expectedSuggestion,
1526
+ "messageId",
1527
+ ),
1528
+ `${suggestionPrefix} Test should not specify both 'desc' and 'messageId'.`,
1529
+ );
1530
+ assert.strictEqual(
1531
+ actualSuggestion.desc,
1532
+ expectedSuggestion.desc,
1533
+ `${suggestionPrefix} desc should be "${expectedSuggestion.desc}" but got "${actualSuggestion.desc}" instead.`,
1534
+ );
1535
+ } else if (
1536
+ hasOwnProperty(
1537
+ expectedSuggestion,
1538
+ "messageId",
1539
+ )
1540
+ ) {
1541
+ assert.ok(
1542
+ ruleHasMetaMessages,
1543
+ `${suggestionPrefix} Test can not use 'messageId' if rule under test doesn't define 'meta.messages'.`,
1544
+ );
1545
+ assert.ok(
1546
+ hasOwnProperty(
1547
+ rule.meta.messages,
1548
+ expectedSuggestion.messageId,
1549
+ ),
1550
+ `${suggestionPrefix} Test has invalid messageId '${expectedSuggestion.messageId}', the rule under test allows only one of ${friendlyIDList}.`,
1551
+ );
1552
+ assert.strictEqual(
1553
+ actualSuggestion.messageId,
1554
+ expectedSuggestion.messageId,
1555
+ `${suggestionPrefix} messageId should be '${expectedSuggestion.messageId}' but got '${actualSuggestion.messageId}' instead.`,
1556
+ );
1557
+
1558
+ const rawSuggestionMessage =
1559
+ rule.meta.messages[
1560
+ expectedSuggestion
1561
+ .messageId
1562
+ ];
1563
+ const unsubstitutedPlaceholders =
1564
+ getUnsubstitutedMessagePlaceholders(
1565
+ actualSuggestion.desc,
1566
+ rawSuggestionMessage,
1567
+ expectedSuggestion.data,
1568
+ );
1569
+
1570
+ assert.ok(
1571
+ unsubstitutedPlaceholders.length ===
1572
+ 0,
1573
+ `The message of the suggestion has ${unsubstitutedPlaceholders.length > 1 ? `unsubstituted placeholders: ${unsubstitutedPlaceholders.map(name => `'${name}'`).join(", ")}` : `an unsubstituted placeholder '${unsubstitutedPlaceholders[0]}'`}. Please provide the missing ${unsubstitutedPlaceholders.length > 1 ? "values" : "value"} via the 'data' property for the suggestion in the context.report() call.`,
1574
+ );
1575
+
1576
+ if (
1577
+ hasOwnProperty(
1578
+ expectedSuggestion,
1579
+ "data",
1580
+ )
1581
+ ) {
1582
+ const unformattedMetaMessage =
1583
+ rule.meta.messages[
1584
+ expectedSuggestion
1585
+ .messageId
1586
+ ];
1587
+ const rehydratedDesc =
1588
+ interpolate(
1589
+ unformattedMetaMessage,
1590
+ expectedSuggestion.data,
1591
+ );
1592
+
1593
+ assert.strictEqual(
1594
+ actualSuggestion.desc,
1595
+ rehydratedDesc,
1596
+ `${suggestionPrefix} Hydrated test desc "${rehydratedDesc}" does not match received desc "${actualSuggestion.desc}".`,
1597
+ );
1598
+ } else {
1599
+ const requiresDataProperty =
1600
+ requireData ===
1601
+ true ||
1602
+ requireData ===
1603
+ "suggestion";
1604
+ const hasPlaceholders =
1605
+ getMessagePlaceholders(
1606
+ rawSuggestionMessage,
1607
+ ).length > 0;
1608
+ assert.ok(
1609
+ !requiresDataProperty ||
1610
+ !hasPlaceholders,
1611
+ `${suggestionPrefix} Suggestion should specify the 'data' property as the referenced message has placeholders.`,
1612
+ );
1613
+ }
1614
+ } else if (
1615
+ hasOwnProperty(
1616
+ expectedSuggestion,
1617
+ "data",
1618
+ )
1619
+ ) {
1620
+ assert.fail(
1621
+ `${suggestionPrefix} Test must specify 'messageId' if 'data' is used.`,
1622
+ );
1623
+ } else {
1624
+ assert.fail(
1625
+ `${suggestionPrefix} Test must specify either 'messageId' or 'desc'.`,
1626
+ );
1627
+ }
1628
+
1629
+ assert.ok(
1630
+ hasOwnProperty(
1631
+ expectedSuggestion,
1632
+ "output",
1633
+ ),
1634
+ `${suggestionPrefix} The "output" property is required.`,
1635
+ );
1636
+ const codeWithAppliedSuggestion =
1637
+ SourceCodeFixer.applyFixes(
1638
+ item.code,
1639
+ [actualSuggestion],
1640
+ ).output;
1641
+
1642
+ // Verify if suggestion fix makes a syntax error or not.
1643
+ const errorMessageInSuggestion =
1644
+ linter
1645
+ .verify(
1646
+ codeWithAppliedSuggestion,
1647
+ result.configs,
1648
+ result.filename,
1649
+ )
1650
+ .find(m => m.fatal);
1651
+
1652
+ assert(
1653
+ !errorMessageInSuggestion,
1654
+ [
1655
+ "A fatal parsing error occurred in suggestion fix.",
1656
+ `Error: ${errorMessageInSuggestion && errorMessageInSuggestion.message}`,
1657
+ "Suggestion output:",
1658
+ codeWithAppliedSuggestion,
1659
+ ].join("\n"),
1660
+ );
1661
+
1662
+ assert.strictEqual(
1663
+ codeWithAppliedSuggestion,
1664
+ expectedSuggestion.output,
1665
+ `Expected the applied suggestion fix to match the test suggestion output for suggestion at index: ${index} on error with message: "${message.message}"`,
1666
+ );
1667
+ assert.notStrictEqual(
1668
+ expectedSuggestion.output,
1669
+ item.code,
1670
+ `The output of a suggestion should differ from the original source code for suggestion at index: ${index} on error with message: "${message.message}"`,
1671
+ );
1672
+ },
1673
+ );
1674
+ } else {
1675
+ assert.fail(
1676
+ "Test error object property 'suggestions' should be an array or a number",
1677
+ );
1678
+ }
1679
+ }
1680
+ }
1681
+ }
1682
+ } catch (error) {
1683
+ if (error instanceof Error) {
1684
+ error.errorIndex = i;
1685
+ }
1686
+ throw error;
1687
+ }
1688
+ }
1689
+ }
1690
+
1691
+ if (hasOwnProperty(item, "output")) {
1692
+ if (item.output === null) {
1693
+ assert.strictEqual(
1694
+ result.output,
1695
+ item.code,
1696
+ "Expected no autofixes to be suggested",
1697
+ );
1698
+ } else {
1699
+ assert.strictEqual(
1700
+ result.output,
1701
+ item.output,
1702
+ "Output is incorrect.",
1703
+ );
1704
+ assert.notStrictEqual(
1705
+ item.code,
1706
+ item.output,
1707
+ "Test property 'output' matches 'code'. If no autofix is expected, then omit the 'output' property or set it to null.",
1708
+ );
1709
+ }
1710
+ } else {
1711
+ assert.strictEqual(
1712
+ result.output,
1713
+ item.code,
1714
+ "The rule fixed the code. Please add 'output' property.",
1715
+ );
1716
+ }
1717
+
1718
+ assertASTDidntChange(result.beforeAST, result.afterAST);
1719
+ }
1720
+
1721
+ /*
1722
+ * This creates a mocha test suite and pipes all supplied info through
1723
+ * one of the templates above.
1724
+ * The test suites for valid/invalid are created conditionally as
1725
+ * test runners (eg. vitest) fail for empty test suites.
1726
+ */
1727
+ this.constructor.describe(ruleName, () => {
1728
+ if (test.valid.length > 0) {
1729
+ this.constructor.describe("valid", () => {
1730
+ const seenTestCases = new Set();
1731
+ test.valid.forEach((valid, index) => {
1732
+ const item = normalizeTestCase(valid);
1733
+ this.constructor[valid.only ? "itOnly" : "it"](
1734
+ sanitize(item.name || item.code),
1735
+ () => {
1736
+ try {
1737
+ runHook(item, "before");
1738
+ assertValidTestCase(item, seenTestCases);
1739
+ testValidTemplate(item);
1740
+ } catch (error) {
1741
+ if (error instanceof Error) {
1742
+ error.scenarioType = "valid";
1743
+ error.scenarioIndex = index;
1744
+ error.stack = error.stack.replace(
1745
+ /^ +at /mu,
1746
+ [
1747
+ ` at RuleTester.run.valid[${index}]`,
1748
+ ` at RuleTester.run.valid`,
1749
+ ` at RuleTester.run (${invocationLocation})`,
1750
+ " at ",
1751
+ ].join("\n"),
1752
+ );
1753
+ }
1754
+ throw error;
1755
+ } finally {
1756
+ runHook(item, "after");
1757
+ }
1758
+ },
1759
+ );
1760
+ });
1761
+ });
1762
+ }
1763
+
1764
+ if (test.invalid.length > 0) {
1765
+ this.constructor.describe("invalid", () => {
1766
+ const seenTestCases = new Set();
1767
+ test.invalid.forEach((invalid, index) => {
1768
+ const item = normalizeTestCase(invalid);
1769
+ this.constructor[item.only ? "itOnly" : "it"](
1770
+ sanitize(item.name || item.code),
1771
+ () => {
1772
+ try {
1773
+ runHook(item, "before");
1774
+ assertInvalidTestCase(
1775
+ item,
1776
+ seenTestCases,
1777
+ ruleName,
1778
+ test.assertionOptions,
1779
+ );
1780
+ testInvalidTemplate(item);
1781
+ } catch (error) {
1782
+ if (error instanceof Error) {
1783
+ error.scenarioType = "invalid";
1784
+ error.scenarioIndex = index;
1785
+ const errorIndex = error.errorIndex;
1786
+ error.stack = error.stack.replace(
1787
+ /^ +at /mu,
1788
+ [
1789
+ ...(typeof errorIndex ===
1790
+ "number"
1791
+ ? [
1792
+ ` at RuleTester.run.invalid[${index}].error[${errorIndex}]`,
1793
+ ]
1794
+ : []),
1795
+ ` at RuleTester.run.invalid[${index}]`,
1796
+ ` at RuleTester.run.invalid`,
1797
+ ` at RuleTester.run (${invocationLocation})`,
1798
+ " at ",
1799
+ ].join("\n"),
1800
+ );
1801
+ }
1802
+ throw error;
1803
+ } finally {
1804
+ runHook(item, "after");
1805
+ }
1806
+ },
1807
+ );
1808
+ });
1809
+ });
1810
+ }
1811
+ });
1812
+ }
1813
+ }
1814
+
1815
+ RuleTester[DESCRIBE] = RuleTester[IT] = RuleTester[IT_ONLY] = null;
1816
+
1817
+ module.exports = RuleTester;