-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
950 lines (899 loc) · 38.3 KB
/
index.js
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
import { pathToFileURL } from 'node:url';
import next from '@next/eslint-plugin-next';
import eslintTypescript from '@typescript-eslint/eslint-plugin';
import typescriptParser from '@typescript-eslint/parser';
import gitignore from 'eslint-config-flat-gitignore';
import eslintImport from 'eslint-plugin-import';
import jsxA11y from 'eslint-plugin-jsx-a11y';
import jsxExpressions from 'eslint-plugin-jsx-expressions';
import react from 'eslint-plugin-react';
import reactHooks from 'eslint-plugin-react-hooks';
import security from 'eslint-plugin-security';
import sonarjs from 'eslint-plugin-sonarjs';
import unicorn from 'eslint-plugin-unicorn';
import upleveled from 'eslint-plugin-upleveled';
import globals from 'globals';
/** @type {import('@typescript-eslint/utils/ts-eslint').FlatConfig.RuleLevelAndOptions} */
export const noRestrictedSyntaxOptions = [
'warn',
// Currently it is not possible to use Markdown eg. links in ESLint warnings / error messages
//
// FIXME: Switch to a custom rule
// https://github.com/upleveled/eslint-config-upleveled/issues/123
{
selector:
"ExpressionStatement CallExpression[callee.object.name='document'][callee.property.name='querySelector'], VariableDeclaration VariableDeclarator CallExpression[callee.object.name='document'][callee.property.name='querySelector']",
message: `Using document.querySelector() can lead to problems, and is not commonly used in React code - prefer instead usage of basic React patterns such as state and controlled components
https://github.com/reactjs/reactjs.org/issues/4626#issuecomment-1117535930`,
},
{
selector:
"ExpressionStatement CallExpression[callee.object.name='document'][callee.property.name='querySelectorAll'], VariableDeclaration VariableDeclarator CallExpression[callee.object.name='document'][callee.property.name='querySelectorAll']",
message: `Using document.querySelectorAll() can lead to problems, and is not commonly used in React code - prefer instead usage of basic React patterns such as state and controlled components
https://github.com/reactjs/reactjs.org/issues/4626#issuecomment-1117535930`,
},
{
selector:
"ExpressionStatement CallExpression[callee.object.name='document'][callee.property.name='getElementById'], VariableDeclaration VariableDeclarator[init.callee.object.name!='ReactDOM'][init.callee.property.name!='createRoot'] CallExpression[callee.object.name='document'][callee.property.name='getElementById']",
message: `Using document.getElementById() can lead to problems, and is not commonly used in React code - prefer instead usage of basic React patterns such as state and controlled components
https://github.com/reactjs/reactjs.org/issues/4626#issuecomment-1117535930`,
},
// Currently it is not possible to use Markdown eg. links in ESLint warnings / error messages
//
// FIXME: Switch to a custom rule
// https://github.com/upleveled/eslint-config-upleveled/issues/126
{
selector:
'FunctionDeclaration VariableDeclaration:has(VariableDeclarator > TaggedTemplateExpression > MemberExpression[object.name="styled"][property]), FunctionDeclaration VariableDeclaration:has(VariableDeclarator > TaggedTemplateExpression[tag.name="css"])',
message:
'Declaring Emotion styles or a styled component within a React component will cause the element to get recreated, causing loss of state and other problems - see the react/no-unstable-nested-components docs for more info https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-unstable-nested-components.md',
},
{
selector:
"ExpressionStatement CallExpression[callee.object.name='location'][callee.property.name='reload']",
message:
'Update content and elements with React instead of using location.reload()',
},
{
selector:
"ExpressionStatement CallExpression[callee.object.object.name='window'][callee.object.property.name='location'][callee.property.name='reload']",
message:
'Update content and elements with React instead of using location.reload()',
},
{
selector:
"JSXAttribute[name.name='href'] > Literal[value=/^\\./], JSXAttribute[name.name='href'] > JSXExpressionContainer > TemplateLiteral TemplateElement:first-child[value.cooked=/^\\./]",
message:
'Always start href relative URLs with a forward slash (aka use root relative URLs) - read more at https://www.webdevbydoing.com/absolute-relative-and-root-relative-file-paths/',
},
{
selector:
"JSXAttribute[name.name='key'] > JSXExpressionContainer > :not(TemplateLiteral)",
message:
// eslint-disable-next-line no-template-curly-in-string -- Allow for the code example including template strings and interpolation
'Use template literals including a prefixes for the values of key props (eg. <div key={`user-${user.id}`}> instead of <div key={user.id}>)',
},
// Warn on nesting <a> elements, <button> elements and framework <Link> components inside of each other
{
selector:
"JSXElement[openingElement.name.name='a'] > JSXElement[openingElement.name.name=/^(a|button|Link)$/]",
message:
'Invalid DOM Nesting: anchor elements cannot have anchor elements, button elements or Link components as children',
},
{
selector:
"JSXElement[openingElement.name.name='button'] > JSXElement[openingElement.name.name=/^(a|button|Link)$/]",
message:
'Invalid DOM Nesting: button elements cannot have anchor elements, button elements or Link components as children',
},
{
selector:
"JSXElement[openingElement.name.name='Link'] > JSXElement[openingElement.name.name=/^(a|button|Link)$/]",
message:
'Invalid DOM Nesting: Link components cannot have anchor elements, button elements or Link components as children',
},
// Warn on nesting of non-<li> elements inside of <ol> and <ul> elements
{
selector:
"JSXElement[openingElement.name.name=/^(ol|ul)$/] > JSXElement[openingElement.name.name!='li'][openingElement.name.name!=/^[A-Z]/]",
message:
'Invalid DOM Nesting: ol and ul elements cannot have non-li elements as children',
},
// Warn on nesting common invalid elements inside of <p> elements
{
selector:
"JSXElement[openingElement.name.name='p'] > JSXElement[openingElement.name.name=/^(div|h1|h2|h3|h4|h5|h6|hr|ol|p|table|ul)$/]",
message:
'Invalid DOM Nesting: p elements cannot have div, h1, h2, h3, h4, h5, h6, hr, ol, p, table or ul elements as children',
},
// Warn on nesting any invalid elements inside of <table> elements
{
selector:
"JSXElement[openingElement.name.name='table'] > JSXElement[openingElement.name.name!=/^(caption|colgroup|tbody|tfoot|thead)$/][openingElement.name.name!=/^[A-Z]/]",
message:
'Invalid DOM Nesting: table elements cannot have element which are not caption, colgroup, tbody, tfoot or thead elements as children',
},
// Warn on nesting any invalid elements inside of <tbody>, <thead> and <tfoot> elements
{
selector:
"JSXElement[openingElement.name.name=/(tbody|thead|tfoot)/] > JSXElement[openingElement.name.name!='tr'][openingElement.name.name!=/^[A-Z]/]",
message:
'Invalid DOM Nesting: tbody, thead and tfoot elements cannot have non-tr elements as children',
},
// Warn on nesting any invalid elements inside of <tr> elements
{
selector:
"JSXElement[openingElement.name.name='tr'] > JSXElement[openingElement.name.name!=/(th|td)/][openingElement.name.name!=/^[A-Z]/]",
message:
'Invalid DOM Nesting: tr elements cannot have elements which are not th or td elements as children',
},
// Warn on sql tagged template literal without generic type argument
{
selector:
"VariableDeclarator > AwaitExpression > TaggedTemplateExpression[tag.name='sql']:not([typeParameters.params.0])",
message: `sql tagged template literal missing generic type argument, eg.
const animals = await sql<Animal[]>\`
SELECT * FROM animals
\`;
`,
},
// Warn on standalone && expressions at top level and inside blocks
{
selector:
"Program > ExpressionStatement > LogicalExpression[operator='&&'], BlockStatement > ExpressionStatement > LogicalExpression[operator='&&']",
message: `Prefer if statements to standalone && expressions, eg. instead of a standalone expression like this:
animal && showAnimal();
Prefer an if statement like this:
if (animal) showAnimal();
`,
},
// Warn on standalone || expressions at top level and inside blocks
{
selector:
"Program > ExpressionStatement > LogicalExpression[operator='||'], BlockStatement > ExpressionStatement > LogicalExpression[operator='||']",
message: `Prefer if statements to standalone || expressions, eg. instead of a standalone expression like this:
animal || hideAnimal();
Prefer an if statement like this:
if (!animal) hideAnimal();
`,
},
// Warn on standalone ternary expressions at top level and inside blocks
{
selector:
'Program > ExpressionStatement > ConditionalExpression, BlockStatement > ExpressionStatement > ConditionalExpression',
message: `Prefer if...else statements to standalone ternary operators, eg. instead of a standalone ternary operator like this:
animal ? showAnimal() : hideAnimal();
Prefer an if...else statement like this:
if (animal) {
showAnimal();
} else {
hideAnimal();
}
`,
},
// Warn on import paths ending in /page to avoid errors with Next.js Statically Typed Links
{
selector:
'ImportDeclaration[source.value=/^\\.\\.?\\u002F(.+\\u002F)?page$/]',
message: `Avoid imports from other pages in Next.js - this can cause errors with Next.js Statically Typed Links https://nextjs.org/docs/app/building-your-application/configuring/typescript#statically-typed-links
Instead, move anything you want to import to a non-page file`,
},
];
/**
* Copied contents from the defunct project eslint-config-react-app
*
* https://github.com/facebook/create-react-app/blob/main/packages/eslint-config-react-app/index.js
* https://github.com/facebook/create-react-app/blob/main/packages/eslint-config-react-app/base.js
*
* @type {import('@typescript-eslint/utils/ts-eslint').FlatConfig.Rules}
*/
const eslintConfigReactAppRules = {
'array-callback-return': 'warn',
'default-case': ['warn', { commentPattern: '^no default$' }],
'dot-location': ['warn', 'property'],
eqeqeq: ['warn', 'smart'],
'new-parens': 'warn',
'no-caller': 'warn',
'no-cond-assign': ['warn', 'except-parens'],
'no-const-assign': 'warn',
'no-control-regex': 'warn',
'no-delete-var': 'warn',
'no-dupe-args': 'warn',
'no-dupe-class-members': 'warn',
'no-dupe-keys': 'warn',
'no-duplicate-case': 'warn',
'no-empty-character-class': 'warn',
'no-empty-pattern': 'warn',
'no-eval': 'warn',
'no-ex-assign': 'warn',
'no-extend-native': 'warn',
'no-extra-bind': 'warn',
'no-extra-label': 'warn',
'no-fallthrough': 'warn',
'no-func-assign': 'warn',
'no-implied-eval': 'warn',
'no-invalid-regexp': 'warn',
'no-iterator': 'warn',
'no-label-var': 'warn',
'no-labels': ['warn', { allowLoop: true, allowSwitch: false }],
'no-lone-blocks': 'warn',
'no-loop-func': 'warn',
'no-mixed-operators': [
'warn',
{
groups: [
['&', '|', '^', '~', '<<', '>>', '>>>'],
['==', '!=', '===', '!==', '>', '>=', '<', '<='],
['&&', '||'],
['in', 'instanceof'],
],
allowSamePrecedence: false,
},
],
'no-multi-str': 'warn',
'no-global-assign': 'warn',
'no-unsafe-negation': 'warn',
'no-new-func': 'warn',
'no-new-object': 'warn',
'no-new-symbol': 'warn',
'no-new-wrappers': 'warn',
'no-obj-calls': 'warn',
'no-octal': 'warn',
'no-octal-escape': 'warn',
'no-regex-spaces': 'warn',
'no-script-url': 'warn',
'no-self-assign': 'warn',
'no-self-compare': 'warn',
'no-sequences': 'warn',
'no-shadow-restricted-names': 'warn',
'no-sparse-arrays': 'warn',
'no-template-curly-in-string': 'warn',
'no-this-before-super': 'warn',
'no-throw-literal': 'warn',
'no-undef': 'error',
'no-restricted-globals': [
'error',
// Confusing browser globals (copied from create-react-app)
//
// The ESLint browser environment defines all browser globals as valid,
// even though most people don't know some of them exist (e.g. `name` or `status`).
// This is dangerous as it hides accidentally undefined variables.
// We blacklist the globals that we deem potentially confusing.
// To use them, explicitly reference them, e.g. `window.name` or `window.status`.
//
// https://github.com/facebook/create-react-app/blob/main/packages/confusing-browser-globals/index.js
'addEventListener',
'blur',
'close',
'closed',
'confirm',
'defaultStatus',
'defaultstatus',
'event',
'external',
'find',
'focus',
'frameElement',
'frames',
'history',
'innerHeight',
'innerWidth',
'length',
'location',
'locationbar',
'menubar',
'moveBy',
'moveTo',
'name',
'onblur',
'onerror',
'onfocus',
'onload',
'onresize',
'onunload',
'open',
'opener',
'opera',
'outerHeight',
'outerWidth',
'pageXOffset',
'pageYOffset',
'parent',
'print',
'removeEventListener',
'resizeBy',
'resizeTo',
'screen',
'screenLeft',
'screenTop',
'screenX',
'screenY',
'scroll',
'scrollbars',
'scrollBy',
'scrollTo',
'scrollX',
'scrollY',
'self',
'status',
'statusbar',
'stop',
'toolbar',
'top',
],
'no-unreachable': 'warn',
'no-unused-labels': 'warn',
'no-useless-computed-key': 'warn',
'no-useless-concat': 'warn',
'no-useless-escape': 'warn',
'no-useless-rename': [
'warn',
{
ignoreDestructuring: false,
ignoreImport: false,
ignoreExport: false,
},
],
'no-with': 'warn',
'no-whitespace-before-property': 'warn',
'react-hooks/exhaustive-deps': 'warn',
'require-yield': 'warn',
'rest-spread-spacing': ['warn', 'never'],
strict: ['warn', 'never'],
'unicode-bom': ['warn', 'never'],
'use-isnan': 'warn',
'valid-typeof': 'warn',
'no-restricted-properties': [
'error',
{
object: 'require',
property: 'ensure',
message:
'Please use import() instead. More info: https://facebook.github.io/create-react-app/docs/code-splitting',
},
{
object: 'System',
property: 'import',
message:
'Please use import() instead. More info: https://facebook.github.io/create-react-app/docs/code-splitting',
},
],
'getter-return': 'warn',
// https://github.com/benmosher/eslint-plugin-import/tree/master/docs/rules
'import/first': 'error',
'import/no-amd': 'error',
'import/no-anonymous-default-export': 'warn',
'import/no-webpack-loader-syntax': 'error',
// https://github.com/yannickcr/eslint-plugin-react/tree/master/docs/rules
'react/forbid-foreign-prop-types': ['warn', { allowInPropTypes: true }],
'react/jsx-no-comment-textnodes': 'warn',
'react/jsx-no-duplicate-props': 'warn',
'react/jsx-no-target-blank': 'warn',
'react/jsx-no-undef': 'error',
'react/jsx-pascal-case': [
'warn',
{
allowAllCaps: true,
ignore: [],
},
],
'react/no-danger-with-children': 'warn',
// Disabled because of undesirable warnings
// See https://github.com/facebook/create-react-app/issues/5204 for
// blockers until its re-enabled
// 'react/no-deprecated': 'warn',
'react/no-direct-mutation-state': 'warn',
'react/no-is-mounted': 'warn',
'react/no-typos': 'error',
'react/require-render-return': 'error',
'react/style-prop-object': [
'warn',
{
allow: [
// Allow expo-status-bar style prop, which is a string, eg:
// <StatusBar style="auto" />
// https://github.com/expo/expo/blob/999572cd1036529ffa3a28a0490dd7c0f6f0d731/packages/expo-status-bar/src/StatusBar.types.ts#L2
'StatusBar',
],
},
],
// https://github.com/evcohen/eslint-plugin-jsx-a11y/tree/master/docs/rules
'jsx-a11y/alt-text': 'warn',
'jsx-a11y/anchor-has-content': 'warn',
'jsx-a11y/aria-activedescendant-has-tabindex': 'warn',
'jsx-a11y/aria-props': 'warn',
'jsx-a11y/aria-proptypes': 'warn',
'jsx-a11y/aria-role': ['warn', { ignoreNonDOM: true }],
'jsx-a11y/aria-unsupported-elements': 'warn',
'jsx-a11y/heading-has-content': 'warn',
'jsx-a11y/iframe-has-title': 'warn',
'jsx-a11y/img-redundant-alt': 'warn',
'jsx-a11y/no-access-key': 'warn',
'jsx-a11y/no-distracting-elements': 'warn',
'jsx-a11y/no-redundant-roles': 'warn',
'jsx-a11y/role-has-required-aria-props': 'warn',
'jsx-a11y/role-supports-aria-props': 'warn',
'jsx-a11y/scope': 'warn',
// https://github.com/facebook/react/tree/main/packages/eslint-plugin-react-hooks
'react-hooks/rules-of-hooks': 'error',
};
/** @type {import('@typescript-eslint/utils/ts-eslint').FlatConfig.ConfigArray} */
const configArray = [
gitignore(),
{
// Lint common extensions by default with rules above
files: [
'**/*.js',
'**/*.jsx',
'**/*.cjs',
'**/*.mjs',
'**/*.ts',
'**/*.tsx',
'**/*.cts',
'**/*.mts',
],
languageOptions: {
parser: typescriptParser,
parserOptions: {
project: './tsconfig.json',
// typescript-eslint specific options
warnOnUnsupportedTypeScriptVersion: true,
},
globals: {
...globals.browser,
...globals.node,
...globals.commonjs,
...globals.es2021,
// Allow using React as a global without importing it
React: true,
},
},
plugins: {
'@next/next': next,
'@typescript-eslint': {
rules: eslintTypescript.rules,
},
'jsx-a11y': jsxA11y,
'jsx-expressions': jsxExpressions,
'react-hooks': reactHooks,
import: eslintImport,
react,
security,
sonarjs: {
rules: sonarjs.rules,
},
unicorn,
upleveled,
},
settings: {
'import/resolver': {
// Load <rootdir>/tsconfig.json
typescript: {
// Always try resolving any corresponding @types/* folders
alwaysTryTypes: true,
},
},
react: {
version: 'detect',
},
},
rules: {
...eslintConfigReactAppRules,
// eslint-disable-next-line rest-spread-spacing -- Allow JSDoc casting
.../** @type {Exclude<Exclude<import('@typescript-eslint/utils/ts-eslint').FlatConfig.Plugin['configs'], undefined>[string], undefined>} */ (
/** @type {Exclude<import('@typescript-eslint/utils/ts-eslint').FlatConfig.Plugin['configs'], undefined>} */ (
jsxA11y.configs
).recommended
).rules,
// Error about importing next/document in a page other than pages/_document.js
// https://github.com/vercel/next.js/blob/canary/errors/no-document-import-in-page.md
'@next/next/no-document-import-in-page': 'error',
// Error about importing next/head in pages/_document.js
// https://github.com/vercel/next.js/blob/canary/errors/no-head-import-in-document.md
'@next/next/no-head-import-in-document': 'error',
// Error about using <a> element to navigate to a page route instead of Next.js <Link /> component
// https://github.com/vercel/next.js/blob/canary/errors/no-html-link-for-pages.md
'@next/next/no-html-link-for-pages': 'error',
// Warn about using a custom font in a single page instead of in pages/_document.js
// https://github.com/vercel/next.js/blob/canary/errors/no-page-custom-font.md
'@next/next/no-page-custom-font': 'warn',
// Warn about setting a title for all pages in a single page by importing <Head /> from next/document
// https://github.com/vercel/next.js/blob/canary/errors/no-title-in-document-head.md
'@next/next/no-title-in-document-head': 'warn',
// Error on dangerous types like:
// - uppercase primitive types
// - Function
// - Object and {}
// https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/ban-types.md
'@typescript-eslint/ban-types': ['error'],
// Warn on usage of angle brackets for type assertions (eg. `<Type>x`)
// https://typescript-eslint.io/rules/consistent-type-assertions/
'@typescript-eslint/consistent-type-assertions': 'warn',
// Warn on variables not following naming convention
// https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/naming-convention.md
'@typescript-eslint/naming-convention': [
'warn',
// Defaults from @typescript-eslint/eslint-plugin
// https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/naming-convention.md#options
{
selector: 'default',
format: ['camelCase'],
leadingUnderscore: 'allow',
trailingUnderscore: 'allow',
},
{
selector: 'variable',
types: ['boolean', 'string', 'number', 'array'],
format: ['camelCase', 'UPPER_CASE'],
leadingUnderscore: 'allow',
trailingUnderscore: 'allow',
},
{
selector: 'typeLike',
format: ['PascalCase'],
},
// Allow PascalCase for functions (React components)
{
selector: 'function',
format: ['camelCase', 'PascalCase'],
leadingUnderscore: 'allow',
},
{
selector: 'variable',
types: ['function'],
format: ['camelCase', 'PascalCase'],
leadingUnderscore: 'allow',
},
{
selector: 'property',
format: null,
},
{
selector: 'parameter',
format: ['camelCase', 'snake_case', 'PascalCase'],
},
// Disable @typescript-eslint/naming-convention format for imports
// https://github.com/typescript-eslint/typescript-eslint/pull/7269#issuecomment-1777628591
{
selector: 'import',
format: null,
},
],
// Warn on usage of array constructor (eg. Array(0, 1), new Array(0, 1))
// https://typescript-eslint.io/rules/no-array-constructor/
'no-array-constructor': 'off',
'@typescript-eslint/no-array-constructor': 'warn',
// Error on expressions where operations with ||, && and
// ?? operators have likely unintended effects
// https://eslint.org/docs/latest/rules/no-constant-binary-expression
'no-constant-binary-expression': 'error',
// Warn on dangling promises without await
'@typescript-eslint/no-floating-promises': [
'warn',
{ ignoreVoid: false },
],
// Warn on redeclare of variables
// https://typescript-eslint.io/rules/no-redeclare/
'no-redeclare': 'off',
'@typescript-eslint/no-redeclare': 'warn',
// Warn about variable shadowing
// https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-shadow.md
'@typescript-eslint/no-shadow': 'warn',
// Disable built-in ESLint no-constant-condition
// to use the more powerful @typescript-eslint/no-unnecessary-condition
// https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-unnecessary-condition.md
'no-constant-condition': 'off',
'@typescript-eslint/no-unnecessary-condition': 'warn',
// Prevent unnecessary type arguments
// https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-unnecessary-type-arguments.md
'@typescript-eslint/no-unnecessary-type-arguments': 'warn',
// Prevent unnecessary type assertions
// https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-unnecessary-type-assertion.md
'@typescript-eslint/no-unnecessary-type-assertion': 'warn',
// Disable built-in ESLint no-dupe-class-members
// to use the more powerful @typescript-eslint/no-dupe-class-members
// https://typescript-eslint.io/rules/no-dupe-class-members/
'no-dupe-class-members': 'off',
'@typescript-eslint/no-dupe-class-members': 'warn',
// Warn on unused expressions
// https://typescript-eslint.io/rules/no-unused-expression
'no-unused-expressions': 'off',
'@typescript-eslint/no-unused-expressions': [
'warn',
{
allowShortCircuit: true,
allowTernary: true,
allowTaggedTemplates: true,
},
],
// Disable built-in ESLint no-unused-vars
// to use the more powerful @typescript-eslint/no-unused-vars
// https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-unused-vars.md
// https://eslint.org/docs/rules/no-unused-vars
'no-unused-vars': 'off',
// No need for this, @typescript-eslint/parser fully understands JSX semantics
// https://github.com/typescript-eslint/typescript-eslint/issues/2985#issuecomment-771771967
'@typescript-eslint/no-unused-vars': [
'warn',
{
args: 'after-used',
ignoreRestSiblings: true,
},
],
// Disable built-in ESLint no-use-before-define
// in order to enable the rule from the
// @typescript-eslint plugin
'no-use-before-define': 'off',
'@typescript-eslint/no-use-before-define': [
'error',
{
functions: false,
typedefs: false,
},
],
// Warn on useless constructor in class
// https://typescript-eslint.io/rules/no-useless-constructor/
'no-useless-constructor': 'off',
'@typescript-eslint/no-useless-constructor': 'warn',
// Warn about unnecessary tepmlate literals
// https://typescript-eslint.io/rules/no-useless-template-literals/
'@typescript-eslint/no-useless-template-literals': 'warn',
// Warn about template literal interpolation of non-primitive
// data types like objects / arrays and values with type `any`
// https://typescript-eslint.io/rules/restrict-template-expressions/
'@typescript-eslint/restrict-template-expressions': [
'error',
{
allowAny: false,
},
],
// Allow leaving out curlies only with single-line condition blocks
// https://github.com/eslint/eslint/blob/master/docs/rules/curly.md#multi-line
curly: ['warn', 'multi-line', 'consistent'],
// Error out on imports that don't match
// the underlying file system
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-unresolved.md
'import/no-unresolved': 'error',
// Remove `href` warnings on anchor tags for Next.js
// Issue in Next.js: https://github.com/zeit/next.js/issues/5533
// Fix: https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/issues/402#issuecomment-368305051
'jsx-a11y/anchor-is-valid': [
'error',
{
components: ['Link'],
specialLink: ['hrefLeft', 'hrefRight'],
aspects: ['invalidHref', 'preferButton'],
},
],
// Disable obsolete rule
// https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/issues/398#issuecomment-728976688
'jsx-a11y/no-onchange': 'off',
// Disallow potentially falsey string and number values in logical && expressions
// https://github.com/hpersson/eslint-plugin-jsx-expressions/blob/master/docs/rules/strict-logical-expressions.md
'jsx-expressions/strict-logical-expressions': 'error',
// Warn on async promise executor function
// https://github.com/eslint/eslint/blob/main/docs/src/rules/no-async-promise-executor.md
'no-async-promise-executor': 'warn',
// Warn on return in promise executor function
// https://github.com/eslint/eslint/blob/main/docs/src/rules/no-promise-executor-return.md
'no-promise-executor-return': 'warn',
// Warn on restricted syntax
'no-restricted-syntax': noRestrictedSyntaxOptions,
// Warn on usage of var (which doesn't follow block scope rules)
// https://eslint.org/docs/rules/no-var
'no-var': 'warn',
// Warn about non-changing variables not being constants
// https://eslint.org/docs/rules/prefer-const
'prefer-const': 'warn',
// Warn on promise rejection without Error object
// https://github.com/eslint/eslint/blob/main/docs/src/rules/prefer-promise-reject-errors.md
'prefer-promise-reject-errors': 'warn',
// Warn about state variable and setter names which are not symmetrically named
// https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/hook-use-state.md
'react/hook-use-state': 'warn',
// Error on missing sandbox attribute on iframes (good security practice)
// https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/iframe-missing-sandbox.md
'react/iframe-missing-sandbox': 'error',
// Warn about unnecessary curly braces around props and string literal children
// https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-curly-brace-presence.md
'react/jsx-curly-brace-presence': [
'warn',
{ props: 'never', children: 'never', propElementValues: 'always' },
],
// Error on missing or incorrect `key` props in maps in JSX
// https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-key.md
'react/jsx-key': [
'error',
{
checkFragmentShorthand: true,
checkKeyMustBeforeSpread: true,
warnOnDuplicates: true,
},
],
// Error on useless React fragments
'react/jsx-no-useless-fragment': 'warn',
// Disallow React being marked as unused
// https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-uses-react.md
'react/jsx-uses-react': 'warn',
// Warn if a `key` is set to an `index`
// https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-array-index-key.md
'react/no-array-index-key': ['error'],
// Error on invalid HTML attributes (only `rel` as of March 2022)
// https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-invalid-html-attribute.md
'react/no-invalid-html-attribute': 'error',
// Warn on usage of `class` prop instead of `className`
// https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-unknown-property.md
'react/no-unknown-property': ['warn', { ignore: ['css'] }],
// Error on creating components within components
// https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-unstable-nested-components.md
'react/no-unstable-nested-components': 'error',
// Error on unused React prop types
// https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-unused-prop-types.md
'react/no-unused-prop-types': 'warn',
// Disable rule because the new JSX transform in React 17,
// Next.js and Gatsby no longer requires the import.
// https://github.com/yannickcr/eslint-plugin-react/issues/2440#issuecomment-683433266
'react/react-in-jsx-scope': 'off',
// Warn about components that have a closing
// tag but no children
// https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/self-closing-comp.md
'react/self-closing-comp': 'warn',
// Error on passing children to void elements
// https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/void-dom-elements-no-children.md
'react/void-dom-elements-no-children': 'error',
// Warn on missing `await` within async functions
// https://eslint.org/docs/rules/require-await
'require-await': 'warn',
// Error on trojan source code attacks using bidirectional characters
// https://github.com/eslint-community/eslint-plugin-security/blob/main/docs/rules/detect-bidi-characters.md
'security/detect-bidi-characters': 'error',
// Error on child_process.exec usage with variables
// https://github.com/eslint-community/eslint-plugin-security/blob/main/docs/rules/detect-child-process.md
'security/detect-child-process': 'error',
// Error on running eval with a variable
// https://github.com/eslint-community/eslint-plugin-security/blob/main/docs/rules/detect-eval-with-expression.md
'security/detect-eval-with-expression': 'error',
// Warn on comments without a space between the `//` and the comment
// https://github.com/eslint/eslint/blob/master/docs/rules/spaced-comment.md
'spaced-comment': ['warn', 'always', { markers: ['/'] }],
// Warn on duplicate code in if / else if branches
// https://github.com/SonarSource/eslint-plugin-sonarjs/blob/master/docs/rules/no-duplicated-branches.md
'sonarjs/no-duplicated-branches': 'warn',
// Warn on identical conditions for if / else if chains
// https://github.com/SonarSource/eslint-plugin-sonarjs/blob/master/docs/rules/no-identical-conditions.md
'sonarjs/no-identical-conditions': 'warn',
// Warn on return of boolean literals inside if / else
// https://github.com/SonarSource/eslint-plugin-sonarjs/blob/master/docs/rules/prefer-single-boolean-return.md
'sonarjs/prefer-single-boolean-return': 'warn',
// Warn on usage of .map(...).flat() and recommend .flatMap()
// https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-array-flat-map.md
'unicorn/prefer-array-flat-map': 'warn',
// Warn on legacy techniques to flatten and recommend .flat()
// https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-array-flat.md
'unicorn/prefer-array-flat': 'warn',
// Warn about importing or requiring builtin modules without node: prefix
// https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-node-protocol.md
'unicorn/prefer-node-protocol': ['warn'],
// Warn about usage of substring or substr instead of slice
'unicorn/prefer-string-slice': 'warn',
// Warn about submit handler without event.preventDefault()
// https://github.com/upleveled/eslint-plugin-upleveled/blob/main/docs/rules/no-submit-handler-without-preventDefault.md
'upleveled/no-submit-handler-without-preventDefault': 'error',
// Warn about unnecessary HTML attributes
// https://github.com/upleveled/eslint-plugin-upleveled/blob/main/docs/rules/no-unnecessary-html-attributes.md
'upleveled/no-unnecessary-html-attributes': 'warn',
// Warn about unnecessary for and id attributes with inputs nested inside of labels
// https://github.com/upleveled/eslint-plugin-upleveled/blob/main/docs/rules/no-unnecessary-for-and-id.md
'upleveled/no-unnecessary-for-and-id': 'warn',
},
},
{
files: [
'app/**/layout.js',
'app/**/layout.tsx',
'app/**/page.js',
'app/**/page.tsx',
],
rules: {
// Warn on restricted syntax
'no-restricted-syntax': [
...noRestrictedSyntaxOptions,
// Warn on 'use client' usage in pages and layouts
{
selector: "ExpressionStatement > Literal[value='use client']",
message:
'Performance: avoid making pages or layouts into Client Components - instead create a new Client Component and use it in your page / layout',
},
],
},
},
{
files: ['app/**/route.js', 'app/**/route.ts'],
rules: {
// Warn on restricted syntax
'no-restricted-syntax': [
...noRestrictedSyntaxOptions,
// Warn on Route Handler function without NextResponse return type annotation
{
selector:
"FunctionDeclaration[id.name=/^(GET|POST|PUT|DELETE)$/]:not([returnType.typeAnnotation.typeName.name='Promise'][returnType.typeAnnotation.typeParameters.params.0.typeName.name='NextResponse'][returnType.typeAnnotation.typeParameters.params.0.typeParameters.params.0]):not([returnType.typeAnnotation.typeName.name='NextResponse'][returnType.typeAnnotation.typeParameters.params.0])",
message:
'Route Handler function missing return type annotation (eg. `async function PUT(request: NextRequest): Promise<NextResponse<AnimalResponseBodyPut>>`)',
},
],
},
},
];
// Only configure SafeQL if Postgres.js is installed
if (
'postgres' in
((
await import(pathToFileURL(`${process.cwd()}/package.json`).href, {
assert: { type: 'json' },
})
).default.dependencies || {})
) {
// Abort early if either of these modules are not installed
try {
import.meta.resolve('@ts-safeql/eslint-plugin');
import.meta.resolve('dotenv-safe');
} catch (error) {
throw new Error(
`SafeQL configuration failed
Please reinstall the UpLeveled ESLint Config using the instructions on https://www.npmjs.com/package/eslint-config-upleveled
${/** @type {Error} */ (error).message}
`,
);
}
// @ts-ignore 2307 (module not found) -- The import.meta.resolve() above will ensure that dotenv is available before this line by throwing if it is not available
// eslint-disable-next-line import/no-unresolved
(await import('dotenv-safe')).config();
const missingEnvVars = [
'PGHOST',
'PGUSERNAME',
'PGPASSWORD',
'PGDATABASE',
].filter((envVar) => !process.env[envVar]);
if (missingEnvVars.length > 0) {
throw new Error(
`SafeQL configuration failed
The following environment variables are not set: ${missingEnvVars.join(', ')}
`,
);
}
const firstConfig = configArray.find((config) => {
return config.languageOptions && config.plugins && config.rules;
});
if (!firstConfig || !firstConfig.plugins || !firstConfig.rules) {
throw new Error(
`SafeQL configuration failed
The UpLeveled ESLint config object does not contain all of the properties: .plugins, .rules`,
);
}
// @ts-expect-error 2307 Cannot find module '@ts-safeql/eslint-plugin' because it is not a dependency of the ESLint config
// eslint-disable-next-line import/no-unresolved
firstConfig.plugins['@ts-safeql'] = await import('@ts-safeql/eslint-plugin');
firstConfig.rules['@ts-safeql/check-sql'] = [
'error',
{
connections: [
{
databaseUrl: `postgres://${process.env.PGUSERNAME}:${process.env.PGPASSWORD}@${process.env.PGHOST}:5432/${process.env.PGDATABASE}`,
targets: [
{
tag: 'sql',
fieldTransform: 'camel',
transform: '{type}[]',
},
],
overrides: {
types: {
json: 'JsonAgg',
},
},
},
],
},
];
}
export default configArray;