@checkdigit/eslint-plugin 7.3.0-PR.75-f04b → 7.3.0-PR.89-2e8d

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 (81) hide show
  1. package/README.md +2 -1
  2. package/dist-mjs/agent/no-full-response.mjs +35 -0
  3. package/dist-mjs/{no-serve-runtime.mjs → agent/no-serve-runtime.mjs} +3 -3
  4. package/dist-mjs/index.mjs +51 -172
  5. package/dist-mjs/library/tree.mjs +2 -2
  6. package/dist-mjs/no-random-v4-uuid.mjs +67 -0
  7. package/dist-mjs/require-resolve-full-response.mjs +15 -30
  8. package/dist-types/agent/no-full-response.d.ts +4 -0
  9. package/dist-types/index.d.ts +2 -4
  10. package/dist-types/no-random-v4-uuid.d.ts +5 -0
  11. package/package.json +1 -1
  12. package/src/agent/no-full-response.ts +41 -0
  13. package/src/{no-serve-runtime.ts → agent/no-serve-runtime.ts} +2 -2
  14. package/src/index.ts +50 -173
  15. package/src/library/tree.ts +0 -1
  16. package/src/no-random-v4-uuid.ts +92 -0
  17. package/src/require-resolve-full-response.ts +21 -38
  18. package/dist-mjs/agent/add-assert-import.mjs +0 -58
  19. package/dist-mjs/agent/add-base-path-const.mjs +0 -65
  20. package/dist-mjs/agent/add-base-path-import.mjs +0 -60
  21. package/dist-mjs/agent/add-url-domain.mjs +0 -61
  22. package/dist-mjs/agent/agent-test-wiring.mjs +0 -221
  23. package/dist-mjs/agent/fetch-response-body-json.mjs +0 -146
  24. package/dist-mjs/agent/fetch-response-header-getter.mjs +0 -117
  25. package/dist-mjs/agent/fetch-then.mjs +0 -269
  26. package/dist-mjs/agent/fetch.mjs +0 -38
  27. package/dist-mjs/agent/file.mjs +0 -43
  28. package/dist-mjs/agent/fix-function-call-arguments.mjs +0 -153
  29. package/dist-mjs/agent/no-fixture.mjs +0 -356
  30. package/dist-mjs/agent/no-mapped-response.mjs +0 -75
  31. package/dist-mjs/agent/no-service-wrapper.mjs +0 -185
  32. package/dist-mjs/agent/no-status-code.mjs +0 -59
  33. package/dist-mjs/agent/no-unused-function-argument.mjs +0 -79
  34. package/dist-mjs/agent/no-unused-imports.mjs +0 -81
  35. package/dist-mjs/agent/no-unused-service-variable.mjs +0 -74
  36. package/dist-mjs/agent/response-reference.mjs +0 -70
  37. package/dist-mjs/agent/url.mjs +0 -32
  38. package/dist-mjs/no-legacy-service-typing.mjs +0 -39
  39. package/dist-types/agent/add-assert-import.d.ts +0 -4
  40. package/dist-types/agent/add-base-path-const.d.ts +0 -4
  41. package/dist-types/agent/add-base-path-import.d.ts +0 -4
  42. package/dist-types/agent/add-url-domain.d.ts +0 -4
  43. package/dist-types/agent/agent-test-wiring.d.ts +0 -4
  44. package/dist-types/agent/fetch-response-body-json.d.ts +0 -4
  45. package/dist-types/agent/fetch-response-header-getter.d.ts +0 -4
  46. package/dist-types/agent/fetch-then.d.ts +0 -4
  47. package/dist-types/agent/fetch.d.ts +0 -5
  48. package/dist-types/agent/file.d.ts +0 -7
  49. package/dist-types/agent/fix-function-call-arguments.d.ts +0 -9
  50. package/dist-types/agent/no-fixture.d.ts +0 -4
  51. package/dist-types/agent/no-mapped-response.d.ts +0 -4
  52. package/dist-types/agent/no-service-wrapper.d.ts +0 -4
  53. package/dist-types/agent/no-status-code.d.ts +0 -4
  54. package/dist-types/agent/no-unused-function-argument.d.ts +0 -4
  55. package/dist-types/agent/no-unused-imports.d.ts +0 -4
  56. package/dist-types/agent/no-unused-service-variable.d.ts +0 -4
  57. package/dist-types/agent/response-reference.d.ts +0 -16
  58. package/dist-types/agent/url.d.ts +0 -4
  59. package/dist-types/no-legacy-service-typing.d.ts +0 -5
  60. package/src/agent/add-assert-import.ts +0 -74
  61. package/src/agent/add-base-path-const.ts +0 -81
  62. package/src/agent/add-base-path-import.ts +0 -69
  63. package/src/agent/add-url-domain.ts +0 -76
  64. package/src/agent/agent-test-wiring.ts +0 -273
  65. package/src/agent/fetch-response-body-json.ts +0 -197
  66. package/src/agent/fetch-response-header-getter.ts +0 -148
  67. package/src/agent/fetch-then.ts +0 -357
  68. package/src/agent/fetch.ts +0 -57
  69. package/src/agent/file.ts +0 -42
  70. package/src/agent/fix-function-call-arguments.ts +0 -200
  71. package/src/agent/no-fixture.ts +0 -512
  72. package/src/agent/no-mapped-response.ts +0 -84
  73. package/src/agent/no-service-wrapper.ts +0 -241
  74. package/src/agent/no-status-code.ts +0 -72
  75. package/src/agent/no-unused-function-argument.ts +0 -98
  76. package/src/agent/no-unused-imports.ts +0 -103
  77. package/src/agent/no-unused-service-variable.ts +0 -93
  78. package/src/agent/response-reference.ts +0 -129
  79. package/src/agent/url.ts +0 -32
  80. package/src/no-legacy-service-typing.ts +0 -49
  81. /package/dist-types/{no-serve-runtime.d.ts → agent/no-serve-runtime.d.ts} +0 -0
