@sap/eslint-plugin-cds 2.3.0 → 2.3.4

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 (45) hide show
  1. package/CHANGELOG.md +44 -61
  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 +387 -0
  23. package/lib/utils/ruleHelpers.js +56 -0
  24. package/lib/utils/ruleTester.js +79 -0
  25. package/lib/utils/rules.js +973 -0
  26. package/lib/{impl/utils → utils}/validate.js +2 -18
  27. package/package.json +2 -2
  28. package/lib/api/formatter.js +0 -182
  29. package/lib/impl/constants.js +0 -30
  30. package/lib/impl/index.js +0 -63
  31. package/lib/impl/processor.js +0 -23
  32. package/lib/impl/ruleFactory.js +0 -341
  33. package/lib/impl/rules/cds-compile-error.js +0 -34
  34. package/lib/impl/rules/latest-cds-version.js +0 -51
  35. package/lib/impl/rules/min-node-version.js +0 -44
  36. package/lib/impl/rules/no-db-keywords.js +0 -38
  37. package/lib/impl/rules/require-2many-oncond.js +0 -31
  38. package/lib/impl/rules/rule.hbs +0 -20
  39. package/lib/impl/rules/sql-cast-suggestion.js +0 -52
  40. package/lib/impl/rules/start-elements-lowercase.js +0 -75
  41. package/lib/impl/rules/start-entities-uppercase.js +0 -65
  42. package/lib/impl/types.d.ts +0 -48
  43. package/lib/impl/utils/helpers.js +0 -68
  44. package/lib/impl/utils/model.js +0 -554
  45. package/lib/impl/utils/rules.js +0 -678
