@keeex/eslint-config 2.2.5 → 2.3.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.
package/README.md CHANGED
@@ -131,6 +131,13 @@ following options:
131
131
  "webapp": ["src/**", "webres/*/js/**"]
132
132
  }
133
133
  }
134
+ // "environment": "weblibrary"
135
+ {
136
+ "environments": {
137
+ "webapp": ["src/**"],
138
+ "mocha": ["src/**/*.test.*", "src/tests/**/*"]
139
+ }
140
+ }
134
141
  // "environments": "mobile"
135
142
  {
136
143
  "environments": {
package/package.json CHANGED
@@ -11,24 +11,25 @@
11
11
  }
12
12
  ],
13
13
  "dependencies": {
14
- "semver": "^7.6.3"
14
+ "prompts": "^2.4.2",
15
+ "semver": "^7.7.1"
15
16
  },
16
17
  "description": "Common eslint configuration",
17
18
  "devDependencies": {
18
- "@eslint/compat": "^1.2.4",
19
+ "@eslint/compat": "^1.2.6",
19
20
  "@eslint/js": "^9.12.0",
20
- "eslint": "^9.17.0",
21
+ "eslint": "^9.20.0",
21
22
  "eslint-import-resolver-typescript": "^3.7.0",
22
23
  "eslint-import-resolver-webpack": "^0.13.10",
23
24
  "eslint-plugin-import-x": "^4.6.1",
24
25
  "eslint-plugin-mocha": "^10.5.0",
25
26
  "eslint-plugin-promise": "^7.2.1",
26
- "eslint-plugin-react": "^7.37.3",
27
+ "eslint-plugin-react": "^7.37.4",
27
28
  "eslint-plugin-react-hooks": "^5.1.0",
28
29
  "eslint-plugin-tsdoc": "^0.4.0",
29
30
  "globals": "^15.14.0",
30
- "prettier": "^3.4.2",
31
- "typescript-eslint": "^8.19.0"
31
+ "prettier": "^3.5.0",
32
+ "typescript-eslint": "^8.24.0"
32
33
  },
33
34
  "files": [
34
35
  "prettier.config.js",
@@ -112,5 +113,5 @@
112
113
  "test": "echo No test for this project"
113
114
  },
114
115
  "type": "module",
115
- "version": "2.2.5"
116
+ "version": "2.3.0"
116
117
  }
@@ -12,4 +12,5 @@ if (!fs.existsSync(eslintFile)) {
12
12
  }
13
13
  const eslintConfig = (await import(eslintFile)).default;
14
14
  const JSON_INDENT = 2;
15
+
15
16
  console.log(JSON.stringify(eslintConfig, null, JSON_INDENT));
@@ -4,10 +4,13 @@ import * as fs from "node:fs";
4
4
  import * as path from "node:path";
5
5
  import process from "node:process";
6
6
 
7
+ import prompts from "prompts";
8
+
7
9
  import * as deps from "../dependencies.js";
8
10
  import {setDepCheck} from "../environ.js";
9
11
 
10
12
  const getEslintConfig = () => path.resolve(process.cwd(), "eslint.config.js");
