@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
@@ -0,0 +1,979 @@
1
+ /**
2
+ * @typedef { import('eslint').Linter.ConfigOverride.files } ConfigOverrideFiles
3
+ */
4
+
5
+ const fs = require("fs");
6
+ const os = require("os");
7
+ const cp = require("child_process");
8
+ const cds = require("@sap/cds");
9
+
10
+ const semver = require("semver");
11
+ const path = require("path");
12
+ const { mkdirp } = require("@sap/cds/lib/utils");
13
+ const { SourceCode } = require("eslint");
14
+
15
+ const { hasDebugFlag, isValidFile, isVSCodeEditor } = require("./helpers");
16
+ const { DEFAULT_RULE_CATEGORY, DEFAULT_RULE_SEVERITY, DEFAULT_RULE_TYPE } = require("../constants");
17
+
18
+ const {
19
+ Cache,
20
+ getAST,
21
+ getLastLine,
22
+ initRootModel,
23
+ updateModel,
24
+ compileModelFromFile,
25
+ isNewConfigPath,
26
+ isFileInModel,
27
+ hasFileChanged,
28
+ getLocation,
29
+ getRange,
30
+ loadConfigPath,
31
+ } = require("./model");
32
+
33
+ const { isValidModel } = require("./validate");
34
+ const { exit } = require("process");
35
+
36
+ const JSONC = require("./jsonc");
37
+ const IS_WIN = os.platform() === "win32";
38
+ const REGEX_COMMENT_START = "(/\\*|(.+)?//)(\\s?)+eslint-";
39
+ const REGEX_COMMENTS = `${REGEX_COMMENT_START}(enable|disable)(-next)?(-line)?(.+)?`;
40
+
41
+ function doReport(cdscontext, reportDescriptor, d) {
42
+ const retouchLocations = (descriptor) => {
43
+ if (d) {
44
+ descriptor.loc = descriptor.loc || cdscontext.cds.getLocation(d.name, d);
45
+ descriptor.file = descriptor.file || (d.$location ? d.$location.file : "unknown.cds");
46
+ }
47
+ };
48
+
49
+ switch (typeof reportDescriptor) {
50
+ case "string":
51
+ reportDescriptor = { message: reportDescriptor };
52
+ retouchLocations(reportDescriptor);
53
+ cdscontext.report(reportDescriptor);
54
+ break;
55
+ case "object":
56
+ if (!Array.isArray(reportDescriptor)) {
57
+ retouchLocations(reportDescriptor);
58
+ cdscontext.report(reportDescriptor);
59
+ } else {
60
+ reportDescriptor.forEach((x) => {
61
+ if (typeof x === "string") {
62
+ x = { message: x };
63
+ }
64
+ retouchLocations(x);
65
+ cdscontext.report(x);
66
+ });
67
+ }
68
+ break;
69
+ }
70
+ }
71
+
72
+ function reportCompilationErr(meta, node, cdscontext, err) {
73
+ const lint = { err: true };
74
+ const name = err.constructor.name;
75
+ if (err.messages) {
76
+ lint.message = `${name}: ${err.message}`;
77
+ // const text = err.message.split(/CDS Compilation failed\s+/, "");
78
+ err.messages.forEach((msg) => {
79
+ if (msg.severity === "Error") {
80
+ meta.severity = 2;
81
+ lint.file = msg.location.file;
82
+ lint.message = `${name}: ${msg}`;
83
+ lint.filePath = cdscontext.filePath;
84
+ return {
85
+ meta,
86
+ create: cdscontext.report(lint),
87
+ };
88
+ }
89
+ });
90
+ }
91
+ }
92
+
93
+ function reportErr(meta, node, cdscontext, err) {
94
+ const lint = { err: true };
95
+ lint.err = true;
96
+ if (hasDebugFlag() && !isVSCodeEditor()) {
97
+ lint.message = err.stack;
98
+ meta.severity = 2;
99
+ return {
100
+ meta,
101
+ create: cdscontext.report(lint),
102
+ };
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Expands CDS context object with some CDS properties
108
+ * We also retrieve the file contents cached by the preprocessor
109
+ * @param {RuleContext} context
110
+ * @param {RuleNode} node
111
+ * @returns cdscontext
112
+ */
113
+ function addCDSContext(context, node) {
114
+ const filePath = (context.filePath = context.getPhysicalFilename());
115
+ const configPath = !Cache.has("test") ? loadConfigPath(filePath) : path.dirname(filePath);
116
+ let sourcecode = context.getSourceCode();
117
+ const code = sourcecode.getText(node) || Cache.get(`file:${filePath}`);
118
+ if (code) {
119
+ sourcecode = new SourceCode(code, getAST(code));
120
+ }
121
+ const options = context.options;
122
+ const id = context.id;
123
+ return {
124
+ _context: context,
125
+ report: module.exports.reportProxy(context.report),
126
+ cds: module.exports.cdsProxy(cds, { code, filePath, configPath, id, options }),
127
+ id,
128
+ code,
129
+ sourcecode,
130
+ options,
131
+ filePath,
132
+ configPath,
133
+ };
134
+ }
135
+
136
+ /**
137
+ * Wrapper for ESLint's Rule creator:
138
+ * https://eslint.org/docs/developer-guide/working-with-rules
139
+ * - Must follow the ESLint prescribed convention for all rule exports
140
+ * - ESLint uses 'create' function to traverse its AST nodes
141
+ * - Since we do not work with an AST for cds models, a dummy 'Programm'
142
+ * node is used as an entry point
143
+ * - For all ESLint rules, we have two entry points for additional checks:
144
+ * 1. Before ESLint's report via context.report()
145
+ * (see getProxyReport())
146
+ * - More eslint-like API
147
+ * - More convenience re error reports
148
+ * @param {CDSRuleSpec} spec
149
+ * @returns {RuleModule}
150
+ */
151
+ function createRule(spec) {
152
+ const { meta, create } = spec;
153
+
154
+ if (!meta.type) meta.type = DEFAULT_RULE_TYPE;
155
+ if (!meta.severity) meta.severity = DEFAULT_RULE_SEVERITY;
156
+ if (meta.docs && !meta.docs.category) meta.docs.category = DEFAULT_RULE_CATEGORY;
157
+
158
+ return {
159
+ meta,
160
+ create: (context) => ({
161
+ Program: function (node) {
162
+ const cdscontext = addCDSContext(context, node, meta);
163
+ const lintWithCDSLinter = isValidFile(cdscontext.filePath, 'FILES');
164
+
165
+ if (lintWithCDSLinter || Cache.has("test") ) {
166
+ try {
167
+ const { report, ...ruleDescriptors } = cdscontext;
168
+ const handlers = create({ ...ruleDescriptors, report: (r) => report(r) });
169
+
170
+ // Report descriptors with fake visitor 'all'
171
+ // Used for environment rules and rules which require another compiled model
172
+ // (i.e. sql or odata)
173
+ if (handlers.all) {
174
+ let reportDescriptor = handlers.all();
175
+ doReport(cdscontext, reportDescriptor);
176
+ } else {
177
+ // TODO: Use external address
178
+ // Report descriptors with visitors using using `any.is()`
179
+ // https://pages.github.tools.sap/cap/docs/node.js/cds-reflect
180
+ if (cdscontext.cds.model) {
181
+ cdscontext.cds.model.forall((d) =>
182
+ Object.entries(handlers)
183
+ .filter(([type, lazy]) => d.is(type))
184
+ .forEach(([lazy, handler]) => doReport(cdscontext, handler(d), d))
185
+ );
186
+ }
187
+ }
188
+ if (Cache.has(`errRootModel`)) {
189
+ reportCompilationErr(meta, node, cdscontext, Cache.get('errRootModel'));
190
+ }
191
+ } catch (err) {
192
+ // Report errors in ESLint style
193
+ if (err.messages) {
194
+ // Always show model compile errors
195
+ reportCompilationErr(meta, node, cdscontext, err);
196
+ } else {
197
+ // Thrown errors are only shown on console with --debug
198
+ reportErr(meta, node, cdscontext, err);
199
+ }
200
+ }
201
+ }
202
+ },
203
+ }),
204
+ };
205
+ }
206
+
207
+ /**
208
+ * Checks whether a lint rule has been disabled by eslint-disable
209
+ * comments at a given location
210
+ * @param entry lint report
211
+ * @param cdscontext cds context object
212
+ * @param rules all availabe rules
213
+ * @returns boolean
214
+ */
215
+
216
+ function isRuleDisabled(entry, cdscontext) {
217
+ let isDisabled = false;
218
+ if (entry.loc && entry.loc.start) {
219
+ const line = entry.loc.start.line;
220
+ if (cdscontext) {
221
+ const rulesDisabled = _getDisabled(cdscontext.code, cdscontext.sourcecode, line);
222
+ const id = cdscontext.id;
223
+ isDisabled = line && id in rulesDisabled && rulesDisabled[id] === "off";
224
+ }
225
+ }
226
+ return isDisabled;
227
+ }
228
+
229
+ /**
230
+ * Turns rules "on" or "off" for given line according to eslint-disable
231
+ * comments:
232
+ * 1. Reads code string and extracts a list of comments (in order)
233
+ * 2. Initiates rulesDisabled array with all rules "on" by default
234
+ * 3. Switches rules "off" (or "on" again) based on disable comment
235
+ * @param code current code
236
+ * @param sourcecode source code object to get index from
237
+ * @param line current code line to analyze
238
+ * @returns rules dictionary with rules being either 'on' and 'off'
239
+ */
240
+ function _getDisabled(code, sourcecode, line) {
241
+ const listDisabled = [];
242
+ let { listEnvRules, listModelRules, listRules } = Cache.get("rulesInfo");
243
+ const rulesDisabled = listRules.reduce((o, key) => ({ ...o, [key]: "on" }), {});
244
+ let matches = [];
245
+ if (code) {
246
+ matches = [...code.matchAll(REGEX_COMMENTS)];
247
+ if (matches.length > 0) {
248
+ matches.forEach((match) => {
249
+ if (match) {
250
+ const index = match.index;
251
+ match = match[0];
252
+ if (match.includes("*/")) {
253
+ match = match.split("*/")[0].replace("/*", "");
254
+ } else if (match.includes("//")) {
255
+ match = match.split("//")[1];
256
+ }
257
+ if (match) {
258
+ match = match.trim();
259
+ }
260
+ ["disable", "enable"].forEach((keyword) => {
261
+ const loc = sourcecode.getLocFromIndex(index);
262
+ const disableType = match.split(" ")[0];
263
+ let disableRules = match.split(`${disableType} `)[1];
264
+ disableRules = disableRules
265
+ ? disableRules.split(",").map((rule) => rule.trim())
266
+ : listEnvRules.concat(listModelRules).map((rule) => `@sap/cds/${rule}`);
267
+ let comment = {};
268
+ if ([`eslint-${keyword}`, `eslint-${keyword}-line`, `eslint-${keyword}-next-line`].includes(disableType)) {
269
+ comment = disableType.includes("-next-line")
270
+ ? {
271
+ lineComment: loc.line,
272
+ lineDisabled: loc.line + 1,
273
+ rules: disableRules,
274
+ type: keyword,
275
+ }
276
+ : {
277
+ lineComment: loc.line,
278
+ lineDisabled: loc.line,
279
+ rules: disableRules,
280
+ type: keyword,
281
+ };
282
+ if (!disableType.includes("-line")) {
283
+ comment.lineDisabled = "EOF";
284
+ }
285
+ }
286
+ listDisabled.push(comment);
287
+ });
288
+ }
289
+ });
290
+ for (const el of listDisabled.filter(
291
+ (d) => d.lineComment > line && (d.lineDisabled === "EOF" || d.lineDisabled === line)
292
+ )) {
293
+ if (el.lineDisabled === "EOF") {
294
+ el.lineDisabled = getLastLine(code);
295
+ }
296
+ if (el.rules) {
297
+ el.rules.forEach((rule) => {
298
+ if (el.type === "disable") {
299
+ rulesDisabled[rule] = "off";
300
+ } else if (el.type === "enable") {
301
+ rulesDisabled[rule] = "on";
302
+ }
303
+ });
304
+ }
305
+ }
306
+ }
307
+ }
308
+ return rulesDisabled;
309
+ }
310
+
311
+ module.exports = {
312
+ /**
313
+ * Gets value for a given key in allowed keys of ESLint's meta data
314
+ * @param {string} text meta object from rule
315
+ * @param {string} key key to get value for
316
+ * @returns Value for given key
317
+ */
318
+ getKeyFromMeta: function (text, key) {
319
+ const regexQuote = new RegExp(`${key}:[\\s]+[\\', \\\`, \\"]`, "gm");
320
+ const matchQuote = regexQuote.exec(text);
321
+ if (matchQuote) {
322
+ const quote = matchQuote[0].slice(-1);
323
+ const exprStart = `${key}:[\\s]+\\${quote}`;
324
+ const exprEnd = `(\\${quote},,?)`;
325
+ const regexKey = new RegExp(`${exprStart}[\\s\\S]*?${exprEnd}`, "gm");
326
+ const matchKey = regexKey.exec(text);
327
+ if (matchKey) {
328
+ const regexStart = new RegExp(`${exprStart}`, "gm");
329
+ const regexEnd = new RegExp(`${exprEnd}`, "gm");
330
+ return matchKey[0]
331
+ .replace(regexStart, "")
332
+ .replace(regexEnd, "")
333
+ .replace("fixable:", "")
334
+ .replace(/\\/gm, "")
335
+ .trim();
336
+ } else {
337
+ return "";
338
+ }
339
+ } else {
340
+ const regexBoolean = new RegExp(`${key}:[\\s]+true[\\s]?,`, "gm");
341
+ const matchBoolean = regexBoolean.exec(text);
342
+ if (matchBoolean) {
343
+ if (matchBoolean[0].includes("true,")) {
344
+ return true;
345
+ } else {
346
+ return false;
347
+ }
348
+ }
349
+ return "";
350
+ }
351
+ },
352
+
353
+ getPackageVersion: function (registry) {
354
+ let version;
355
+ let result;
356
+ try {
357
+ result = cp
358
+ .execSync(`npm show @sap/eslint-plugin-cds --@sap:registry=${registry} --json`, {
359
+ cwd: process.cwd(),
360
+ shell: IS_WIN,
361
+ stdio: "pipe",
362
+ })
363
+ .toString();
364
+ } catch (err) {
365
+ console.err(`Failed to connect to ${registry} - check your connection and try again.`);
366
+ exit(0);
367
+ }
368
+ version = JSON.parse(result)["version"];
369
+ if (!version) {
370
+ console.err(`Failed to get latest plugin version from ${registry} - check your connection and try again.`);
371
+ exit(0);
372
+ }
373
+ return version;
374
+ },
375
+
376
+ /**
377
+ * Gets value for a given key in allowed keys for input of runRuleTester api
378
+ * @param {string} text test input for ruleTester
379
+ * @param {string} key key to get value for
380
+ * @returns Value for given key
381
+ */
382
+ getKeyFromTest: function (text, key) {
383
+ let result = "";
384
+ if (["root", "rule", "filename", "parser"].includes(key)) {
385
+ const regexTestKey = new RegExp(`${key}:.*$`, "gm");
386
+ const matchTestKey = regexTestKey.exec(text);
387
+ if (matchTestKey) {
388
+ const quote = matchTestKey[0].replace(",", "").slice(-1);
389
+ const regexTestValue = new RegExp(`${quote}[\\s\\S]*?(\\${quote},?)`, "gm");
390
+ const matchValue = regexTestValue.exec(matchTestKey[0]);
391
+ if (matchValue) {
392
+ const regex = new RegExp(`${quote},`, "gm");
393
+ const regex2 = new RegExp(`${quote}`, "gm");
394
+ result = matchValue[0].replace(regex, "").replace(regex2, "");
395
+ }
396
+ }
397
+ } else if (key === "errors") {
398
+ const regexTestKey = new RegExp(`${key}:.*$(([\\s]+.+)+])?`, "gm");
399
+ const matchTestKey = regexTestKey.exec(text);
400
+ if (matchTestKey) {
401
+ result = matchTestKey[0];
402
+ }
403
+ } else if (key === "data") {
404
+ const regexTestKey = new RegExp(`${key}:.*}`, "gm");
405
+ const matchTestKey = regexTestKey.exec(text);
406
+ if (matchTestKey) {
407
+ result = matchTestKey[0];
408
+ }
409
+ } else {
410
+ result = `No parameter \\'${key}\\' found in ruleTest`;
411
+ }
412
+ return result;
413
+ },
414
+
415
+ /**
416
+ * Generates overview table of all rules based on rule dictionary.
417
+ * @param ruleDict
418
+ * @param release
419
+ * @param table
420
+ * @returns Markdown table
421
+ */
422
+ genMdRules: function (ruleDict, release, table = true) {
423
+ let mdRules = `# @sap/eslint-plugin-cds [latest]\n\n`;
424
+ if (table) {
425
+ mdRules += `Rules in ESLint are grouped by type to help you understand their purpose. Each rule has emojis denoting:\n\n`;
426
+ mdRules += `✔️ if the plugin's "recommended" configuration enables the rule\n\n`;
427
+ mdRules += `🔧 if problems reported by the rule are automatically fixable (\`--fix\`)\n\n`;
428
+ mdRules += `💡 if problems reported by the rule are manually fixable (editor)\n\n`;
429
+ if (!release) {
430
+ mdRules += `🚧 if rule exists in plugin (main branch) but is not yet released (artifactory)\n\n`;
431
+ mdRules += "| | | | | | | |\n";
432
+ mdRules += "|:-:|:-:|:-:|:-:|-:|:-|:-|\n";
433
+ } else {
434
+ mdRules += "| | | | | | | |\n";
435
+ mdRules += "|:-:|:-:|:-:|:-:|-:|:-|:-|\n";
436
+ }
437
+ /* eslint-disable-next-line no-unused-vars */
438
+ Object.entries(ruleDict).forEach(([, rules]) => {
439
+ rules.forEach(function (rule) {
440
+ mdRules += release
441
+ ? `| ${rule.recommended} | ${rule.fixable} | ${rule.hasSuggestions} | |   | [${rule.name}](Rules-released.md#${rule.name}) | ${rule.details}|\n`
442
+ : `| ${rule.recommended} | ${rule.fixable} | ${rule.hasSuggestions} | ${rule.construction} |   | [${rule.name}](Rules.md#${rule.name}) | ${rule.details}|\n`;
443
+ });
444
+ });
445
+ mdRules += "\n";
446
+ }
447
+ return mdRules;
448
+ },
449
+
450
+ /**
451
+ * Generates markdown documentation files for:
452
+ * - Overview of all rules in form of markdown table (RuleList)
453
+ * - List of all rules details in form of markdown page (Rules)
454
+ * If used internally within the @sap/eslint-plugin-cds, this
455
+ * also generates 'released' files, which only contain information
456
+ * on rules published until the currently released version.
457
+ * @param ruleDict
458
+ * @param docsPath
459
+ * @param release
460
+ */
461
+ genDocFiles: function (ruleDict, docsPath, release = false) {
462
+ let suffix = "";
463
+ if (release) {
464
+ suffix = "-released";
465
+ }
466
+ const ruleDocsPath = path.join(docsPath, `Rules${suffix}.md`);
467
+ const ruleListDocsPath = path.join(docsPath, `RuleList${suffix}.md`);
468
+
469
+ if (!fs.existsSync(ruleDocsPath)) {
470
+ fs.writeFileSync(ruleDocsPath, "", "utf8");
471
+ }
472
+ if (!fs.existsSync(ruleListDocsPath)) {
473
+ fs.writeFileSync(ruleListDocsPath, "", "utf8");
474
+ }
475
+ const mdRulesCur = fs.readFileSync(ruleDocsPath, "utf8");
476
+ const mdRuleListCur = fs.readFileSync(ruleListDocsPath, "utf8");
477
+
478
+ // Get rules table
479
+ const mdRuleList = module.exports.genMdRules(ruleDict, release, true);
480
+
481
+ // Get rule details
482
+ let mdRules = module.exports.genMdRules(ruleDict, release, false);
483
+ /* eslint-disable-next-line no-unused-vars */
484
+ Object.entries(ruleDict).forEach(([category, rules]) => {
485
+ rules.forEach(function (rule) {
486
+ mdRules += `${rule.contents}\n\n${rule.sources}\n\n---\n\n`;
487
+ });
488
+ });
489
+
490
+ if (mdRuleListCur !== mdRuleList || mdRulesCur !== mdRules) {
491
+ fs.writeFileSync(ruleDocsPath, mdRules, "utf8");
492
+ fs.writeFileSync(ruleListDocsPath, mdRuleList, "utf8");
493
+ }
494
+ },
495
+
496
+ /**
497
+ * Generates custom rules documentation (markdown files)
498
+ * for user according to contents of:
499
+ * - Rule files
500
+ * - Test files (with valid/invalid/fixed examples)
501
+ * @param {string} projectPath
502
+ * @param {string} customRulesDir
503
+ */
504
+ async genDocs(projectPath, customRulesDir, registry, prepareRelease = false) {
505
+ let docsPath, rulePath, testPath, release;
506
+
507
+ if (!projectPath) {
508
+ docsPath = path.join(__dirname, "../../docs");
509
+ rulePath = path.join(__dirname, "../rules");
510
+ testPath = path.join(__dirname, "../../test/rules");
511
+ release = JSON.parse(fs.readFileSync(path.join(__dirname, "../../package.json"))).version;
512
+ } else {
513
+ docsPath = path.join(projectPath, `${customRulesDir}/docs`);
514
+ rulePath = path.join(projectPath, `${customRulesDir}/rules`);
515
+ testPath = path.join(projectPath, `${customRulesDir}/tests`);
516
+ await Promise.all(
517
+ [docsPath, rulePath, testPath].filter((path) => !fs.existsSync(path)).map((path) => mkdirp(path))
518
+ );
519
+ }
520
+
521
+ if (registry) {
522
+ // Get rules (internal on artifactory)
523
+ const versionInternal = prepareRelease
524
+ ? JSON.parse(fs.readFileSync(path.join(__dirname, "../../package.json"))).version
525
+ : module.exports.getPackageVersion(registry);
526
+ if (versionInternal) {
527
+ console.log(`Updating internal rules from v>=${versionInternal}:\n${registry}\n`);
528
+ const ruleDictInternal = module.exports.getRuleDict(docsPath, rulePath, testPath, versionInternal);
529
+ module.exports.genDocFiles(ruleDictInternal, docsPath);
530
+ }
531
+ // Get rules released (external on npm)
532
+ const npmRegistry = "https://registry.npmjs.org";
533
+ const versionExternal = prepareRelease
534
+ ? JSON.parse(fs.readFileSync(path.join(__dirname, "../../package.json"))).version
535
+ : module.exports.getPackageVersion(npmRegistry);
536
+ if (versionExternal) {
537
+ console.log(`Updating external rules from v>=${versionExternal}:\n${npmRegistry}\n`);
538
+ const ruleDictExternal = module.exports.getRuleDict(docsPath, rulePath, testPath, versionExternal, release);
539
+ module.exports.genDocFiles(ruleDictExternal, docsPath, release);
540
+ }
541
+ } else {
542
+ // Get "custom" rules
543
+ const ruleDict = module.exports.getRuleDict(docsPath, rulePath, testPath);
544
+ module.exports.genDocFiles(ruleDict, docsPath);
545
+ }
546
+ console.log("Done!");
547
+ },
548
+
549
+ getRuleDict: function (docsPath, rulePath, testPath, versionRequired = "0.0.0", release = false) {
550
+ let mdRule, mdRuleSources, mdRuleContents;
551
+ const ruleDict = {};
552
+ fs.readdirSync(rulePath).filter((file) => {
553
+ if (path.extname(file).toLowerCase() === ".js" && file !== "index.js") {
554
+ const rule = path.basename(file).replace(path.extname(file), "");
555
+ const ruleTestPath = path.join(testPath, rule, "rule.test.js");
556
+
557
+ // Get rule meta information
558
+ const ruleMeta = require(path.join(rulePath, file)).meta;
559
+ const version = ruleMeta.docs.version;
560
+
561
+ if ((release && semver.satisfies(version, `<=${versionRequired}`)) || !release) {
562
+ const details = ruleMeta.docs.description;
563
+ const category = ruleMeta.docs.category;
564
+ const fixable = ruleMeta.fixable;
565
+ const messages = ruleMeta.messages;
566
+ const recommended = ruleMeta.docs.recommended;
567
+ const suggestions = ruleMeta.hasSuggestions;
568
+
569
+ let underConstruction = "";
570
+ if (!release && (version === "TBD" || semver.satisfies(version, `>${versionRequired}`))) {
571
+ underConstruction = "🚧";
572
+ console.log(` > 🚧 Rule '${rule}' still under construction.\n`);
573
+ }
574
+
575
+ const isFixable = ["code", "whitespace"].includes(fixable) ? "🔧" : "";
576
+ const isRecommended = recommended === true ? "✔️" : "";
577
+ const hasSuggestions = suggestions === true ? "💡" : "";
578
+
579
+ const ruleDictEntry = {
580
+ name: rule,
581
+ details,
582
+ recommended: isRecommended,
583
+ fixable: isFixable,
584
+ hasSuggestions,
585
+ construction: underConstruction,
586
+ messages,
587
+ version: version,
588
+ };
589
+ mdRule = module.exports.getRuleExamples(ruleTestPath, testPath, ruleDictEntry);
590
+ mdRuleContents = "";
591
+
592
+ mdRuleContents +=
593
+ !release && underConstruction
594
+ ? `## ${rule}\n<span class='shifted'>${underConstruction}&nbsp;&nbsp;<span class='label'>${category}</span></span>\n\n`
595
+ : `## ${rule}\n<span class='shifted label'>${category}</span>\n\n`;
596
+
597
+ mdRuleContents += `### Rule Details\n${details}\n\n`;
598
+ if (mdRule) {
599
+ mdRuleContents += `### Examples\n${mdRule}\n\n`;
600
+ }
601
+ mdRuleContents += `### Version\nThis rule was introduced in \`@sap/eslint-plugin-cds ${version}\`.\n\n`;
602
+ mdRuleSources = `### Resources\n[Rule & Documentation source](${path
603
+ .relative(docsPath, path.join(rulePath, `${rule}.js`))
604
+ .replace(/\\/g, "/")})\n\n`;
605
+
606
+ ruleDictEntry.contents = mdRuleContents;
607
+ ruleDictEntry.sources = mdRuleSources;
608
+ if (Object.keys(ruleDict).includes(category)) {
609
+ ruleDict[category].push(ruleDictEntry);
610
+ } else {
611
+ ruleDict[category] = [
612
+ {
613
+ name: rule,
614
+ details,
615
+ recommended: isRecommended,
616
+ fixable: isFixable,
617
+ hasSuggestions,
618
+ version: version,
619
+ contents: mdRuleContents,
620
+ sources: mdRuleSources,
621
+ construction: underConstruction,
622
+ },
623
+ ];
624
+ }
625
+ }
626
+ }
627
+ });
628
+ return ruleDict;
629
+ },
630
+
631
+ getRuleExamples: function (ruleTestPath, testPath, ruleDictEntry) {
632
+ // Get rule valid/invalid tests
633
+ let mdRule = "";
634
+ if (fs.existsSync(ruleTestPath)) {
635
+ const ruleTest = fs.readFileSync(ruleTestPath, "utf8");
636
+ const filename = module.exports.getKeyFromTest(ruleTest, "filename");
637
+ let errorsString = module.exports.getKeyFromTest(ruleTest, "errors");
638
+ const re = /(\S+):/gm;
639
+ errorsString = errorsString.replace(re, `"$&`).replace(/:/gm, '":').replace(/`/gm, '"');
640
+ const errors = JSONC.parse(`{${errorsString}}`).errors;
641
+ const valid = fs.readFileSync(path.join(testPath, ruleDictEntry.name, "valid", filename), "utf8");
642
+ let invalid = fs.readFileSync(path.join(testPath, ruleDictEntry.name, "invalid", filename), "utf8");
643
+ const insertAt = (str, sub, pos) => `${str.slice(0, pos)}${sub}${str.slice(pos)}`;
644
+ let errorsSorted = [];
645
+ errors.forEach((err) => {
646
+ if (errorsSorted.length === 0) {
647
+ errorsSorted = [err];
648
+ } else {
649
+ const errLast = errorsSorted[errorsSorted.length - 1];
650
+ if (err.line > errLast.line) {
651
+ errorsSorted.push(err);
652
+ } else if (err.line < errLast.line) {
653
+ errorsSorted.unshift(err);
654
+ } else {
655
+ if (err.column > errLast.column) {
656
+ errorsSorted.push(err);
657
+ } else if (err.line < errLast.line) {
658
+ errorsSorted.unshift(err);
659
+ } else {
660
+ errorsSorted.push(err);
661
+ }
662
+ }
663
+ }
664
+ });
665
+ errorsSorted.reverse().forEach((err, i) => {
666
+ if (err.messageId) {
667
+ let msg = ruleDictEntry.messages[err.messageId];
668
+ let data;
669
+ if (errorsSorted[i].suggestions && errorsSorted[i].suggestions[0]) {
670
+ data = errorsSorted[i].suggestions[0].data;
671
+ }
672
+ if (data) {
673
+ Object.keys(data).forEach((d) => {
674
+ msg = msg.replace(`{{${d}}}`, data[d]);
675
+ });
676
+ }
677
+ err.message = msg;
678
+ }
679
+ const msg = err.message.replace(/"/gm, "`");
680
+ if (err.line) {
681
+ const code = invalid.split("\n");
682
+ code[err.line - 1] = insertAt(code[err.line - 1], "</i></b></span>", err.endColumn - 1);
683
+ code[err.line - 1] = insertAt(
684
+ code[err.line - 1],
685
+ `<span style="display:inline-block; position:relative; color:red; border-bottom:2pt dotted red" title="${msg}"><b><i>`,
686
+ err.column - 1
687
+ );
688
+ invalid = code.join("\n");
689
+ }
690
+ });
691
+
692
+ mdRule +=
693
+ `<span>✔️&nbsp;&nbsp; Example of ` +
694
+ `<span style="color:green">correct</span> ` +
695
+ `code for this rule:</span>\n\n<pre><code>\n${valid}\n</code></pre>\n\n`;
696
+ mdRule +=
697
+ `<span>❌&nbsp;&nbsp; Example of ` +
698
+ `<span style="color:red">incorrect</span> ` +
699
+ `code for this rule:</span>\n\n<pre><code>\n${invalid}\n</code></pre>`;
700
+ }
701
+ return mdRule;
702
+ },
703
+
704
+ /**
705
+ * Gets all plugin rules and stores contents for later use in isRuleDisabled()
706
+ * @param {*} dirname rules dirname
707
+ * @param {*} rulename optional rule name (for single rule unit tests with RuleTester)
708
+ * @returns rule object with sources and rule lists
709
+ */
710
+ getRules: function (dirname, rulename) {
711
+ let rulesInfo;
712
+ if (Cache.has("rulesInfo")) {
713
+ rulesInfo = Cache.get("rulesInfo");
714
+ } else {
715
+ const rules = {};
716
+ const listEnvRules = [];
717
+ const listModelRules = [];
718
+
719
+ if (rulename) {
720
+ const file = `${rulename}.js`;
721
+
722
+ let rule = createRule(require(path.join(dirname, file)));
723
+ rules[rulename] = rule;
724
+
725
+ if (!listEnvRules.includes(rulename) && !isValidModel(file, "model")) {
726
+ listEnvRules.push(rulename);
727
+ }
728
+ if (!listModelRules.includes(rulename) && isValidModel(file, "model")) {
729
+ listModelRules.push(rulename);
730
+ }
731
+ } else {
732
+ fs.readdirSync(dirname).forEach((file) => {
733
+ if (path.extname(file) === ".js") {
734
+ const rulename = file.replace(".js", "");
735
+
736
+ let rule = createRule(require(path.join(dirname, file)));
737
+ rules[rulename] = rule;
738
+
739
+ if (!listEnvRules.includes(rulename) && !isValidModel(file, "model")) {
740
+ listEnvRules.push(rulename);
741
+ }
742
+ if (!listModelRules.includes(rulename) && isValidModel(file, "model")) {
743
+ listModelRules.push(rulename);
744
+ }
745
+ }
746
+ });
747
+ }
748
+ const listRules = listEnvRules.concat(listModelRules);
749
+
750
+ const recommended = Object.assign(
751
+ {},
752
+ ...Object.entries(rules)
753
+ .filter(([, v]) => v.meta.docs.recommended)
754
+ .map(([k, v]) => ({ [`@sap/cds/${k}`]: v.meta.severity }))
755
+ );
756
+
757
+ const all = Object.assign({}, ...Object.entries(rules).map(([k, v]) => ({ [`@sap/cds/${k}`]: v.meta.severity })));
758
+ rulesInfo = { sources: rules, all, recommended, listRules, listEnvRules, listModelRules };
759
+ Cache.set("rulesInfo", rulesInfo);
760
+ }
761
+ return rulesInfo;
762
+ },
763
+
764
+ // populateRules: function (context, customRulesDir) {
765
+ // const configPath = Cache.get("configpath") || "";
766
+ // // Allow for custom rules
767
+ // if (configPath) {
768
+ // let customRulesPath = path.join(Cache.get("configpath"), customRulesDir, "rules");
769
+ // let customRulesInfo;
770
+ // if (fs.existsSync(customRulesPath)) {
771
+ // customRulesInfo = module.exports.getRules(customRulesPath);
772
+ // Cache.set("rulesInfo", {
773
+ // listEnvRules: context.listEnvRules.concat(customRulesInfo.listEnvRules),
774
+ // listModelRules: context.listModelRules.concat(customRulesInfo.listModelRules),
775
+ // listRules: context.listRules.concat(customRulesInfo.listRules),
776
+ // });
777
+ // }
778
+ // }
779
+ // },
780
+
781
+ /**
782
+ * Generates proxy for `@sap/cds` object which adds:
783
+ * - Extra properties (model, environment, etc.)
784
+ * - Option to cache function calls (apply)
785
+ * @param {cds} object
786
+ * @returns Proxy for cds
787
+ */
788
+ cdsProxy: function (cds, { code, filePath, configPath, id, options }) {
789
+ const handler = {
790
+ get(target, prop, receiver) {
791
+ let value;
792
+ switch (prop) {
793
+ case "model":
794
+ value = module.exports.getModel(code, filePath, configPath, id, cds);
795
+ break;
796
+ case "environment":
797
+ value = module.exports.getEnvironment(options);
798
+ break;
799
+ case "getLocation":
800
+ value = getLocation;
801
+ break;
802
+ case "getRange":
803
+ value = getRange;
804
+ break;
805
+ default:
806
+ break;
807
+ }
808
+ if (value) {
809
+ return value;
810
+ } else {
811
+ value = Reflect.get(target, prop, receiver);
812
+ if (value && typeof value == "object") {
813
+ value = new Proxy(value, handler);
814
+ }
815
+ return value;
816
+ }
817
+ },
818
+ apply(target, thisArg, argumentsList) {
819
+ // NOTE: Possible to add caching for expensive function calls
820
+ // here as the rule set grows further
821
+ const result = Reflect.apply(target, this, argumentsList);
822
+ return result;
823
+ },
824
+ };
825
+ return new Proxy(cds, handler);
826
+ },
827
+ /**
828
+ * Generates proxy for ESLint's context object which adds caching
829
+ * @param {CDSRuleReport} ESLint's context object
830
+ * @returns {Rule.ReportDescriptor}
831
+ */
832
+ reportProxy: function (ruleReport) {
833
+ const handler = {
834
+ get(target, prop, receiver) {
835
+ const value = Reflect.get(target, prop, receiver);
836
+ if (typeof value !== "object") {
837
+ return value;
838
+ }
839
+ if (value) {
840
+ return new Proxy(value, handler);
841
+ }
842
+ return {
843
+ err: `Property ${prop} prop does not exist on object ${ruleReport}!`,
844
+ };
845
+ },
846
+ apply(target, thisArg, argumentsList) {
847
+ let report = false;
848
+ if (argumentsList.length > 0) {
849
+ argumentsList.forEach((lint) => {
850
+ if (lint) {
851
+ // Do not consider disabled content
852
+ if (!isRuleDisabled(lint, thisArg)) {
853
+ const isModelLint = lint.file && isValidFile(lint.file, "MODEL_FILES") && !lint.err;
854
+ if (isModelLint && module.exports.isDedicatedFile(lint, thisArg)) {
855
+ if (isVSCodeEditor()) {
856
+ report = true;
857
+ } else {
858
+ if (module.exports.isReportUnique(lint, "modelReports")) {
859
+ report = true;
860
+ }
861
+ }
862
+ }
863
+ if (!lint.loc) {
864
+ lint.loc = module.exports.addDefaultLoc();
865
+ }
866
+ if (
867
+ !isModelLint &&
868
+ !lint.err &&
869
+ module.exports.isReportUnique(lint, "envReports", thisArg.configPath)
870
+ ) {
871
+ report = true;
872
+ }
873
+ if (lint.err && (lint.file || module.exports.isReportUnique(lint, "errReports", thisArg.configPath))) {
874
+ report = true;
875
+ }
876
+ if (report) {
877
+ return thisArg._context.report(lint);
878
+ }
879
+ }
880
+ }
881
+ });
882
+ }
883
+ },
884
+ };
885
+ return new Proxy(ruleReport, handler);
886
+ },
887
+
888
+ resolveFilePath: (file) => (path.isAbsolute(file) ? file : path.join(Cache.get("configpath"), file)),
889
+
890
+ isDedicatedFile: (lint, thisArg) =>
891
+ module.exports.resolveFilePath(lint.file) === thisArg.filePath || lint.file === "<stdin>.cds",
892
+
893
+ isReportUnique: function (lint, name, uniqueness) {
894
+ let report = false;
895
+ if (!uniqueness) {
896
+ uniqueness = JSON.stringify(lint);
897
+ }
898
+ if (!Cache.has(name) && uniqueness) {
899
+ const lintString = `${uniqueness}:${JSON.stringify(lint)}`;
900
+ Cache.set(name, [lintString]);
901
+ report = true;
902
+ } else {
903
+ if (uniqueness) {
904
+ const lintMessages = Cache.has(name) ? Cache.get(name) : [];
905
+ const lintString = `${uniqueness}:${JSON.stringify(lint)}`;
906
+ if (!lintMessages.includes(lintString)) {
907
+ lintMessages.push(lintString);
908
+ Cache.set(name, lintMessages);
909
+ report = true;
910
+ }
911
+ }
912
+ }
913
+ return report;
914
+ },
915
+
916
+ addDefaultLoc: () => ({
917
+ start: { line: 0, column: -1 },
918
+ end: { line: 0, column: -1 },
919
+ }),
920
+
921
+ getModel: function (code, filePath, configPath) {
922
+ let model;
923
+
924
+ if (Cache.has("test")) {
925
+ return Cache.get(`model:${configPath}`);
926
+ }
927
+
928
+ if (!Cache.has(`model:${configPath}`)) {
929
+ const isValidPluginFile = isValidFile(filePath, "FILES");
930
+
931
+ if (isValidPluginFile) {
932
+ model = initRootModel(configPath);
933
+ if (module.exports.isParkedModelFile(filePath, configPath)) {
934
+ return compileModelFromFile(code, filePath);
935
+ } else if (model) {
936
+ return model;
937
+ }
938
+ }
939
+ } else {
940
+ const isValidModelFile = isValidFile(filePath, "MODEL_FILES");
941
+
942
+ if (module.exports.isParkedModelFile(filePath, configPath)) {
943
+ return compileModelFromFile(code, filePath);
944
+ } else if (isValidModelFile) {
945
+ const hasRootChanged = isNewConfigPath(configPath);
946
+ const fileChanged = hasFileChanged(code, filePath, configPath);
947
+
948
+ if (hasRootChanged || fileChanged) {
949
+ if (hasRootChanged) {
950
+ Cache.remove("envReports");
951
+ }
952
+ Cache.remove("modelReports");
953
+ Cache.remove("errReports");
954
+ model = updateModel(code, filePath, configPath);
955
+ } else {
956
+ model = Cache.get(`model:${configPath}`);
957
+ }
958
+ } else {
959
+ model = Cache.get(`model:${configPath}`);
960
+ }
961
+ return model;
962
+ }
963
+ },
964
+
965
+ isParkedModelFile: (filePath, configPath) =>
966
+ isValidFile(filePath, "MODEL_FILES") && !isFileInModel(filePath, configPath),
967
+
968
+ getEnvironment: function (options) {
969
+ let environment;
970
+ if (options) {
971
+ const hasEnvTestCases = options && options[0] && options[0].environment;
972
+ if (hasEnvTestCases) {
973
+ environment = options[0].environment;
974
+ }
975
+ }
976
+ return environment;
977
+ },
978
+ createRule,
979
+ };