@sap/eslint-plugin-cds 2.3.2 → 2.3.5

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 (44) hide show
  1. package/CHANGELOG.md +25 -50
  2. package/lib/api/index.js +11 -13
  3. package/lib/api/lint.d.ts +48 -0
  4. package/lib/constants.js +54 -0
  5. package/lib/index.js +44 -0
  6. package/lib/{impl/parser.js → parser.js} +2 -13
  7. package/lib/processor.js +47 -0
  8. package/lib/{impl/rules → rules}/assoc2many-ambiguous-key.js +50 -53
  9. package/lib/rules/latest-cds-version.js +42 -0
  10. package/lib/rules/min-node-version.js +47 -0
  11. package/lib/rules/no-db-keywords.js +46 -0
  12. package/lib/rules/no-dollar-prefixed-names.js +49 -0
  13. package/lib/{impl/rules → rules}/no-join-on-draft-enabled-entities.js +14 -11
  14. package/lib/rules/require-2many-oncond.js +27 -0
  15. package/lib/rules/sql-cast-suggestion.js +52 -0
  16. package/lib/rules/start-elements-lowercase.js +61 -0
  17. package/lib/rules/start-entities-uppercase.js +55 -0
  18. package/lib/{impl/rules → rules}/valid-csv-header.js +17 -9
  19. package/lib/{impl/utils → utils}/fuzzySearch.js +0 -0
  20. package/lib/utils/helpers.js +47 -0
  21. package/lib/{impl/utils → utils}/jsonc.js +0 -0
  22. package/lib/utils/model.js +394 -0
  23. package/lib/utils/ruleHelpers.js +56 -0
  24. package/lib/utils/ruleTester.js +79 -0
  25. package/lib/utils/rules.js +979 -0
  26. package/lib/{impl/utils → utils}/validate.js +2 -18
  27. package/package.json +2 -2
  28. package/lib/impl/constants.js +0 -30
  29. package/lib/impl/index.js +0 -63
  30. package/lib/impl/processor.js +0 -23
  31. package/lib/impl/ruleFactory.js +0 -360
  32. package/lib/impl/rules/cds-compile-error.js +0 -34
  33. package/lib/impl/rules/latest-cds-version.js +0 -51
  34. package/lib/impl/rules/min-node-version.js +0 -44
  35. package/lib/impl/rules/no-db-keywords.js +0 -38
  36. package/lib/impl/rules/require-2many-oncond.js +0 -31
  37. package/lib/impl/rules/rule.hbs +0 -20
  38. package/lib/impl/rules/sql-cast-suggestion.js +0 -52
  39. package/lib/impl/rules/start-elements-lowercase.js +0 -75
  40. package/lib/impl/rules/start-entities-uppercase.js +0 -65
  41. package/lib/impl/types.d.ts +0 -48
  42. package/lib/impl/utils/helpers.js +0 -68
  43. package/lib/impl/utils/model.js +0 -548
  44. package/lib/impl/utils/rules.js +0 -697