@@ -1,357 +0,0 @@
1
- // agent/fetch-then.ts
2
-
3
- /*
4
- * Copyright (c) 2021-2024 Check Digit, LLC
5
- *
6
- * This code is licensed under the MIT license (see LICENSE.txt for details).
7
- */
8
-
9
- import { strict as assert } from 'node:assert';
10
-
11
- import type { CallExpression, Expression, MemberExpression, SimpleCallExpression } from 'estree';
12
- import { type Rule, type Scope, SourceCode } from 'eslint';
13
-
14
- import { getEnclosingFunction, getEnclosingStatement, getParent, isUsedInArrayOrAsArgument } from '../library/tree';
15
- import getDocumentationUrl from '../get-documentation-url';
16
- import { getIndentation } from '../library/format';
17
- import { isValidPropertyName } from '../library/variable';
18
- import { hasAssertions, isInvalidResponseHeadersAccess } from './fetch';
19
- import { replaceEndpointUrlPrefixWithBasePath } from './url';
20
-
21
- export const ruleId = 'fetch-then';
22
-
23
- interface FixtureCallInformation {
24
- fixtureNode: SimpleCallExpression;
25
- requestBody?: Expression;
26
- requestHeaders?: { name: Expression; value: Expression }[];
27
- assertions?: Expression[][];
28
- }
29
-
30
- // recursively analyze the fixture/supertest call chain to collect information of request/response
31
- function analyzeFixtureCall(call: SimpleCallExpression, results: FixtureCallInformation, sourceCode: SourceCode) {
32
- const parent = getParent(call);
33
- if (!parent) {
34
- return;
35
- }
36
-
37
- let nextCall;
38
- if (parent.type !== 'MemberExpression') {
39
- results.fixtureNode = call;
40
- return;
41
- }
42
-
43
- if (parent.property.type === 'Identifier') {
44
- if (parent.property.name === 'expect') {
45
- // supertest assertions
46
- const assertionCall = getParent(parent);
47
- assert.ok(assertionCall && assertionCall.type === 'CallExpression');
48
- results.assertions = [...(results.assertions ?? []), assertionCall.arguments as Expression[]];
49
- nextCall = assertionCall;
50
- } else if (parent.property.name === 'send') {
51
- // request body
52
- const sendRequestBodyCall = getParent(parent);
53
- assert.ok(sendRequestBodyCall && sendRequestBodyCall.type === 'CallExpression');
54
- results.requestBody = sendRequestBodyCall.arguments[0] as Expression;
55
- nextCall = sendRequestBodyCall;
56
- } else if (parent.property.name === 'set') {
57
- // request headers
58
- const setRequestHeaderCall = getParent(parent);
59
- assert.ok(setRequestHeaderCall && setRequestHeaderCall.type === 'CallExpression');
60
- const [name, value] = setRequestHeaderCall.arguments as [Expression, Expression];
61
- results.requestHeaders = [...(results.requestHeaders ?? []), { name, value }];
62
- nextCall = setRequestHeaderCall;
63
- }
64
- } else {
65
- throw new Error(`Unexpected expression in fixture/supertest call ${sourceCode.getText(parent)}.`);
66
- }
67
- if (nextCall) {
68
- analyzeFixtureCall(nextCall, results, sourceCode);
69
- }
70
- }
71
-
72
- // eslint-disable-next-line sonarjs/cognitive-complexity
73
- function createResponseAssertions(
74
- fixtureCallInformation: FixtureCallInformation,
75
- sourceCode: SourceCode,
76
- responseVariableName: string,
77
- ) {
78
- let statusAssertion: string | undefined;
79
- const nonStatusAssertions: string[] = [];
80
- for (const expectArguments of fixtureCallInformation.assertions ?? []) {
81
- if (expectArguments.length === 1) {
82
- const [assertionArgument] = expectArguments;
83
- assert.ok(assertionArgument);
84
- if (
85
- (assertionArgument.type === 'MemberExpression' &&
86
- assertionArgument.object.type === 'Identifier' &&
87
- assertionArgument.object.name === 'StatusCodes') ||
88
- assertionArgument.type === 'Literal' ||
89
- sourceCode.getText(assertionArgument).includes('StatusCodes.')
90
- ) {
91
- // status code assertion
92
- statusAssertion = `assert.equal(${responseVariableName}.status, ${sourceCode.getText(assertionArgument)})`;
93
- } else if (assertionArgument.type === 'ArrowFunctionExpression') {
94
- // callback assertion using arrow function
95
- let functionBody = sourceCode.getText(assertionArgument.body);
96
-
97
- const [originalResponseArgument] = assertionArgument.params;
98
- assert.ok(originalResponseArgument?.type === 'Identifier');
99
- const originalResponseArgumentName = originalResponseArgument.name;
100
- if (originalResponseArgumentName !== responseVariableName) {
101
- functionBody = functionBody.replace(
102
- new RegExp(`\\b${originalResponseArgumentName}\\b`, 'ug'),
103
- responseVariableName,
104
- );
105
- }
106
- nonStatusAssertions.push(`assert.doesNotThrow(()=>${functionBody})`);
107
- } else if (assertionArgument.type === 'Identifier') {
108
- // callback assertion using function reference
109
- nonStatusAssertions.push(
110
- `assert.doesNotThrow(()=>${sourceCode.getText(assertionArgument)}(${responseVariableName}))`,
111
- );
112
- } else if (assertionArgument.type === 'ObjectExpression' || assertionArgument.type === 'CallExpression') {
113
- // body deep equal assertion
114
- nonStatusAssertions.push(
115
- `assert.deepEqual(await ${responseVariableName}.json(), ${sourceCode.getText(assertionArgument)})`,
116
- );
117
- } else {
118
- throw new Error(`Unexpected Supertest assertion argument: ".expect(${sourceCode.getText(assertionArgument)})`);
119
- }
120
- } else if (expectArguments.length === 2) {
121
- // header assertion
122
- const [headerName, headerValue] = expectArguments;
123
- assert.ok(headerName && headerValue);
124
- const headersReference = `${responseVariableName}.headers`;
125
- if (headerValue.type === 'Literal' && headerValue.value instanceof RegExp) {
126
- nonStatusAssertions.push(
127
- `assert.ok(${headersReference}.get(${sourceCode.getText(headerName)}).match(${sourceCode.getText(headerValue)}))`,
128
- );
129
- } else {
130
- nonStatusAssertions.push(
131
- `assert.equal(${headersReference}.get(${sourceCode.getText(headerName)}), ${sourceCode.getText(headerValue)})`,
132
- );
133
- }
134
- }
135
- }
136
- return {
137
- statusAssertion,
138
- nonStatusAssertions,
139
- };
140
- }
141
-
142
- function getResponseHeadersAccesses(
143
- responseVariables: Scope.Variable[],
144
- scopeManager: Scope.ScopeManager,
145
- sourceCode: SourceCode,
146
- ) {
147
- const responseHeadersAccesses: MemberExpression[] = [];
148
- for (const responseVariable of responseVariables) {
149
- for (const responseReference of responseVariable.references) {
150
- const responseAccess = getParent(responseReference.identifier);
151
- if (!responseAccess || responseAccess.type !== 'MemberExpression') {
152
- continue;
153
- }
154
-
155
- const responseAccessParent = getParent(responseAccess);
156
- if (!responseAccessParent) {
157
- continue;
158
- }
159
-
160
- if (
161
- responseAccessParent.type === 'CallExpression' &&
162
- responseAccessParent.arguments[0]?.type === 'ArrowFunctionExpression'
163
- ) {
164
- // map-like operation against responses, e.g. responses.map((response) => response.headers.etag)
165
- responseHeadersAccesses.push(
166
- ...getResponseHeadersAccesses(
167
- scopeManager.getDeclaredVariables(responseAccessParent.arguments[0]),
168
- scopeManager,
169
- sourceCode,
170
- ),
171
- );
172
- continue;
173
- }
174
-
175
- if (
176
- responseAccess.computed &&
177
- responseAccess.property.type === 'Literal' &&
178
- responseAccessParent.type === 'MemberExpression'
179
- ) {
180
- // header access through indexed responses array, e.g. responses[0].headers, responses[1].get(...), etc.
181
- responseHeadersAccesses.push(responseAccessParent);
182
- } else {
183
- responseHeadersAccesses.push(responseAccess);
184
- }
185
- }
186
- }
187
- return responseHeadersAccesses;
188
- }
189
-
190
- const rule: Rule.RuleModule = {
191
- meta: {
192
- type: 'suggestion',
193
- docs: {
194
- description: 'Prefer native fetch API over customized fixture API.',
195
- url: getDocumentationUrl(ruleId),
196
- },
197
- messages: {
198
- preferNativeFetch: 'Prefer native fetch API over customized fixture API.',
199
- shouldUseHeaderGetter: 'Getter should be used to access response headers.',
200
- unknownError: 'Unknown error occurred in file "{{fileName}}": {{ error }}.',
201
- },
202
- fixable: 'code',
203
- schema: [],
204
- },
205
-
206
- create(context) {
207
- const sourceCode = context.sourceCode;
208
- const scopeManager = sourceCode.scopeManager;
209
-
210
- return {
211
- 'CallExpression[callee.object.object.name="fixture"][callee.object.property.name="api"]': (
212
- fixtureCall: CallExpression,
213
- // eslint-disable-next-line sonarjs/cognitive-complexity
214
- ) => {
215
- try {
216
- if (!hasAssertions(fixtureCall)) {
217
- // skip if there are no assertions, let "no-fixture" rule to handle the conversion
218
- return;
219
- }
220
-
221
- if (!(isUsedInArrayOrAsArgument(fixtureCall) || getEnclosingFunction(fixtureCall)?.async === false)) {
222
- return;
223
- }
224
-
225
- assert.ok(fixtureCall.type === 'CallExpression');
226
- const fixtureFunction = fixtureCall.callee; // e.g. fixture.api.get
227
- assert.ok(fixtureFunction.type === 'MemberExpression');
228
- const indentation = getIndentation(fixtureCall, sourceCode);
229
-
230
- const [urlArgumentNode] = fixtureCall.arguments; // e.g. `/sample-service/v1/ping`
231
- assert.ok(urlArgumentNode !== undefined);
232
-
233
- const fixtureCallInformation = {} as FixtureCallInformation;
234
- analyzeFixtureCall(fixtureCall, fixtureCallInformation, sourceCode);
235
-
236
- // convert url from `/sample-service/v1/ping` to `${BASE_PATH}/ping`
237
- const originalUrlArgumentText = sourceCode.getText(urlArgumentNode);
238
- const fetchUrlArgumentText = replaceEndpointUrlPrefixWithBasePath(originalUrlArgumentText);
239
-
240
- // fetch request argument
241
- const methodNode = fixtureFunction.property; // get/put/etc.
242
- assert.ok(methodNode.type === 'Identifier');
243
- const fetchRequestArgumentLines = [
244
- '{',
245
- ` method: '${methodNode.name.toUpperCase()}',`,
246
- ...(fixtureCallInformation.requestBody
247
- ? [` body: JSON.stringify(${sourceCode.getText(fixtureCallInformation.requestBody)}),`]
248
- : []),
249
- ...(fixtureCallInformation.requestHeaders
250
- ? [
251
- ` headers: {`,
252
- ...fixtureCallInformation.requestHeaders.map(
253
- ({ name, value }) =>
254
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions, no-nested-ternary, sonarjs/no-nested-template-literals
255
- ` ${name.type === 'Literal' ? (isValidPropertyName(name.value) ? name.value : `'${name.value}'`) : `[${sourceCode.getText(name)}]`}: ${sourceCode.getText(value)},`,
256
- ),
257
- ` },`,
258
- ]
259
- : []),
260
- '}',
261
- ].join(`\n${indentation}`);
262
-
263
- const responseVariableNameToUse = 'res';
264
- const { statusAssertion, nonStatusAssertions } = createResponseAssertions(
265
- fixtureCallInformation,
266
- sourceCode,
267
- responseVariableNameToUse,
268
- );
269
-
270
- // add variable declaration if needed
271
- const disableLintComment = '// eslint-disable-next-line @checkdigit/no-promise-instance-method';
272
- const fetchCallText = `fetch(${fetchUrlArgumentText}, ${fetchRequestArgumentLines})`;
273
- const appendingAssignmentAndAssertionText = [
274
- ...(statusAssertion !== undefined ? [statusAssertion] : []),
275
- ...nonStatusAssertions,
276
- ].join(`;\n${indentation}`);
277
- const replacementText = fixtureCallInformation.assertions
278
- ? [
279
- disableLintComment,
280
- `${fetchCallText}.then((${responseVariableNameToUse}) => {`,
281
- appendingAssignmentAndAssertionText === '' ? '' : ` ${appendingAssignmentAndAssertionText};`,
282
- ` return ${responseVariableNameToUse};`,
283
- `})`,
284
- ].join(`\n${indentation}`)
285
- : fetchCallText;
286
-
287
- context.report({
288
- node: fixtureCall,
289
- messageId: 'preferNativeFetch',
290
- fix(fixer) {
291
- return fixer.replaceText(fixtureCallInformation.fixtureNode, replacementText);
292
- },
293
- });
294
-
295
- const responsesVariable = getEnclosingStatement(fixtureCallInformation.fixtureNode);
296
- if (!responsesVariable) {
297
- return;
298
- }
299
-
300
- const responseVariableReferences = scopeManager.getDeclaredVariables(responsesVariable);
301
- const responseHeadersAccesses = getResponseHeadersAccesses(
302
- responseVariableReferences,
303
- scopeManager,
304
- sourceCode,
305
- );
306
- for (const responseHeadersAccess of responseHeadersAccesses) {
307
- if (isInvalidResponseHeadersAccess(responseHeadersAccess)) {
308
- const headerAccess = getParent(responseHeadersAccess);
309
- if (headerAccess?.type === 'MemberExpression') {
310
- const headerNameNode = headerAccess.property;
311
- const headerName = headerAccess.computed
312
- ? sourceCode.getText(headerNameNode)
313
- : `'${sourceCode.getText(headerNameNode)}'`;
314
- const headerAccessReplacementText = `${sourceCode.getText(headerAccess.object)}.get(${headerName})`;
315
-
316
- context.report({
317
- node: headerAccess,
318
- messageId: 'shouldUseHeaderGetter',
319
- fix(fixer) {
320
- return fixer.replaceText(headerAccess, headerAccessReplacementText);
321
- },
322
- });
323
- } else if (
324
- headerAccess?.type === 'CallExpression' &&
325
- responseHeadersAccess.property.type === 'Identifier' &&
326
- responseHeadersAccess.property.name === 'get'
327
- ) {
328
- const headerAccessReplacementText = `${sourceCode.getText(responseHeadersAccess.object)}.headers.get(${sourceCode.getText(headerAccess.arguments[0])})`;
329
-
330
- context.report({
331
- node: headerAccess,
332
- messageId: 'shouldUseHeaderGetter',
333
- fix(fixer) {
334
- return fixer.replaceText(headerAccess, headerAccessReplacementText);
335
- },
336
- });
337
- }
338
- }
339
- }
340
- } catch (error) {
341
- // eslint-disable-next-line no-console
342
- console.error(`Failed to apply ${ruleId} rule for file "${context.filename}":`, error);
343
- context.report({
344
- node: fixtureCall,
345
- messageId: 'unknownError',
346
- data: {
347
- fileName: context.filename,
348
- error: error instanceof Error ? error.toString() : JSON.stringify(error),
349
- },
350
- });
351
- }
352
- },
353
- };
354
- },
355
- };
356
-
357
- export default rule;
@@ -1,57 +0,0 @@
1
- // agent/fetch.ts
2
-
3
- import type { Node } from 'estree';
4
-
5
- import { getParent, isBlockStatement } from '../library/tree';
6
-
7
- export function getResponseBodyRetrievalText(responseVariableName: string) {
8
- return `await ${responseVariableName}.json()`;
9
- }
10
-
11
- export function getResponseHeadersRetrievalText(responseVariableName: string) {
12
- return `${responseVariableName}.headers`;
13
- }
14
-
15
- export function isInvalidResponseHeadersAccess(responseHeadersAccess: Node): boolean {
16
- const responseHeaderAccessParent = getParent(responseHeadersAccess);
17
- if (responseHeaderAccessParent?.type === 'VariableDeclarator') {
18
- return false;
19
- }
20
-
21
- if (
22
- responseHeaderAccessParent?.type === 'CallExpression' &&
23
- responseHeaderAccessParent.callee.type === 'MemberExpression' &&
24
- responseHeaderAccessParent.callee.property.type === 'Identifier' &&
25
- responseHeaderAccessParent.callee.property.name === 'get'
26
- ) {
27
- return true;
28
- }
29
-
30
- return !(
31
- responseHeaderAccessParent?.type === 'MemberExpression' &&
32
- responseHeaderAccessParent.property.type === 'Identifier' &&
33
- responseHeaderAccessParent.property.name === 'get'
34
- );
35
- }
36
-
37
- export function hasAssertions(fixtureCall: Node): boolean {
38
- if (isBlockStatement(fixtureCall)) {
39
- return false;
40
- }
41
-
42
- const parent = getParent(fixtureCall);
43
- if (!parent) {
44
- return false;
45
- }
46
-
47
- if (
48
- parent.type === 'MemberExpression' &&
49
- parent.property.type === 'Identifier' &&
50
- parent.property.name === 'expect' &&
51
- getParent(parent)?.type === 'CallExpression'
52
- ) {
53
- return true;
54
- }
55
-
56
- return hasAssertions(parent);
57
- }
package/src/agent/file.ts DELETED
@@ -1,42 +0,0 @@
1
- // agent/file.ts
2
-
3
- import fs from 'node:fs';
4
- import path from 'node:path';
5
-
6
- export function isApiIndexFile(filename: string): boolean {
7
- return /.*\/src\/api\/v\d+\/index.ts/u.test(filename);
8
- }
9
-
10
- export function getProjectRootFolder(indexFilename: string): string {
11
- return indexFilename.substring(0, indexFilename.lastIndexOf('/src/'));
12
- }
13
-
14
- export function getSwaggerPathByIndexFile(indexFilename: string): string {
15
- return indexFilename.replace(/index\.ts$/u, 'swagger.yml');
16
- }
17
-
18
- export function loadSwagger(filename: string): string {
19
- return fs.readFileSync(filename, 'utf8');
20
- }
21
-
22
- export function loadPackageJson(projectRoot: string): string {
23
- return fs.readFileSync(`${projectRoot}/package.json`, 'utf8');
24
- }
25
-
26
- export function getApiFolder(folder: string): string | undefined {
27
- if (/^(?<absolutePath>.*\/)*src\/api\/v\d+$/u.test(folder)) {
28
- return folder;
29
- }
30
- const upperFolder = folder.substring(0, folder.lastIndexOf('/'));
31
- return upperFolder.trim() === '' ? undefined : getApiFolder(upperFolder);
32
- }
33
-
34
- export function getApiIndexPathByFilename(filename: string): string | undefined {
35
- const apiFolder = getApiFolder(filename);
36
- if (apiFolder === undefined) {
37
- return undefined;
38
- }
39
-
40
- const relativePath = path.relative(path.dirname(filename), `${apiFolder}/index`);
41
- return relativePath.startsWith('../') ? relativePath : `./${relativePath}`;
42
- }
@@ -1,200 +0,0 @@
1
- // agent/fix-function-call-arguments.ts
2
-
3
- /*
4
- * Copyright (c) 2021-2024 Check Digit, LLC
5
- *
6
- * This code is licensed under the MIT license (see LICENSE.txt for details).
7
- */
8
-
9
- import { strict as assert } from 'node:assert';
10
- import { ESLintUtils, TSESTree } from '@typescript-eslint/utils';
11
- import debug from 'debug';
12
- import getDocumentationUrl from '../get-documentation-url';
13
-
14
- export const ruleId = 'fix-function-call-arguments';
15
-
16
- export interface FixFunctionCallArgumentsRuleOptions {
17
- typesToCheck: string[];
18
- }
19
- const DEFAULT_OPTIONS = {
20
- typesToCheck: [
21
- 'Configuration<ResolvedServices>',
22
- 'Fixture<ResolvedServices>',
23
- 'InboundContext',
24
- '{ get: () => string; }',
25
- 'Api',
26
- ],
27
- };
28
-
29
- const createRule = ESLintUtils.RuleCreator((name) => getDocumentationUrl(name));
30
- const log = debug('eslint-plugin:fix-function-call-arguments');
31
-
32
- const rule: ESLintUtils.RuleModule<
33
- 'removeIncompatibleFunctionArguments' | 'unknownError',
34
- [FixFunctionCallArgumentsRuleOptions]
35
- > = createRule({
36
- name: ruleId,
37
- meta: {
38
- type: 'suggestion',
39
- docs: {
40
- description: 'Remove incompatible function arguments.',
41
- },
42
- messages: {
43
- removeIncompatibleFunctionArguments: 'Removing incompatible function arguments.',
44
- unknownError: 'Unknown error occurred in file "{{fileName}}": {{ error }}.',
45
- },
46
- fixable: 'code',
47
- schema: [
48
- {
49
- type: 'object',
50
- properties: {
51
- typesToCheck: {
52
- description: 'Text representation of the types of which the function call parameters will be examine',
53
- type: 'array',
54
- items: {
55
- type: 'string',
56
- },
57
- },
58
- },
59
- additionalProperties: false,
60
- },
61
- ],
62
- },
63
- defaultOptions: [DEFAULT_OPTIONS],
64
- create(context) {
65
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
66
- const { typesToCheck } = context.options[0] ?? DEFAULT_OPTIONS;
67
- const parserServices = ESLintUtils.getParserServices(context);
68
- const typeChecker = parserServices.program.getTypeChecker();
69
- const sourceCode = context.sourceCode;
70
-
71
- return {
72
- CallExpression(callExpression) {
73
- // ignore calls like `foo.bar()` which are likely to be 3rd party module calls
74
- // we only focus on calls against local functions or functions imported from the same module
75
- // if (callExpression.callee.type === TSESTree.AST_NODE_TYPES.MemberExpression) {
76
- // return;
77
- // }
78
-
79
- log('===== file name:', context.filename);
80
- log('callExpression:', sourceCode.getText(callExpression));
81
-
82
- try {
83
- const actualParameters = callExpression.arguments;
84
- if (
85
- !actualParameters.some((actualParameter) => {
86
- const actualType = typeChecker.getTypeAtLocation(
87
- parserServices.esTreeNodeToTSNodeMap.get(actualParameter),
88
- );
89
- const actualTypeString = typeChecker.typeToString(actualType);
90
- return typesToCheck.includes(actualTypeString) || actualTypeString.endsWith('RequestType');
91
- })
92
- ) {
93
- return;
94
- }
95
-
96
- const calleeTsNode = parserServices.esTreeNodeToTSNodeMap.get(callExpression.callee);
97
- const calleeType = typeChecker.getTypeAtLocation(calleeTsNode);
98
-
99
- const signatures = calleeType.getCallSignatures();
100
- if (signatures.length > 1) {
101
- // ignore complex signatures with overloads
102
- return;
103
- }
104
-
105
- const signature = signatures[0];
106
- assert(signature);
107
- // if (
108
- // signature === undefined ||
109
- // (signature.typeParameters !== undefined && signature.typeParameters.length > 0)
110
- // ) {
111
- // // ignore complex signatures with type parameters
112
- // return;
113
- // }
114
-
115
- log('signature:', signature.getDeclaration().getText());
116
- const expectedParameters = signature.getParameters();
117
- log(
118
- 'expected parameters:',
119
- expectedParameters.map((expectedParameter) =>
120
- typeChecker.typeToString(typeChecker.getTypeOfSymbol(expectedParameter)),
121
- ),
122
- );
123
- const expectedParametersCount = expectedParameters.length;
124
- const actualParametersCount = actualParameters.length;
125
- if (actualParametersCount === 0) {
126
- return;
127
- }
128
-
129
- const parametersToKeep: TSESTree.CallExpressionArgument[] = [];
130
- let expectedParameterIndex = 0;
131
- for (const [actualParameterIndex, actualParameter] of actualParameters.entries()) {
132
- if (expectedParameterIndex >= expectedParametersCount) {
133
- break;
134
- }
135
-
136
- const expectedParameter = expectedParameters[expectedParameterIndex];
137
- assert.ok(expectedParameter, 'Expected parameter not found.');
138
-
139
- const expectedType = typeChecker.getTypeOfSymbol(expectedParameter);
140
- const actualType = typeChecker.getTypeAtLocation(parserServices.esTreeNodeToTSNodeMap.get(actualParameter));
141
- const actualTypeString = typeChecker.typeToString(actualType);
142
- log(
143
- 'expected type: #',
144
- expectedParameterIndex,
145
- expectedParameter.escapedName,
146
- typeChecker.typeToString(expectedType),
147
- );
148
- log('actual type: #', actualParameterIndex, sourceCode.getText(actualParameter), actualTypeString);
149
-
150
- if (
151
- (typesToCheck.includes(actualTypeString) || actualTypeString.endsWith('RequestType')) &&
152
- !typeChecker.isTypeAssignableTo(actualType, expectedType)
153
- ) {
154
- log('removing un-matched parameter', sourceCode.getText(actualParameter));
155
- continue;
156
- }
157
- parametersToKeep.push(actualParameter);
158
- expectedParameterIndex++;
159
- }
160
-
161
- if (parametersToKeep.length === actualParametersCount) {
162
- return;
163
- }
164
-
165
- const firstParameter = actualParameters[0];
166
- const lastParameter = actualParameters.at(-1);
167
- assert.ok(firstParameter !== undefined && lastParameter !== undefined);
168
- const tokenAfterParameters = sourceCode.getTokenAfter(lastParameter);
169
-
170
- context.report({
171
- node: callExpression,
172
- messageId: 'removeIncompatibleFunctionArguments',
173
- fix(fixer) {
174
- return fixer.replaceTextRange(
175
- [
176
- firstParameter.range[0],
177
- tokenAfterParameters?.value === ',' ? tokenAfterParameters.range[1] : lastParameter.range[1],
178
- ],
179
- parametersToKeep.map((arg) => sourceCode.getText(arg)).join(', '),
180
- );
181
- },
182
- });
183
- } catch (error) {
184
- // eslint-disable-next-line no-console
185
- console.error(`Failed to apply ${ruleId} rule for file "${context.filename}":`, error);
186
- context.report({
187
- node: callExpression,
188
- messageId: 'unknownError',
189
- data: {
190
- fileName: context.filename,
191
- error: error instanceof Error ? error.toString() : JSON.stringify(error),
192
- },
193
- });
194
- }
195
- },
196
- };
197
- },
198
- });
199
-
200
- export default rule;