13
+
11
14
  const depsCheck = async () => {
12
15
  console.group("eslint dependencies checking…");
13
16
  try {
@@ -43,22 +46,159 @@ const depsCheck = async () => {
43
46
  console.groupEnd();
44
47
  }
45
48
  };
49
+
46
50
  const eslintRcCandidates = [".js", ".cjs", ".json"];
51
+
47
52
  const getEslintrcPath = () => {
48
53
  for (const candidate of eslintRcCandidates) {
49
54
  const eslintrcPath = path.join(process.cwd(), `.eslintrc${candidate}`);
50
55
  if (fs.existsSync(eslintrcPath)) return eslintrcPath;
51
56
  }
52
57
  };
58
+
53
59
  const deleteLine = "DELETE THIS LINE WHEN CONFIGURED";
60
+
54
61
  const defaultConfig = `
55
62
  // ${deleteLine}
56
63
  import eslintConfig from "@keeex/eslint-config";
57
64
 
58
65
  export default await eslintConfig({});
59
66
  `.trim();
67
+
68
+ const getOptionsFromTargetFilter = (target) => {
69
+ switch (target) {
70
+ case "js":
71
+ return {
72
+ haveMocha: "maybe",
73
+ haveReact: false,
74
+ };
75
+ case "node":
76
+ return {
77
+ haveMocha: "maybe",
78
+ haveReact: "maybe",
79
+ };
80
+ case "browser":
81
+ return {
82
+ haveMocha: "maybe",
83
+ haveReact: "maybe",
84
+ };
85
+ case "react-native":
86
+ return {
87
+ haveMocha: false,
88
+ haveReact: true,
89
+ };
90
+ }
91
+ throw new Error("Unexpected state");
92
+ };
93
+
94
+ const getBooleanPrompt = async (message) => {
95
+ const replyValue = await prompts({
96
+ initial: true,
97
+ message,
98
+ name: "value",
99
+ type: "toggle",
100
+ });
101
+ return replyValue.value;
102
+ };
103
+
104
+ const getOptionsFromTarget = async (target) => {
105
+ let {haveMocha, haveReact} = await getOptionsFromTargetFilter(target);
106
+ if (haveReact === "maybe") haveReact = await getBooleanPrompt("Use React?");
107
+ if (haveMocha === "maybe") haveMocha = await getBooleanPrompt("Use Mocha?");
108
+ return {haveReact, haveMocha};
109
+ };
110
+
111
+ const getAvailableEnv = (target, haveMocha, haveReact) => {
112
+ switch (target) {
113
+ case "js":
114
+ if (haveMocha) return ["library"];
115
+ return [];
116
+ case "node":
117
+ if (haveReact) return ["webservice", "node", "none"];
118
+ return ["node"];
119
+ case "browser":
120
+ return ["webapp", "weblibrary"];
121
+ case "react-native":
122
+ return ["mobile"];
123
+ }
124
+ throw new Error("Unexpected state");
125
+ };
126
+
127
+ const getEnvTitle = (envName) => {
128
+ switch (envName) {
129
+ case "webservice":
130
+ return "Webservice (server + webapp)";
131
+ case "webapp":
132
+ return "Webapp only";
133
+ case "weblibrary":
134
+ return "Library for browsers only";
135
+ case "mobile":
136
+ return "React-native mobile app";
137
+ case "library":
138
+ return "Pure JavaScript library";
139
+ case "node":
140
+ return "NodeJS application";
141
+ case "none":
142
+ return "Do not pick an environment";
143
+ }
144
+ throw new Error("Unexpected state");
145
+ };
146
+
147
+ const getEnvFromTarget = async (target, haveMocha, haveReact) => {
148
+ const availableEnv = getAvailableEnv(target, haveMocha, haveReact);
149
+ if (availableEnv.length === 0) return null;
150
+ if (availableEnv.length === 1) return availableEnv[0];
151
+ const choice = await prompts({
152
+ choices: availableEnv.map((e) => ({title: getEnvTitle(e), value: e})),
153
+ message: "Target environment?",
154
+ name: "value",
155
+ type: "select",
156
+ });
157
+ if (!choice.value) return null;
158
+ return choice.value;
159
+ };
160
+
161
+ const genConfig = (targetEnv, mocha, react) => {
162
+ const configRows = [];
163
+ if (targetEnv && targetEnv !== "none") {
164
+ configRows.push(`"environments": ${JSON.stringify(targetEnv)}`);
165
+ }
166
+ configRows.push(`"mocha": ${JSON.stringify(mocha)}`);
167
+ configRows.push(`"react": ${JSON.stringify(react)}`);
168
+ configRows.push('"typescript": true');
169
+ return `
170
+ import eslintConfig from "@keeex/eslint-config";
171
+
172
+ export default await eslintConfig({
173
+ ${configRows.map((c) => ` ${c},`).join("\n")}
174
+ });
175
+ `.trim();
176
+ };
177
+
178
+ /** Generate a new base config based on a few questions. */
179
+ const getNewConfig = async () => {
180
+ const generalTarget = await prompts({
181
+ choices: [
182
+ {title: "Generic JavaScript", value: "js"},
183
+ {title: "NodeJS", value: "node"},
184
+ {title: "Browser", value: "browser"},
185
+ {title: "React Native", value: "react-native"},
186
+ ],
187
+ message: "General target environment",
188
+ name: "value",
189
+ type: "select",
190
+ });
191
+ const target = generalTarget.value;
192
+ if (!target) return null;
193
+ const {haveMocha, haveReact} = await getOptionsFromTarget(target);
194
+ const targetEnv = await getEnvFromTarget(target, haveMocha, haveReact);
195
+ return genConfig(targetEnv, haveMocha, haveReact);
196
+ };
197
+
198
+ const enforceNewline = (str) => (str.endsWith("\n") ? str : `${str}\n`);
199
+
60
200
  /** Return true if the flat config system is ok */
61
- const checkEslintConfig = () => {
201
+ const checkEslintConfig = async () => {
62
202
  console.group("Checking eslint config file…");
63
203
  try {
64
204
  const eslintrcPath = getEslintrcPath();
@@ -77,11 +217,15 @@ const checkEslintConfig = () => {
77
217
  return false;
78
218
  }
79
219
  if (!fs.existsSync(eslintConfigPath)) {
80
- console.log(
81
- `- No ${eslintConfigPath} found. Generating empty config. Please configure it appropriately.`,
82
- );
83
- fs.writeFileSync(eslintConfigPath, `${defaultConfig}\n`);
84
- return false;
220
+ console.log(`- No ${eslintConfigPath} found. Generating new config.`);
221
+ const configContent = await getNewConfig();
222
+ if (configContent === null) {
223
+ console.log(" Default config file generated. You'll have to edit it manually.");
224
+ fs.writeFileSync(eslintConfigPath, enforceNewline(defaultConfig));
225
+ return false;
226
+ }
227
+ fs.writeFileSync(eslintConfigPath, enforceNewline(configContent));
228
+ return true;
85
229
  }
86
230
  const configContent = fs.readFileSync(eslintConfigPath, "utf8");
87
231
  if (configContent.indexOf(deleteLine) !== -1) {
@@ -99,7 +243,9 @@ const checkEslintConfig = () => {
99
243
  console.groupEnd();
100
244
  }
101
245
  };
246
+
102
247
  const PRETTIER_CONFIG = "prettier.config.js";
248
+
103
249
  const prettierSetup = () => {
104
250
  console.group("Checking prettier config");
105
251
  try {
@@ -120,6 +266,7 @@ export default config;
120
266
  console.groupEnd();
121
267
  }
122
268
  };
269
+
123
270
  const checkTsConfig = () => {
124
271
  const needTsConfig = deps.needDependencies("typescript-eslint");
125
272
  if (!needTsConfig) return;
@@ -132,10 +279,22 @@ const checkTsConfig = () => {
132
279
  console.groupEnd();
133
280
  }
134
281
  };
282
+
283
+ const checkProjectType = () => {
284
+ const packageContent = JSON.parse(fs.readFileSync("package.json", "utf8"));
285
+ if (packageContent.type !== "module") {
286
+ console.error("package.json type is not module.");
287
+ return false;
288
+ }
289
+ return true;
290
+ };
291
+
135
292
  const main = async () => {
136
293
  console.group("KeeeX eslint and prettier configuration setup");
137
294
  try {
138
- const configOk = checkEslintConfig();
295
+ const typeOk = checkProjectType();
296
+ if (!typeOk) return;
297
+ const configOk = await checkEslintConfig();
139
298
  if (!configOk) return;
140
299
  await prettierSetup();
141
300
  await depsCheck();
@@ -4,6 +4,7 @@ import * as pathutils from "../pathutils.js";
4
4
  import * as sections from "../sections.js";
5
5
 
6
6
  const base = {builtin: true, es2025: true};
7
+
7
8
  /** Create the actual eslint globals object from user input */
8
9
  const getGlobalsFromConfig = (configGlobals) => {
9
10
  const res = {};
@@ -19,6 +20,7 @@ const getGlobalsFromConfig = (configGlobals) => {
19
20
  if (configGlobals?.custom) Object.assign(res, configGlobals.custom);
20
21
  return res;
21
22
  };
23
+
22
24
  const addEnv = ({configResult, eslintConfig}, name, fileTypes, globalsEsm, globalsCjs) => {
23
25
  const envDirs = pathutils.getEnvDirectories(name, eslintConfig.environments);
24
26
  if (envDirs.length === 0) return;
@@ -57,6 +59,7 @@ const addEnv = ({configResult, eslintConfig}, name, fileTypes, globalsEsm, globa
57
59
  getGlobalsFromConfig({...(globalsCjs ?? globalsEsm), commonjs: true}),
58
60
  );
59
61
  };
62
+
60
63
  const addNodeEnv = (configResult, eslintConfig) => {
61
64
  addEnv(
62
65
  {configResult, eslintConfig},
@@ -66,15 +69,19 @@ const addNodeEnv = (configResult, eslintConfig) => {
66
69
  {nodeCjs: true, worker: true},
67
70
  );
68
71
  };
72
+
69
73
  const addWebappEnv = (configResult, eslintConfig) => {
70
74
  addEnv({configResult, eslintConfig}, "webapp", {jsx: true}, {browser: true, serviceworker: true});
71
75
  };
76
+
72
77
  const addMobileEnv = (configResult, eslintConfig) => {
73
78
  addEnv({configResult, eslintConfig}, "mobile", {jsx: true}, {browser: true});
74
79
  };
80
+
75
81
  const addMochaEnv = (configResult, eslintConfig) => {
76
82
  addEnv({configResult, eslintConfig}, "mocha", {}, {mocha: true});
77
83
  };
84
+
78
85
  export const apply = (configResult, eslintConfig) => {
79
86
  const sharedGlobals = eslintConfig.globals.find((c) => c.files === undefined) ?? {globals: {}};
80
87
  const sharedSection = sections.getNamedSection(configResult, "keeex/shared");
@@ -2,6 +2,7 @@ import eslintPluginImportX from "eslint-plugin-import-x";
2
2
 
3
3
  import * as pathutils from "../pathutils.js";
4
4
  import * as sections from "../sections.js";
5
+
5
6
  /**
6
7
  * Apply the import-x configs
7
8
  *
@@ -5,6 +5,7 @@ import {getFilesEnv} from "../pathutils.js";
5
5
  import * as sections from "../sections.js";
6
6
 
7
7
  import {getReactFullConfig} from "./reactfullconfig.js";
8
+
8
9
  // eslint-disable-next-line max-lines-per-function
9
10
  export const apply = (configResult, eslintConfig) => {
10
11
  const reactCfg = getReactFullConfig(eslintConfig.react);
@@ -6,6 +6,7 @@ import tseslint from "typescript-eslint";
6
6
  import * as sections from "../sections.js";
7
7
 
8
8
  const filterForFiles = (rules, files) => rules.map((c) => ({...c, files}));
9
+
9
10
  /**
10
11
  * Apply the recommended typescript-eslint configuration plus KeeeX tweaks.
11
12
  *
package/src/defaults.js CHANGED
@@ -1,5 +1,6 @@
1
1
  /** List of ignored patterns by default */
2
2
  export const ignores = ["lib", "web", "gen", "src/gen"];
3
+
3
4
  /** Default globals affected to all projects */
4
5
  export const globals = [
5
6
  {globals: {builtin: true, es2025: true}},
@@ -9,5 +10,6 @@ export const globals = [
9
10
  {files: ["*.cjs"], globals: {nodeCjs: true}},
10
11
  {files: ["src/tests/**/*", "src/**/*.test.*"], globals: {mocha: true}},
11
12
  ];
13
+
12
14
  /** Import cycle max depth */
13
15
  export const cycleMaxDepth = true;
@@ -6,8 +6,10 @@ import * as path from "node:path";
6
6
  import {satisfies} from "semver";
7
7
 
8
8
  import {getReactFullConfig} from "./config/reactfullconfig.js";
9
+
9
10
  /** name => {version: string, force: boolean} */
10
11
  const requiredDependencies = {};
12
+
11
13
  /** List of dependencies no longer used and that should be removed */
12
14
  const removedDependencies = [
13
15
  "@typescript-eslint/eslint-plugin",
@@ -18,8 +20,11 @@ const removedDependencies = [
18
20
  "eslint-plugin-import",
19
21
  "eslint-plugin-react-native",
20
22
  ];
23
+
21
24
  let pkgJson;
25
+
22
26
  export const needDependencies = (name) => name in requiredDependencies;
27
+
23
28
  /**
24
29
  * Retrieve the current project's "package.json".
25
30
  *
@@ -36,6 +41,7 @@ export const getPkgJson = () => {
36
41
  }
37
42
  return pkgJson;
38
43
  };
44
+
39
45
  /** Get installed package version */
40
46
  const getInstalledVersion = (name) => {
41
47
  try {
@@ -47,6 +53,7 @@ const getInstalledVersion = (name) => {
47
53
  return "<unknown>";
48
54
  }
49
55
  };
56
+
50
57
  /**
51
58
  * Check if a particular dependency is installed in the project.
52
59
  *
@@ -60,6 +67,7 @@ const dependencyStatus = (name) => {
60
67
  const version = installed === "missing" ? undefined : getInstalledVersion(name);
61
68
  return {installed, version};
62
69
  };
70
+
63
71
  /**
64
72
  * Add an NPM dependency to the list
65
73
  *
@@ -70,6 +78,7 @@ const dependencyStatus = (name) => {
70
78
  export const addDependency = (depName, version) => {
71
79
  requiredDependencies[depName] = {version: version ?? true, force: false};
72
80
  };
81
+
73
82
  /**
74
83
  * Run a process, and display the output if an error occured.
75
84
  *
@@ -90,6 +99,7 @@ const runProcess = (cmd, ...args) => {
90
99
  }
91
100
  return true;
92
101
  };
102
+
93
103
  /**
94
104
  * List all missing/extra dependencies.
95
105
  *
@@ -119,6 +129,7 @@ export const listDependencies = () => {
119
129
  console.groupEnd();
120
130
  }
121
131
  };
132
+
122
133
  /**
123
134
  * Run the required installation/removal.
124
135
  *
@@ -150,6 +161,7 @@ export const installAndRemoveDeps = () => {
150
161
  }
151
162
  return true;
152
163
  };
164
+
153
165
  /** Add all dependencies needed by the provided config */
154
166
  export const configToDependencies = (eslintConfig) => {
155
167
  addDependency("eslint", "9.x");
package/src/environ.js CHANGED
@@ -2,5 +2,6 @@
2
2
  export const setDepCheck = () => {
3
3
  process.env.KEEEX_DEPCHECK = "true";
4
4
  };
5
+
5
6
  /** Check the depcheck flag */
6
7
  export const isDepCheck = () => process.env.KEEEX_DEPCHECK === "true";
package/src/index.js CHANGED
@@ -4,6 +4,7 @@ import * as defaults from "./defaults.js";
4
4
  import {configToDependencies} from "./dependencies.js";
5
5
  import * as environ from "./environ.js";
6
6
  import {clearConfig} from "./sections.js";
7
+
7
8
  /** Setup all defaults in the eslintParams config */
8
9
  const configDefaults = (eslintParams) => ({
9
10
  environments: eslintParams?.environments ?? "node",
@@ -15,6 +16,7 @@ const configDefaults = (eslintParams) => ({
15
16
  react: eslintParams?.react ?? false,
16
17
  typescript: eslintParams?.typescript ?? true,
17
18
  });
19
+
18
20
  /**
19
21
  * Build the eslint configuration from the provided settings.
20
22
  *
package/src/pathutils.js CHANGED
@@ -2,21 +2,25 @@ const asArray = (value) => {
2
2
  if (Array.isArray(value)) return value;
3
3
  return [value];
4
4
  };
5
+
5
6
  const envShorthands = {
6
7
  library: {mocha: ["src/**/*.test.*", "src/tests/**/*"], node: ""},
7
8
  mobile: {mobile: "src/**"},
8
9
  node: {node: ["", "src/**"], mocha: ["src/**/*.test.*", "src/tests/**/*"]},
9
10
  webapp: {webapp: ["src/**", "webres/*/js/**"]},
11
+ weblibrary: {webapp: "src/**", mocha: ["src/**/*.test.*", "src/tests/**/*"]},
10
12
  webservice: {
11
13
  mocha: ["src/**/*.test.*", "src/tests/**/*"],
12
14
  node: ["", "bin/**", "src/bin/**", "src/server/**"],
13
15
  webapp: ["src/webapp/**", "webres/*/js/**"],
14
16
  },
15
17
  };
18
+
16
19
  const getEffectiveEnv = (configEnv) => {
17
20
  if (typeof configEnv !== "string") return configEnv;
18
21
  return envShorthands[configEnv];
19
22
  };
23
+
20
24
  /**
21
25
  * @param {Array<string>|string} environments - List of environments to pull
22
26
  * @param {Array<string>|string} configEnv - List of configured environments
@@ -30,6 +34,7 @@ export const getEnvDirectories = (environments, configEnv, defaultDir) => {
30
34
  if (dirs.length === 0 && defaultDir) return [defaultDir];
31
35
  return dirs;
32
36
  };
37
+
33
38
  export const getExtensions = (fileTypes) => {
34
39
  const result = [];
35
40
  const esm = fileTypes.esm ?? true;
@@ -48,6 +53,7 @@ export const getExtensions = (fileTypes) => {
48
53
  }
49
54
  return result;
50
55
  };
56
+
51
57
  /** Configuration to build a filter list */
52
58
  // interface FilesDefinition {
53
59
  // /** Directories where the files are; no recursion */
@@ -74,6 +80,7 @@ export const getExtensions = (fileTypes) => {
74
80
  // };
75
81
  // }
76
82
  const extPlaceholder = ".ext";
83
+
77
84
  export const getFiles = (definitions) => {
78
85
  const result = new Set();
79
86
  for (const definition of asArray(definitions)) {
@@ -106,6 +113,7 @@ export const getFiles = (definitions) => {
106
113
  }
107
114
  return Array.from(result);
108
115
  };
116
+
109
117
  /** Get a list of file glob depending on config and requested file types */
110
118
  export const getFilesEnv = (eslintConfig, environments, filePatterns, fileTypes, defaultDir) => {
111
119
  const effectiveFileTypes = fileTypes
package/src/sections.js CHANGED
@@ -15,6 +15,7 @@ export const getNamedSection = (configResult, name) => {
15
15
  configResult.push(newSection);
16
16
  return newSection;
17
17
  };
18
+
18
19
  /**
19
20
  * Add a property in an object on the provided section.
20
21
  *
@@ -37,6 +38,7 @@ export const sectionAddOption = (configSection, optionGroup, optionName, value)
37
38
  configSection[optionGroup][optionName] = value;
38
39
  }
39
40
  };
41
+
40
42
  /** Merge/create the rules property */
41
43
  export const configureRules = (configSection, prefix, rules) => {
42
44
  let prefixed = {};
@@ -47,6 +49,7 @@ export const configureRules = (configSection, prefix, rules) => {
47
49
  }
48
50
  configSection.rules = {...configSection.rules, ...prefixed};
49
51
  };
52
+
50
53
  /** Remove the `_kxconfig` property from all sections and return a suitable object. */
51
54
  export const clearConfig = (configResult) => {
52
55
  const emptySectionsId = [];