@@ -1,548 +0,0 @@
1
- /**
2
- * @typedef { import("eslint").AST.SourceLocation } SourceLocation
3
- */
4
-
5
- const fs = require("fs");
6
- const path = require("path");
7
- const cds = require("@sap/cds");
8
- const { SourceCode } = require("eslint");
9
- const { isValidFile } = require("./helpers");
10
- const { isValidEnv } = require("./validate");
11
-
12
- const cache = new Map();
13
-
14
- module.exports = {
15
- /**
16
- * Simple cache to store model and any cds calls made in the rule creation
17
- * api to modify the model
18
- */
19
- Cache: {
20
- has(key) {
21
- return cache.has(key);
22
- },
23
- set(key, value) {
24
- return cache.set(key, [value, Date.now()]);
25
- },
26
- get(key) {
27
- if (cache.get(key)) {
28
- return cache.get(key)[0];
29
- } else {
30
- return;
31
- }
32
- },
33
- dump() {
34
- const dump = {};
35
- for (const [key, value] of cache.entries()) {
36
- const timestamp = new Date(value[1]);
37
- dump[key] = { key, value: JSON.stringify(value[0]), timestamp };
38
- }
39
- return dump;
40
- },
41
- remove(key) {
42
- if (cache.has(key)) {
43
- cache.delete(key);
44
- }
45
- return;
46
- },
47
- clear() {
48
- cache.clear();
49
- return;
50
- },
51
- },
52
-
53
- hasModelError: function (filePath) {
54
- if (module.exports.Cache.has(`model:${filePath}`)) {
55
- const model = module.exports.Cache.get(`model:${filePath}`);
56
- if (model.err) {
57
- return true;
58
- }
59
- }
60
- return false;
61
- },
62
-
63
- /**
64
- * Checks whether the compiled cds model contains compilation errors which
65
- * should only be reported via the 'cds-compile-error' rule
66
- * @param cds cds object
67
- * @param ruleID rule name
68
- * @returns
69
- */
70
- hasCompilationError: function (context) {
71
- const cds = context.cds;
72
- const ruleID = context.ruleID;
73
- if (
74
- cds &&
75
- cds.model &&
76
- cds.model.err &&
77
- cds.model.err.message.startsWith("CDS compilation failed")
78
- ) {
79
- if (
80
- ruleID === "@sap/cds/cds-compile-error" ||
81
- ruleID === "cds-compile-error"
82
- ) {
83
- cds.model.err;
84
- return true;
85
- }
86
- }
87
- return false;
88
- },
89
-
90
- /**
91
- * Takes care of all of the cds modeling:
92
- * - Loads the model and assigns relevant files to it
93
- * - Updates the model (according to 'type' events in the editor)
94
- * - Updates the ESLint configuration file path (i.e. mono-repo with
95
- * multiple models)
96
- * @param context
97
- * @returns
98
- */
99
- populateModelAndEnv: function (context) {
100
- // Update file and config paths
101
- module.exports.Cache.set("filepath", context.filePath);
102
-
103
- // Get CDS reflected model
104
-
105
- if (
106
- process.env["LINT_FLAVOR"] !== "parsed" &&
107
- isValidFile(context.filePath, "model") &&
108
- (module.exports.isNewFile(context.filePath) ||
109
- module.exports.isNewConfigPath(context.configPath))
110
- ) {
111
- module.exports.initModel(context.configPath, context.filePath);
112
- }
113
- // Trigger model updates for:
114
- // - Changed 'model' files
115
- // - Any 'outsider' files
116
- if (
117
- isValidFile(context.filePath, "model") &&
118
- module.exports.hasFileChanged(context)
119
- ) {
120
- module.exports.updateModel(context);
121
- }
122
-
123
- // Get cds environment (for internal ruleTester)
124
- if (isValidEnv(context)) {
125
- module.exports.Cache.set("environment", context.options[0].environment);
126
- }
127
- },
128
-
129
- /**
130
- * Checks whether a file is new or has already been
131
- * part of an existing cds model
132
- * @param {*} filePath
133
- * @returns boolean
134
- */
135
- isNewFile: function (filePath) {
136
- if (!module.exports.Cache.has(`model:${filePath}`)) {
137
- return true;
138
- } else {
139
- return false;
140
- }
141
- },
142
-
143
- /**
144
- * Checks whether the path where the nearest ESLint configuration
145
- * file has changed
146
- * @param {*} configPath
147
- * @returns boolean
148
- */
149
- isNewConfigPath: function (configPath) {
150
- let update = false;
151
- if (
152
- !module.exports.Cache.has("pluginpath") &&
153
- !module.exports.Cache.has("configpath") ||
154
- configPath !== module.exports.Cache.get("configpath")
155
- ) {
156
- update = true;
157
- }
158
- return update;
159
- },
160
-
161
- /**
162
- * Gets directory of the nearest ESLint config files associated
163
- * Within this plugin, this is equivalent to the cds project's directory
164
- * @param filePath
165
- * @returns Directory of ESLint config file
166
- */
167
- loadConfigPath: function (filePath) {
168
- let configPath = path.dirname(module.exports.getConfigPath(filePath));
169
- if (configPath) {
170
- module.exports.Cache.set("projectpath", configPath);
171
- } else {
172
- throw new Error("Failed to find an ESLint configuration file!");
173
- }
174
- return configPath;
175
- },
176
-
177
- /**
178
- * Generates dummy AST with just single Program node
179
- * @param code Parse file contents
180
- * @returns AST
181
- */
182
- getAST: function (code) {
183
- return {
184
- type: "Program",
185
- body: [],
186
- sourceType: "module",
187
- tokens: [],
188
- comments: [],
189
- range: [0, code.length],
190
- loc: {
191
- start: {
192
- line: 1,
193
- column: 0,
194
- },
195
- end: {
196
- line: 1,
197
- column: 0,
198
- },
199
- },
200
- };
201
- },
202
-
203
- /**
204
- * Generates proxy for cds object which adds caching
205
- * @param obj cds object
206
- * @returns Proxy for cds
207
- */
208
- getCDSProxy: function (obj) {
209
- const handler = {
210
- get(target, prop, receiver) {
211
- const value = Reflect.get(target, prop, receiver);
212
- if (["model", "environment"].includes(prop)) {
213
- if (prop === "model") {
214
- prop = `model:${module.exports.Cache.get("filepath")}`;
215
- }
216
- return module.exports.Cache.get(prop);
217
- }
218
- if (typeof value !== "object") {
219
- return value;
220
- }
221
- /*eslint no-extra-boolean-cast: "off"*/
222
- if (!!value) {
223
- return new Proxy(value, handler);
224
- }
225
- return {
226
- err: `Property ${prop} prop does not exist on object ${obj}!`,
227
- };
228
- },
229
- apply(target, thisArg, argumentsList) {
230
- const result = Reflect.apply(target, this, argumentsList);
231
- return result;
232
- },
233
- };
234
- return new Proxy(obj, handler);
235
- },
236
-
237
- /**
238
- * Converts code with {line, column} to ESLint's 'range' property:
239
- * https://eslint.org/docs/developer-guide/working-with-custom-parsers#all-nodes
240
- * code.slice(node.range[0], node.range[1]) must be the text of the node!
241
- * @param code source code
242
- * @param line line number
243
- * @param column column number
244
- * @returns ESLint range
245
- */
246
- getRange: function (code, line, column) {
247
- let lines;
248
- if (typeof code === "string") {
249
- lines = SourceCode.splitLines(code);
250
- } else {
251
- lines = code;
252
- }
253
- const ranges = [0];
254
- lines.forEach((line, i) => {
255
- if (i === 0) {
256
- ranges[i + 1] = line.length + 1;
257
- } else {
258
- ranges[i + 1] = ranges[i] + line.length + 1;
259
- }
260
- });
261
- if (line > 1) {
262
- return ranges[line - 1] + column;
263
- } else {
264
- return column;
265
- }
266
- },
267
-
268
- /**
269
- * Uses ESLint's static function splitLines() to split the source code text
270
- * into an array of lines:
271
- * https://eslint.org/docs/developer-guide/nodejs-api#sourcecodesplitlines
272
- * Returns the index of the last line
273
- * @param code
274
- * @returns Last line index
275
- */
276
- getLastLine: function (code) {
277
- let lines;
278
- if (typeof code === "string") {
279
- lines = SourceCode.splitLines(code);
280
- } else {
281
- lines = code;
282
- }
283
- return lines.length - 1;
284
- },
285
-
286
- /**
287
- * Generates ESlint's 'loc' from artifact string and cds $location property:
288
- * https://eslint.org/docs/developer-guide/working-with-rules-deprecated#contextreport
289
- * @param name
290
- * @param {SoureLocation} obj
291
- * @returns ESLint's 'loc' object
292
- */
293
- getLocation: function (name, obj) {
294
- const loc = {
295
- start: { line: 0, column: 0 },
296
- end: { line: 1, column: 0 },
297
- };
298
- if (obj.$location) {
299
- const nameloc = obj.$location;
300
- // CSN entry with column 0 is equivalent to 'undefined'
301
- // It means that the column in that line cannot be determined,
302
- // so we assign a value 1 so as not to get a negative value
303
- if (nameloc.col === 0) {
304
- nameloc.col = 1;
305
- }
306
- loc.start.column = nameloc.col - 1;
307
- loc.start.line = nameloc.line;
308
- loc.end.column = nameloc.col - 1 + name.length;
309
- loc.end.line = nameloc.line;
310
- }
311
- return loc;
312
- },
313
-
314
- /**
315
- * Searches for ESLint config file types (in order or precedence)
316
- * and returns corresponding directory (usually project's root dir)
317
- * https://eslint.org/docs/user-guide/configuring#configuration-file-formats
318
- * @param {string} currentDir start here and search until root dir
319
- * @returns {string} dir containing ESLint config file (empty if not exists)
320
- */
321
- getConfigPath: function (currentDir = ".") {
322
- const configFiles = [
323
- ".eslintrc.js",
324
- ".eslintrc.cjs",
325
- ".eslintrc.yaml",
326
- ".eslintrc.yml",
327
- ".eslintrc.json",
328
- ".eslintrc",
329
- "package.json",
330
- ];
331
- let configDir = path.resolve(currentDir);
332
- while (configDir !== path.resolve(configDir, "..")) {
333
- for (let i = 0; i < configFiles.length; i++) {
334
- const configPath = path.join(configDir, configFiles[i]);
335
- if (fs.existsSync(configPath) && fs.statSync(configPath).isFile()) {
336
- return configPath;
337
- }
338
- }
339
- configDir = path.join(configDir, "..");
340
- }
341
- return "";
342
- },
343
-
344
- /**
345
- * Compiles reflected model for a given project directory
346
- * Note, that to support monorepos, the cache (in @sap/cds) must be cleared
347
- * to also change the roots with every changed configPath.
348
- * @param configPath
349
- * @returns reflected model
350
- */
351
- compileModelFromPath: function (configPath) {
352
- let compiledModel;
353
- let reflectedModel;
354
- cds.resolve.cache = {};
355
- const roots = cds.resolve("*", { root: configPath });
356
- if (roots) {
357
- try {
358
- compiledModel = cds.load(roots, {
359
- cwd: configPath,
360
- sync: true,
361
- locations: true,
362
- });
363
- if (compiledModel) {
364
- reflectedModel = cds.linked(compiledModel);
365
- }
366
- } catch (err) {
367
- reflectedModel = { err };
368
- }
369
- }
370
- return reflectedModel;
371
- },
372
-
373
- /**
374
- * Compiles reflected model for a dictionary of files/file contents
375
- * Note, that this method is used to account for editor type events
376
- * and hence, model updates.
377
- * WARNING: Only use if cds roots are defined prior to this step
378
- * and the dictionary is complete (the compiler will not resolve
379
- * any missing files)!
380
- * @param dictFiles
381
- * @returns reflected model
382
- */
383
- compileModelFromDict: function (dictFiles, options) {
384
- let reflectedModel;
385
- try {
386
- const compiledModel = cds.compile(dictFiles, {
387
- sync: true,
388
- locations: true,
389
- ...options,
390
- });
391
- if (compiledModel) {
392
- reflectedModel = cds.linked(compiledModel);
393
- }
394
- } catch (err) {
395
- reflectedModel = { err };
396
- }
397
- return reflectedModel;
398
- },
399
-
400
- /**
401
- * Initiates and stores new reflected model, it's corresponding project path,
402
- * as well as a list and dictionary of files comprising the model.
403
- * @param configPath
404
- * @param filePath
405
- */
406
- initModel: function (configPath, filePath) {
407
- module.exports.Cache.set("configpath", configPath);
408
- const reflectedModel = module.exports.compileModelFromPath(configPath);
409
- let files;
410
- if (reflectedModel && !reflectedModel.err && reflectedModel.$sources) {
411
- module.exports.Cache.set(`model:${filePath}`, reflectedModel);
412
- files = reflectedModel.$sources;
413
- if (files) {
414
- module.exports.Cache.set(`modelfiles:${configPath}`, files);
415
- files.forEach(file => {
416
- module.exports.Cache.set(`model:${file}`, reflectedModel);
417
- })
418
- } else {
419
- files = [];
420
- }
421
- const dictFiles = module.exports.getDictFiles(configPath, files);
422
- module.exports.Cache.set(`dictfiles:${configPath}`, dictFiles);
423
- }
424
- },
425
-
426
- initModelRuleTester: function (filePath) {
427
- const configPath = path.dirname(filePath);
428
- module.exports.Cache.set("configpath", configPath);
429
- let files = fs.readdirSync(configPath);
430
- const modelfiles = [];
431
- files.forEach((file) => {
432
- const filePath = path.join(configPath, file);
433
- if (isValidFile(filePath, "model")) {
434
- modelfiles.push(filePath);
435
- }
436
- });
437
- module.exports.Cache.set(`modelfiles:${configPath}`, files);
438
- const dictFiles = module.exports.getDictFiles(configPath, modelfiles);
439
- module.exports.Cache.set(`dictfiles:${configPath}`, dictFiles);
440
- const compiledModel = module.exports.compileModelFromDict(dictFiles);
441
- let reflectedModel;
442
- if (compiledModel) {
443
- reflectedModel = cds.linked(compiledModel);
444
- }
445
- if (reflectedModel) {
446
- module.exports.Cache.set(`model:${filePath}`, reflectedModel);
447
- }
448
- },
449
-
450
- /**
451
- * Creates or updates a dictionary of files/file contents for a given
452
- * project path.
453
- * @param configPath
454
- * @param files
455
- * @returns dictFiles
456
- */
457
- getDictFiles: function (configPath, files=[]) {
458
- let dictFiles = {};
459
- if (module.exports.Cache.has(`dictfiles:${configPath}`)) {
460
- dictFiles = module.exports.Cache.get(`dictfiles:${configPath}`);
461
- } else {
462
- files.forEach((file) => {
463
- if (module.exports.Cache.has(`file:${file}`)) {
464
- dictFiles[file] = module.exports.Cache.get(`file:${file}`);
465
- } else {
466
- dictFiles[file] = fs.readFileSync(file, "utf8");
467
- }
468
- });
469
- }
470
- return dictFiles;
471
- },
472
-
473
- /**
474
- * Determines whether an incoming file has changed contents
475
- * @param context cds context object
476
- * @returns boolean
477
- */
478
- hasFileChanged: function (context) {
479
- const files = module.exports.Cache.get(`modelfiles:${context.configPath}`);
480
- const dictFiles = module.exports.getDictFiles(context.configPath, files);
481
- // If incoming file is a 'model' file
482
- if (module.exports.isFileInModel(context, files)) {
483
- // Only update on detected changes
484
- if (dictFiles[context.filePath] !== context.code) {
485
- dictFiles[context.filePath] = context.code;
486
- module.exports.Cache.set(`dictfiles:${context.configPath}`, dictFiles);
487
- return true;
488
- }
489
- } else {
490
- if (dictFiles[context.filePath] !== context.code) {
491
- return true;
492
- }
493
- }
494
- return false;
495
- },
496
-
497
- /**
498
- * Checks whether a file is part of the model for a given project
499
- * @param context
500
- * @param files
501
- * @returns boolean
502
- */
503
- isFileInModel(filePath, files) {
504
- if (files && files.length > 0 && files.includes(filePath)) {
505
- return true;
506
- }
507
- return false;
508
- },
509
-
510
- /**
511
- * Updates and stores reflected model on file changes. Model compilation
512
- * us handled separately for 'model' files (part of model) and 'outsider'
513
- * files.
514
- * @param context cds context object
515
- */
516
- updateModel: function (context) {
517
- let reflectedModel;
518
- let files = module.exports.Cache.get(`modelfiles:${context.configPath}`);
519
- if (!files) {
520
- files = [];
521
- }
522
- // If incoming file is a 'model' file
523
- if (
524
- !process.env["LINT_FLAVOR"] === "parsed" ||
525
- module.exports.isFileInModel(context, files)
526
- ) {
527
- const dictFiles = module.exports.Cache.get(
528
- `dictfiles:${context.configPath}`
529
- );
530
- dictFiles[context.filePath] = context.code;
531
- reflectedModel = module.exports.compileModelFromDict(dictFiles, {
532
- flavor: "inferred",
533
- });
534
- files.forEach((file) => {
535
- module.exports.Cache.set(`model:${file}`, reflectedModel);
536
- });
537
- } else {
538
- // If incoming file is an 'outsider' file
539
- const dictFiles = {};
540
- dictFiles[context.filePath] = context.code;
541
- let flavor = "parsed";
542
- reflectedModel = module.exports.compileModelFromDict(dictFiles, {
543
- flavor,
544
- });
545
- module.exports.Cache.set(`model:${context.filePath}`, reflectedModel);
546
- }
547
- },
548
- };