@arnaud-barre/tsl-config 0.1.0

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 (5) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +115 -0
  3. package/index.d.ts +11 -0
  4. package/index.js +226 -0
  5. package/package.json +16 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Arnaud Barré (https://github.com/ArnaudBarre)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,115 @@
1
+ # @arnaud-barre/tsl-config [![npm](https://img.shields.io/npm/v/@arnaud-barre/tsl-config)](https://www.npmjs.com/package/@arnaud-barre/tsl-config)
2
+
3
+ Ongoing port of https://github.com/ArnaudBarre/eslint-config for https://github.com/ArnaudBarre/tsl
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ bun add -D tsl @arnaud-barre/tsl-config
9
+ ```
10
+
11
+ ```js
12
+ // tsl.config.ts
13
+ import { allRules } from "@arnaud-barre/tsl-config";
14
+ import { defineConfig } from "tsl";
15
+
16
+ export default defineConfig({
17
+ rules: [...allRules],
18
+ });
19
+ ```
20
+
21
+ ```json
22
+ // package.json
23
+ "scripts": {
24
+ "tsc": "tsl"
25
+ }
26
+ ```
27
+
28
+ ## TS config (5.8)
29
+
30
+ ### Web project
31
+
32
+ ```json
33
+ {
34
+ "include": ["**/*.ts", "**/*.tsx"],
35
+ "compilerOptions": {
36
+ "target": "ES2022",
37
+ "jsx": "react-jsx",
38
+ "module": "ESNext",
39
+ "moduleDetection": "force",
40
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
41
+ "types": ["vite/client", "tsl/patches"],
42
+ "skipLibCheck": true,
43
+
44
+ /* Bundler mode */
45
+ "moduleResolution": "bundler",
46
+ "allowImportingTsExtensions": true,
47
+ "verbatimModuleSyntax": true,
48
+ "erasableSyntaxOnly": true,
49
+ "noEmit": true,
50
+
51
+ /* Linting */
52
+ "strict": true,
53
+ "noUnusedLocals": true,
54
+ "noUnusedParameters": true,
55
+ "noFallthroughCasesInSwitch": true,
56
+ "useUnknownInCatchVariables": true,
57
+ "noUncheckedSideEffectImports": true,
58
+ "noPropertyAccessFromIndexSignature": true,
59
+
60
+ "plugins": [{ "name": "tsl/plugin" }]
61
+ }
62
+ }
63
+ ```
64
+
65
+ ### Node project (20-22)
66
+
67
+ ```json
68
+ {
69
+ "include": ["**/*.ts"],
70
+ "compilerOptions": {
71
+ "target": "ES2022",
72
+ "module": "ESNext",
73
+ "moduleDetection": "force",
74
+ "lib": ["ES2023"],
75
+ "types": ["node", "tsl/patches"],
76
+ "skipLibCheck": true
77
+
78
+ /* Same as web */
79
+ }
80
+ }
81
+ ```
82
+
83
+ ## Prettier config (3.5.3)
84
+
85
+ ### Web projects
86
+
87
+ ```json
88
+ // package.json
89
+ "prettier": {
90
+ "experimentalOperatorPosition": "start",
91
+ "xmlWhitespaceSensitivity": "ignore",
92
+ "plugins": [
93
+ "@arnaud-barre/prettier-plugin-sort-imports",
94
+ "@prettier/plugin-xml"
95
+ ]
96
+ }
97
+ ```
98
+
99
+ ### Node projects
100
+
101
+ ```json
102
+ // package.json
103
+ "prettier": {
104
+ "experimentalOperatorPosition": "start",
105
+ "plugins": [
106
+ "@arnaud-barre/prettier-plugin-sort-imports"
107
+ ]
108
+ }
109
+ ```
110
+
111
+ ### Custom rules
112
+
113
+ - jsxKey: Validate JSX has key prop when in array or iterator
114
+ - arrayCallbackReturn: Ensure array callbacks that require a return value (map, filter, find, some, ...) don't have undefined in their return type
115
+ - jsxNoNumberTruthiness: Disallow `list.length && ...` in JSX
package/index.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import * as tsl0 from "tsl";
2
+
3
+ //#region src/index.d.ts
4
+ declare const arnaudBarre: tsl0.RulesSet<{
5
+ arrayCallbackReturn: (options?: "off" | undefined) => tsl0.Rule<unknown>;
6
+ jsxKey: (options?: "off" | undefined) => tsl0.Rule<unknown>;
7
+ jsxNoNumberTruthiness: (options?: "off" | undefined) => tsl0.Rule<unknown>;
8
+ }>;
9
+ declare const allRules: tsl0.Rule<unknown>[];
10
+ //#endregion
11
+ export { allRules, arnaudBarre };
package/index.js ADDED
@@ -0,0 +1,226 @@
1
+ import { core, createRulesSet, defineRule } from "tsl";
2
+ import "tsl/ruleTester";
3
+ import { SyntaxKind, TypeFlags } from "typescript";
4
+
5
+ //#region src/rules/arrayCallbackReturn.ts
6
+ const base = "Found undefined in the return type of this callback. It could come from a missing return statement.";
7
+ const messages$1 = {
8
+ shouldBeBoolean: base + " Update the code to return a boolean value.",
9
+ flatMap: base + " If this is intentional, update the code to return an array of a single value.",
10
+ addTypeAnnotation: base + " If this is intentional, add an explicit type to the function or use a disable comment."
11
+ };
12
+ const methodsRecords = {
13
+ every: "shouldBeBoolean",
14
+ some: "shouldBeBoolean",
15
+ filter: "shouldBeBoolean",
16
+ find: "shouldBeBoolean",
17
+ findLast: "shouldBeBoolean",
18
+ findLastIndex: "shouldBeBoolean",
19
+ flatMap: "flatMap",
20
+ map: "addTypeAnnotation",
21
+ reduce: "addTypeAnnotation",
22
+ reduceRight: "addTypeAnnotation"
23
+ };
24
+ const methods = Object.keys(methodsRecords);
25
+ const arrayCallbackReturn = defineRule(() => ({
26
+ name: "arnaudBarre/arrayCallbackReturn",
27
+ visitor: { PropertyAccessExpression(context, node) {
28
+ if (node.name.kind === SyntaxKind.Identifier && methods.includes(node.name.text) && node.parent.kind === SyntaxKind.CallExpression && node.parent.arguments.length >= 1) {
29
+ const callback = node.parent.arguments[0];
30
+ if (callback.kind === SyntaxKind.ArrowFunction && callback.body.kind !== SyntaxKind.Block) return;
31
+ const functionType = context.checker.getTypeAtLocation(callback);
32
+ const signatures = functionType.getCallSignatures();
33
+ if (signatures.length === 0) return;
34
+ for (const signature of signatures) {
35
+ const type = signature.getReturnType();
36
+ if (type.flags & TypeFlags.Undefined || type.isUnion() && type.types.some((t) => t.flags & TypeFlags.Undefined)) {
37
+ const messageId = methodsRecords[node.name.text];
38
+ if (messageId === "addTypeAnnotation" && node.parent.typeArguments) return;
39
+ context.report({
40
+ node: node.name,
41
+ message: messages$1[messageId]
42
+ });
43
+ }
44
+ }
45
+ }
46
+ } }
47
+ }));
48
+
49
+ //#endregion
50
+ //#region src/rules/jsxKey.ts
51
+ const reactComponentNameRE = /^[A-Z][a-zA-Z0-9]*$/u;
52
+ const messages = {
53
+ missingKey: "Missing key",
54
+ keyFirst: "Key should be first",
55
+ keySpread: "Key should not be spread",
56
+ keyInProps: "\"key\" can't be part of props"
57
+ };
58
+ const jsxKey = defineRule(() => {
59
+ const reportFragment = (node, context) => {
60
+ context.report({
61
+ message: messages.missingKey,
62
+ node: node.openingFragment
63
+ });
64
+ };
65
+ const checkElement = (node, context) => {
66
+ const openingElement = node.kind === SyntaxKind.JsxElement ? node.openingElement : node;
67
+ let keyAttr;
68
+ for (const [index, attr] of openingElement.attributes.properties.entries()) {
69
+ if (attr.kind === SyntaxKind.JsxAttribute && attr.name.kind === SyntaxKind.Identifier && attr.name.text === "key") keyAttr = {
70
+ index,
71
+ node: attr
72
+ };
73
+ if (attr.kind === SyntaxKind.JsxSpreadAttribute) {
74
+ const type = context.checker.getTypeAtLocation(attr.expression);
75
+ if (type.getProperty("key")) context.report({
76
+ message: messages.keySpread,
77
+ node: attr
78
+ });
79
+ }
80
+ }
81
+ if (keyAttr) {
82
+ if (keyAttr.index !== 0) context.report({
83
+ message: messages.keyFirst,
84
+ node: keyAttr.node
85
+ });
86
+ } else context.report({
87
+ message: messages.missingKey,
88
+ node: openingElement
89
+ });
90
+ };
91
+ const checkExpression = (node, context) => {
92
+ switch (node.kind) {
93
+ case SyntaxKind.JsxElement:
94
+ checkElement(node, context);
95
+ break;
96
+ case SyntaxKind.JsxSelfClosingElement:
97
+ checkElement(node, context);
98
+ break;
99
+ case SyntaxKind.JsxFragment:
100
+ reportFragment(node, context);
101
+ break;
102
+ case SyntaxKind.ConditionalExpression:
103
+ checkExpression(node.whenTrue, context);
104
+ checkExpression(node.whenFalse, context);
105
+ break;
106
+ case SyntaxKind.BinaryExpression:
107
+ checkExpression(node.left, context);
108
+ checkExpression(node.right, context);
109
+ break;
110
+ default: break;
111
+ }
112
+ };
113
+ const checkStatement = (node, context) => {
114
+ switch (node.kind) {
115
+ case SyntaxKind.Block:
116
+ for (const statement of node.statements) checkStatement(statement, context);
117
+ break;
118
+ case SyntaxKind.ReturnStatement:
119
+ if (node.expression) checkExpression(node.expression, context);
120
+ break;
121
+ case SyntaxKind.ExpressionStatement:
122
+ checkExpression(node.expression, context);
123
+ break;
124
+ case SyntaxKind.IfStatement:
125
+ checkStatement(node.thenStatement, context);
126
+ if (node.elseStatement) checkStatement(node.elseStatement, context);
127
+ break;
128
+ case SyntaxKind.SwitchStatement:
129
+ for (const caseClause of node.caseBlock.clauses) for (const statement of caseClause.statements) checkStatement(statement, context);
130
+ break;
131
+ default: break;
132
+ }
133
+ };
134
+ const checkIfReactComponentWithKeyInProps = (id, fnNode, context) => {
135
+ if (!reactComponentNameRE.test(id.text)) return;
136
+ if (fnNode.parameters.length === 0) return;
137
+ const type = context.checker.getTypeAtLocation(fnNode.parameters[0]);
138
+ if (type.getProperty("key")) context.report({
139
+ message: messages.keyInProps,
140
+ node: id
141
+ });
142
+ };
143
+ return {
144
+ name: "arnaudBarre/jsxKey",
145
+ visitor: {
146
+ JsxElement(context, node) {
147
+ if (node.parent.kind === SyntaxKind.ArrayLiteralExpression) checkElement(node, context);
148
+ },
149
+ JsxSelfClosingElement(context, node) {
150
+ if (node.parent.kind === SyntaxKind.ArrayLiteralExpression) checkElement(node, context);
151
+ },
152
+ JsxFragment(context, node) {
153
+ if (node.parent.kind === SyntaxKind.ArrayLiteralExpression) reportFragment(node, context);
154
+ },
155
+ CallExpression(context, node) {
156
+ if (node.expression.kind === SyntaxKind.PropertyAccessExpression && node.expression.name.kind === SyntaxKind.Identifier && (node.expression.name.text === "map" || node.expression.name.text === "mapNotNull")) {
157
+ const firstArg = node.arguments.at(0);
158
+ if (firstArg?.kind !== SyntaxKind.ArrowFunction) return;
159
+ if (firstArg.body.kind === SyntaxKind.Block) checkStatement(firstArg.body, context);
160
+ else checkExpression(firstArg.body, context);
161
+ }
162
+ },
163
+ VariableDeclaration(context, node) {
164
+ if (node.initializer?.kind !== SyntaxKind.ArrowFunction) return;
165
+ if (node.name.kind !== SyntaxKind.Identifier) return;
166
+ checkIfReactComponentWithKeyInProps(node.name, node.initializer, context);
167
+ },
168
+ FunctionDeclaration(context, node) {
169
+ if (!node.name) return;
170
+ checkIfReactComponentWithKeyInProps(node.name, node, context);
171
+ }
172
+ }
173
+ };
174
+ });
175
+
176
+ //#endregion
177
+ //#region src/rules/jsxNoNumberTruthiness.ts
178
+ const message = "Don't use logical expression on a number inside JSX, you might render the character 0 instead of rendering nothing. Either use a ternary expression or more explicit condition";
179
+ const jsxNoNumberTruthiness = defineRule(() => ({
180
+ name: "arnaudBarre/jsxNoNumberTruthiness",
181
+ visitor: { BinaryExpression(context, node) {
182
+ if (node.operatorToken.kind !== SyntaxKind.AmpersandAmpersandToken) return;
183
+ if (node.parent.kind !== SyntaxKind.JsxExpression) return;
184
+ const type = context.checker.getTypeAtLocation(node.left);
185
+ if (context.utils.typeOrUnionHasFlag(type, TypeFlags.NumberLike)) context.report({
186
+ node,
187
+ message
188
+ });
189
+ } }
190
+ }));
191
+
192
+ //#endregion
193
+ //#region src/index.ts
194
+ const arnaudBarre = createRulesSet({
195
+ arrayCallbackReturn,
196
+ jsxKey,
197
+ jsxNoNumberTruthiness
198
+ });
199
+ const allRules = [
200
+ ...core.all(),
201
+ core.preferNullishCoalescing({ ignoreIfStatements: true }),
202
+ core.noMisusedPromises({
203
+ checksConditionals: false,
204
+ checksVoidReturn: {
205
+ arguments: false,
206
+ attributes: false
207
+ }
208
+ }),
209
+ core.noConfusingVoidExpression({ ignoreArrowShorthand: true }),
210
+ core.noUnnecessaryCondition({
211
+ allowConstantLoopConditions: "only-allowed-literals",
212
+ checkTypePredicates: true
213
+ }),
214
+ core.switchExhaustivenessCheck({
215
+ allowDefaultCaseForExhaustiveSwitch: false,
216
+ considerDefaultExhaustiveForUnions: true
217
+ }),
218
+ core.strictBooleanExpressions({
219
+ allowNullableString: true,
220
+ allowNullableBoolean: true
221
+ }),
222
+ ...arnaudBarre.all()
223
+ ];
224
+
225
+ //#endregion
226
+ export { allRules, arnaudBarre };
package/package.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "@arnaud-barre/tsl-config",
3
+ "description": "TS-React focused tsl configuration",
4
+ "version": "0.1.0",
5
+ "author": "Arnaud Barré (https://github.com/ArnaudBarre)",
6
+ "license": "MIT",
7
+ "repository": "github:ArnaudBarre/tsl-config",
8
+ "type": "module",
9
+ "exports": {
10
+ ".": "./index.js"
11
+ },
12
+ "peerDependencies": {
13
+ "tsl": "^1.0.16",
14
+ "typescript": "~5.8"
15
+ }
16
+ }