@sap/eslint-plugin-cds 2.2.1 → 2.2.2

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