@@ -12,7 +12,7 @@ module.exports = {
12
12
  * @returns
13
13
  */
14
14
  isValidRule: function (context, rules) {
15
- if (rules.includes(context.ruleID.replace("@sap/cds/", ""))) {
15
+ if (rules.includes(context.id.replace("@sap/cds/", ""))) {
16
16
  return true;
17
17
  }
18
18
  return false;
@@ -32,21 +32,5 @@ module.exports = {
32
32
  return true; // allow no model
33
33
  }
34
34
  return false;
35
- },
36
-
37
- /**
38
- * Checks whether a well-defined cds environment exists
39
- * @param context cds context object
40
- * @returns
41
- */
42
- isValidEnv: function (context) {
43
- if (
44
- context.options &&
45
- context.options[0] &&
46
- context.options[0].environment
47
- ) {
48
- return true;
49
- }
50
- return false;
51
- },
35
+ }
52
36
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sap/eslint-plugin-cds",
3
- "version": "2.3.0",
3
+ "version": "2.3.4",
4
4
  "description": "ESLint plugin including recommended SAP Cloud Application Programming model and environment rules",
5
5
  "homepage": "https://cap.cloud.sap/",
6
6
  "keywords": [
@@ -12,7 +12,7 @@
12
12
  ],
13
13
  "author": "SAP SE (https://www.sap.com)",
14
14
  "license": "See LICENSE file",
15
- "main": "lib/impl/index.js",
15
+ "main": "lib/index.js",
16
16
  "files": [
17
17
  "lib/",
18
18
  "CHANGELOG.md",
@@ -1,182 +0,0 @@
1
- /**
2
- * Custom ESLint formatter:
3
- * https://eslint.org/docs/developer-guide/working-with-custom-formatters
4
- * Here, we take the ESLint.LintResult[] and format it into ESLint's standard (stylish) error report.
5
- * Then, we adapt it to report environment errors:
6
- * - Separately from model errors
7
- * - Report them within a project scope but independent of a specific file within that scope
8
- */
9
- const fs = require("fs");
10
- const path = require("path");
11
- const formatter = require("eslint/lib/cli-engine/formatters/stylish");
12
-
13
- const { Cache } = require("../impl/utils/model");
14
- const { styleText, isEditor } = require("../impl/utils/helpers");
15
-
16
- const CONSTANTS = require("../impl/constants");
17
- /* eslint-disable-next-line no-control-regex */
18
- const REGEX_STRIP_ANSI = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;
19
- const REGEX_NEWLINE = /\r?\n/g;
20
-
21
- let projects = Cache.get('configpaths') || [];
22
-
23
- module.exports = function (results, data) {
24
- let output = "";
25
- // Get plugin ruleIDs
26
- const rules = getPluginRules(data);
27
- // Get ruleIDs from custom rules
28
- const customRules = [];
29
- projects.forEach((project) => {
30
- const customRulesPath = path.resolve(project, CONSTANTS.customRulesDir, "rules");
31
- if (fs.existsSync(customRulesPath)) {
32
- fs.readdirSync(customRulesPath).forEach((customRule) => {
33
- const ruleID = path.basename(customRule, ".js");
34
- if (!customRules.includes(ruleID)) {
35
- customRules.push(ruleID);
36
- }
37
- });
38
- }
39
- });
40
- if (!Cache.has("err")) {
41
- // Filter out error messages not from plugin or custom rules
42
- if (!isEditor()) {
43
- results.forEach((result) => {
44
- result.messages = result.messages.filter(
45
- (msg) =>
46
- rules.model.includes(msg.ruleId) ||
47
- rules.environment.includes(msg.ruleId) ||
48
- customRules.includes(msg.ruleId)
49
- );
50
- });
51
- }
52
- // Get standard ESLint 'stylish' output
53
- const outputStylish = formatter(results);
54
-
55
- // Split according to category
56
- const msgs = splitOutput(outputStylish, rules);
57
-
58
- // Format new CDSLint output
59
- output = formatOutput(output, msgs);
60
- }
61
- return output;
62
- };
63
-
64
- /**
65
- * Splits rules by config and category
66
- * @param data Rules meta data
67
- * @returns rules object based on category
68
- */
69
- function getPluginRules(data) {
70
- const rules = { environment: [], model: [], recommended: [] };
71
- Object.keys(data.rulesMeta).forEach((rule) => {
72
- if (data.rulesMeta[rule]) {
73
- const category = data.rulesMeta[rule].docs.category;
74
- if (category === CONSTANTS.categories.model) {
75
- rules.model.push(rule);
76
- rules.recommended.push(rule);
77
- } else if (category === CONSTANTS.categories.env) {
78
- rules.environment.push(rule);
79
- rules.recommended.push(rule);
80
- }
81
- }
82
- });
83
- return rules;
84
- }
85
-
86
- /**
87
- * Obtains ESLint's standard (*stylish*) output, then splits and reccollects error messages
88
- * based on rule category and content type (msg vs. error count/report)
89
- * @param outputStylish ESLint's standard output
90
- * @param rules Plugin rules based on category
91
- * @returns Collected msgs
92
- */
93
- function splitOutput(outputStylish, rules) {
94
- const msgs = { environment: {}, model: {}, report: [] };
95
- let file = "";
96
- outputStylish.split(REGEX_NEWLINE).forEach((line) => {
97
- const lineStripped = line.replace(REGEX_STRIP_ANSI, "");
98
- // Collect model file (default)
99
- const lineStrippedSplit = lineStripped.split(" ");
100
- const rule = lineStrippedSplit[lineStrippedSplit.length - 1];
101
- if (
102
- !lineStripped.startsWith(" ") &&
103
- !rules.recommended.includes(rule) &&
104
- !lineStripped.startsWith("✖")
105
- ) {
106
- file = line;
107
- if (process.argv[1].includes("jest") || process.argv[1].includes("mocha")) {
108
- projects = [path.dirname(lineStripped)];
109
- }
110
- } else if (rules.environment.includes(rule)) {
111
- // Collect error/warning messages from @sap/cds/ rules
112
- const delimiter = line.split(/ +/, 2)[1];
113
- const lineWithoutLocation = line.split(delimiter)[1];
114
- let project = "";
115
- for (let i = 0; i < projects.length; i++) {
116
- project = projects[i];
117
- if (file.includes(project)) {
118
- project = styleText(project, ["link"]);
119
- break;
120
- }
121
- }
122
- if (project) {
123
- if (!Object.keys(msgs.environment).includes(project)) {
124
- msgs.environment[project] = [lineWithoutLocation];
125
- } else if (!msgs.environment[project].includes(lineWithoutLocation)) {
126
- msgs.environment[project].push(lineWithoutLocation);
127
- }
128
- }
129
- } else if (
130
- lineStripped &&
131
- !rules.environment.includes(rule) &&
132
- !lineStripped.includes("potentially fixable") &&
133
- !lineStripped.startsWith("✖")
134
- ) {
135
- if (lineStripped) {
136
- if (!msgs.model[file]) {
137
- msgs.model[file] = [line];
138
- } else {
139
- msgs.model[file].push(line);
140
- }
141
- }
142
- } else if (lineStripped.startsWith("✖") || lineStripped.includes("potentially fixable")) {
143
- msgs.report.push(line);
144
- }
145
- });
146
- return msgs;
147
- }
148
-
149
- /**
150
- * Takes the collected error messages and collects them
151
- * in a final string for ESLint to output
152
- * @param output final string to output
153
- * @param msgs error messages based on category
154
- * @returns
155
- */
156
- function formatOutput(output, msgs) {
157
- // First, output model msgs per file (from ESLint 'stylish' output)
158
- for (const fileModel in msgs.model) {
159
- if (msgs.model[fileModel].length > 0) {
160
- output += `${fileModel}\n`;
161
- output += `${msgs.model[fileModel].join("\n")}\n\n`;
162
- }
163
- }
164
- // Next, output env msgs (file-independent but associated to project)
165
- for (const fileModel in msgs.environment) {
166
- if (msgs.environment[fileModel].length > 0) {
167
- output += `${fileModel}\n`;
168
- output += `${msgs.environment[fileModel].join("\n")}\n\n`;
169
- }
170
- }
171
- // Finally output error/warning report count
172
- if (output && msgs.report) {
173
- output += `${msgs.report.join("\n")}`;
174
- }
175
- if (output) {
176
- output = `\n${output}`;
177
- if (Cache.has('linted')) {
178
- output += `\n\nTotal files linted: ${Cache.get('linted').files.length}\n`;
179
- }
180
- }
181
- return output;
182
- }
@@ -1,30 +0,0 @@
1
- /**
2
- * This file contains all constants for:
3
- * - categories: The category labels we use to for model and environment rules
4
- * - customRulesDir: The custom rules directory name in the user's project home
5
- * which contains the subdirs 'docs', 'rules' and 'tests'
6
- * - globals: The globals which should be exposed to ESLint by this plugin
7
- * - files: Any additional file extensions which ESLint should lint
8
- */
9
-
10
- module.exports = {
11
- categories: {
12
- env: "Environment",
13
- model: "Model Validation",
14
- },
15
- customRulesDir: ".eslint",
16
- globals: {
17
- SELECT: true,
18
- INSERT: true,
19
- UPDATE: true,
20
- DELETE: true,
21
- CREATE: true,
22
- DROP: true,
23
- CDL: true,
24
- CQL: true,
25
- CXL: true,
26
- cds: true,
27
- },
28
- files: ["*.cds", "*.csn", "*.csv", "undeploy.json"],
29
- modelFiles: ["*.cds", "*.csn"],
30
- };
package/lib/impl/index.js DELETED
@@ -1,63 +0,0 @@
1
- /**
2
- * Custom ESLint plugin:
3
- * https://eslint.org/docs/developer-guide/working-with-plugins
4
- * This file exposes our plugins ESLint configuration, which must:
5
- * - Expose any 'configs' for prescribed rule configuration bundles
6
- * (i.e. "recommended"). See shareable configs:
7
- * https://eslint.org/docs/developer-guide/shareable-configs
8
- * - Expose any 'globals' for use in ESLint
9
- * - Expose any 'processors' for use in ESLint
10
- * - Expose any 'rules' for use in ESLint
11
- * We also initiate and cache the objects 'rulesInfo' and 'cds' for later use.
12
- */
13
-
14
- const path = require("path");
15
- const processor = require("./processor");
16
- const plugin = require("../../package.json").name;
17
-
18
- const { getRules } = require("../impl/utils/rules");
19
- const {
20
- Cache,
21
- getCDSProxy,
22
- getLocation,
23
- getRange,
24
- } = require("../impl/utils/model");
25
- const { files, globals } = require("./constants");
26
-
27
- const cds = require("@sap/cds");
28
- cds.getLocation = getLocation;
29
- cds.getRange = getRange;
30
- Cache.set("cds", getCDSProxy(cds));
31
-
32
- let rulesInfo;
33
- if (!Cache.has("rulesInfo")) {
34
- rulesInfo = getRules(path.join(__dirname, "rules"));
35
- Cache.set("rulesInfo", rulesInfo);
36
- } else {
37
- rulesInfo = Cache.get("rulesInfo");
38
- }
39
- const recommended = Object.assign({},
40
- ...Object.entries(rulesInfo.rules)
41
- .filter(([k,v]) => (v.meta.docs.recommended))
42
- .map(([k,v]) => ({ [`@sap/cds/${k}`]:v.meta.severity }))
43
- );
44
-
45
- module.exports = {
46
- configs: {
47
- recommended: {
48
- globals,
49
- plugins: [plugin],
50
- overrides: [
51
- {
52
- files: files,
53
- processor: "@sap/cds/cds",
54
- },
55
- ],
56
- rules: recommended,
57
- },
58
- },
59
- processors: {
60
- cds: processor,
61
- },
62
- rules: rulesInfo.rules,
63
- };
@@ -1,23 +0,0 @@
1
- /**
2
- * ESLint custom processor:
3
- * https://eslint.org/docs/developer-guide/working-with-plugins#processors-in-plugins
4
- * This processor is used to avoid parsing errors when this plugin is extended
5
- * in ESLint alongside other plugins, such as prettier which then also try to
6
- * read the new file types exposed via globs.
7
- * Note, that because we cache the file contents and return empty files, the
8
- * plugin's parser is not actually used and we must retrieve the file contents
9
- * later on (ruleFactory).
10
- */
11
-
12
- const { Cache } = require("./utils/model");
13
- const { isValidFile } = require("./utils/helpers");
14
-
15
- module.exports = {
16
- preprocess: function (text, filename) {
17
- if (isValidFile(filename)) {
18
- Cache.set(`file:${filename}`, text);
19
- }
20
- return [{ text: "", filename }];
21
- },
22
- supportsAutofix: true,
23
- };
@@ -1,341 +0,0 @@
1
- /**
2
- * Rule report object (as prescribed by ESLint):
3
- * https://eslint.org/docs/developer-guide/working-with-rules
4
- *
5
- * Each ESLint rule module must be composed of a 'meta', 'create' object:
6
- * - 'meta': meta data for rule (docs, fixable, etc.)
7
- * - 'create': ingests rule context and returns object with nodes to visit
8
- * while traversing the AST
9
- *
10
- * Since we want to lint cds models without an AST, we adapted the context
11
- * object to explicitly pass some additional information:
12
- * - 'category' : Rule category
13
- * - 'cds' : Proxy for cds object which also caches results
14
- * - 'code' : Code object based on ESLint getFromSourceCode()
15
- * - 'ruleID' : Rule ID ("@sap/cds/...")
16
- * - 'filePath' : ESLint's 'physical' filename
17
- * - 'options' : CDS Environment parameters
18
- * - 'report' : Proxy for ESLint's context.report() for lint filtering
19
- * - 'ruleID' : ESLint's rule ID
20
- * - 'sourcecode': ESLint's SourceCode object
21
- *
22
- * @typedef { import('eslint').Rule.RuleModule } RuleModule
23
- * @typedef { import('eslint').Rule.RuleContext } RuleContext
24
- * @typedef { import('eslint').Rule.Node } RuleNode
25
- * @typedef { import("./types").CDSRuleSpec } CDSRuleSpec
26
- * @typedef { import("./types").CDSRuleMetaData } CDSRuleMetaData
27
- * @typedef { import("./types").CDSRuleContext } CDSRuleContext
28
- * @typedef { import("./types").CDSRuleTestOpts } CDSRuleTestOpts
29
- */
30
-
31
- const fs = require("fs");
32
- const path = require("path");
33
- const { RuleTester, SourceCode } = require("eslint");
34
- const { isEditor, isValidFile } = require("./utils/helpers");
35
- const { isValidEnv, isValidModel } = require("./utils/validate");
36
- const {
37
- Cache,
38
- populateModelAndEnv,
39
- hasCompilationError,
40
- getAST,
41
- initModelRuleTester,
42
- loadConfigPath,
43
- } = require("./utils/model");
44
- const { isRuleDisabled, getRules, populateRules } = require("./utils/rules");
45
- const { customRulesDir, categories } = require("./constants");
46
-
47
- /**
48
- * Wrapper for ESLint's Rule creator:
49
- * https://eslint.org/docs/developer-guide/working-with-rules
50
- * - Must follow the ESLint prescribed convention for all rule exports
51
- * - ESLint uses 'create' function to traverse its AST nodes
52
- * - Since we do not work with an AST for cds models, a dummy 'Programm'
53
- * node is used as an entry point
54
- * - For all ESLint rules, we have two entry points for additional checks:
55
- * 1. Before ESLint's rule creation via create()
56
- * (see below)
57
- * 2. Before ESLint's report via context.report()
58
- * (see getProxyReport())
59
- * @param {CDSRuleSpec} spec
60
- * @returns {RuleModule}
61
- */
62
- function createRule(spec) {
63
- const { meta, create } = spec;
64
- return {
65
- meta,
66
- create: function (context) {
67
- return {
68
- Program: function (node) {
69
- // --- Checks before create() ---
70
- let cdscontext = createCDSContext(context, node, meta);
71
- // 1. Is file exension allowed?
72
- // (i.e. when using globs + other plugins)
73
- if (
74
- isValidFile(cdscontext.filePath) ||
75
- meta.docs.category === categories["env"]
76
- ) {
77
- // Update model/env contents and rules (at runtime)
78
- populateModelAndEnv(cdscontext);
79
- populateRules(cdscontext, customRulesDir);
80
- // 2. Is rule allowed and model/env valid?
81
- if (isValidEnv(cdscontext) || isValidModel(cdscontext)) {
82
- try {
83
- create(cdscontext);
84
- } catch (err) {
85
- if (isEditor()) { // Do not throw to avoid ESLint VSCode editor pop-ups
86
- console.error(`An error occurred while linting. Rule: ${cdscontext.ruleID}\n`, err);
87
- } else {
88
- throw err;
89
- }
90
- }
91
- // Show compilation error only on console
92
- } else if (hasCompilationError(cdscontext) && !isEditor()) {
93
- create(cdscontext);
94
- }
95
- }
96
- },
97
- };
98
- },
99
- };
100
- }
101
-
102
- /**
103
- * Experimental wrapper for 'createRule' to yield:
104
- * - More eslint-like API
105
- * - More convenience re error reports
106
- * @param {CDSRuleSpec} spec
107
- * @returns {RuleModule}
108
- */
109
- function defineRule(spec) {
110
- const { meta, create } = spec;
111
- if (!meta.type) meta.type = "problem";
112
- if (meta.docs && !meta.docs.category) meta.docs.category = "Model Validation";
113
- return createRule({
114
- meta,
115
- create: (context) => {
116
- const { cds, report } = context;
117
- const handlers = create({
118
- cds,
119
- model: cds.model,
120
- report: (r) => report(r),
121
- });
122
- if (cds.model) {
123
- cds.model.forall((d) => {
124
- for (let each in handlers)
125
- if (d.is(each)) {
126
- let r = handlers[each](d);
127
- if (r) {
128
- if (typeof r === "string") r = { message: r };
129
- if (!r.loc) r.loc = cds.getLocation(d.name, d);
130
- if (!r.file)
131
- r.file = (d.$location && d.$location.file) || "unknown.cds";
132
- context.report(r);
133
- }
134
- }
135
- });
136
- }
137
- },
138
- });
139
- }
140
-
141
- /**
142
- * Generates proxy for ESLint's context object which adds caching
143
- * @param obj ESLint's context object
144
- * @returns Proxy for cds
145
- */
146
- function getProxyReport(obj) {
147
- const handler = {
148
- get(target, prop, receiver) {
149
- const value = Reflect.get(target, prop, receiver);
150
- if (typeof value !== "object") {
151
- return value;
152
- }
153
- /* eslint no-extra-boolean-cast: "off" */
154
- if (!!value) {
155
- return new Proxy(value, handler);
156
- }
157
- return {
158
- err: `Property ${prop} prop does not exist on object ${obj}!`,
159
- };
160
- },
161
- apply(target, thisArg, argumentsList) {
162
- let report = false;
163
- if (argumentsList.length > 0) {
164
- argumentsList.forEach((lint) => {
165
- if (lint) {
166
- // --- Checks before context.report() ---
167
- // 1. Is lint (loc) not disabled by ESLint disable comments?
168
- if (!isRuleDisabled(lint, thisArg)) {
169
- const fileRel = lint.file;
170
- let fileAbs = lint.file || "";
171
- if (!path.isAbsolute(fileAbs)) {
172
- fileAbs = fileRel
173
- ? path.join(Cache.get("configpath"), fileRel)
174
- : "";
175
- }
176
- // Only show 'env' lints on console
177
- if (thisArg.category === "env" && !isEditor()) {
178
- lint["loc"] = {
179
- start: { line: 0, column: -1 },
180
- end: { line: 0, column: -1 },
181
- };
182
- report = true;
183
- // Only show 'model' lints at corrsponding file
184
- } else if (
185
- fileAbs === thisArg.filePath ||
186
- fileRel === "<stdin>.cds"
187
- ) {
188
- report = true;
189
- }
190
- if (report) {
191
- return thisArg._context.report(lint);
192
- }
193
- }
194
- }
195
- });
196
- }
197
- },
198
- };
199
- return new Proxy(obj, handler);
200
- }
201
-
202
- /**
203
- * Expands CDS context object with some CDS properties
204
- * We also retrieve the file contents cached by the preprocessor
205
- * @param {RuleContext} context
206
- * @param {RuleNode} node
207
- * @returns cdscontext
208
- */
209
- function createCDSContext(context, node, meta) {
210
- const filePath = context.getPhysicalFilename();
211
- let configPath;
212
- if (!Cache.has("pluginpath")) {
213
- configPath = loadConfigPath(filePath);
214
- } else {
215
- configPath = Cache.get("configpath")
216
- }
217
- let category = "model";
218
- if (meta.docs.category === categories["env"]) {
219
- category = "env";
220
- }
221
- let sourcecode = context.getSourceCode();
222
- let code = sourcecode.getText(node);
223
- if (!code) {
224
- code = Cache.get(`file:${context.getPhysicalFilename()}`);
225
- }
226
- if (code) {
227
- sourcecode = new SourceCode(code, getAST(code));
228
- }
229
- return {
230
- _context: context,
231
- ...context,
232
- category,
233
- cds: context.parserServices.cdsProxy || Cache.get("cds"),
234
- configPath,
235
- code,
236
- filePath,
237
- options: context.options,
238
- report: getProxyReport(context.report),
239
- ruleID: context.id,
240
- sourcecode
241
- };
242
- }
243
-
244
- function getProxyRun(obj) {
245
- const handler = {
246
- get(target, prop, receiver) {
247
- const value = Reflect.get(target, prop, receiver);
248
- if (typeof value !== "object") {
249
- return value;
250
- }
251
- /* eslint no-extra-boolean-cast: "off" */
252
- if (!!value) {
253
- return new Proxy(value, handler);
254
- }
255
- return {
256
- err: `Property ${prop} prop does not exist on object ${obj}!`,
257
- };
258
- },
259
- apply(target, thisArg, argumentsList) {
260
- return thisArg.run();
261
- },
262
- };
263
- return new Proxy(obj, handler);
264
- }
265
-
266
- /**
267
- * ESLint RuleTester (used by custom rule creator api)
268
- * Calls ESLint's RuleTester with custom cds parser and input for
269
- * valid/invalid checks:
270
- * Model checks require input 'code' entries
271
- * Env checks require input 'options' with selected parameters
272
- * @param {CDSRuleTestOpts} options RuleTester input options
273
- * @returns RuleTester results
274
- */
275
- function runRuleTester(options, dryRun=false) {
276
- let parser;
277
- let rule = {};
278
- process.env.LINT_FLAVOR = "inferred";
279
- const rulename = path.basename(options.root);
280
- const plugin = "eslint-plugin-cds";
281
- if (options.root.includes(plugin)) {
282
- // For plugin's internal tests, resolve parser from here
283
- parser = require.resolve("./parser");
284
- rule = require(`./rules/${path.basename(options.root)}`);
285
- const pluginPath = path.join(path.dirname(options.root), "../..");
286
- Cache.set(
287
- "rulesInfo",
288
- getRules(path.join(path.dirname(options.root), "../../lib/impl/rules"))
289
- );
290
- Cache.set("pluginpath", pluginPath);
291
- } else {
292
- // Otherwise from project root
293
- const resolvedPlugin = require.resolve("@sap/eslint-plugin-cds", {
294
- paths: [options.root],
295
- });
296
- parser = path.join(path.dirname(resolvedPlugin), "parser");
297
- rule = require(path.join(
298
- options.root,
299
- `../../rules/${path.basename(options.root)}`
300
- ));
301
- const pluginPath = path.join(path.dirname(options.root), "../../../..");
302
- Cache.set("rulesInfo", getRules(path.join(options.root, "../../rules")));
303
- Cache.set("pluginpath", pluginPath);
304
- }
305
- let category = categories["model"];
306
- if (rule.meta) {
307
- category = rule.meta.docs.category;
308
- }
309
- let tester = new RuleTester({});
310
- if (parser) {
311
- tester = new RuleTester({ parser });
312
- }
313
- const testerCases = {};
314
- ["valid", "invalid"].forEach((type) => {
315
- const filePath = path.join(options.root, `${type}/${options.filename}`);
316
- testerCases[type] = [
317
- {
318
- filename: filePath,
319
- },
320
- ];
321
- if (category === categories["env"]) {
322
- testerCases[type][0].code = "";
323
- testerCases[type][0].options = [
324
- { environment: JSON.parse(fs.readFileSync(filePath, "utf8")) },
325
- ];
326
- } else if (!category || category === categories.model) {
327
- testerCases[type][0].code = fs.readFileSync(filePath, "utf8");
328
- initModelRuleTester(filePath);
329
- }
330
- if (type === "invalid") {
331
- testerCases[type][0].errors = options.errors;
332
- const fileFixed = path.join(options.root, `fixed/${options.filename}`);
333
- if (fs.existsSync(fileFixed) && rule.meta.type !== "suggestion") {
334
- testerCases[type][0].output = fs.readFileSync(fileFixed, "utf8");
335
- }
336
- }
337
- });
338
- return tester.run(rulename, rule, testerCases);
339
- }
340
-
341
- module.exports = { createRule, defineRule, runRuleTester };