@checkdigit/eslint-plugin 7.3.0-PR.75-1f63 → 7.3.0-PR.93-561f

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 (65) hide show
  1. package/dist-mjs/index.mjs +3 -122
  2. package/dist-mjs/require-resolve-full-response.mjs +1 -1
  3. package/package.json +1 -1
  4. package/src/index.ts +0 -119
  5. package/src/require-resolve-full-response.ts +1 -3
  6. package/dist-mjs/agent/add-assert-import.mjs +0 -58
  7. package/dist-mjs/agent/add-base-path-const.mjs +0 -65
  8. package/dist-mjs/agent/add-base-path-import.mjs +0 -60
  9. package/dist-mjs/agent/add-url-domain.mjs +0 -61
  10. package/dist-mjs/agent/agent-test-wiring.mjs +0 -196
  11. package/dist-mjs/agent/fetch-response-body-json.mjs +0 -134
  12. package/dist-mjs/agent/fetch-response-header-getter.mjs +0 -117
  13. package/dist-mjs/agent/fetch-then.mjs +0 -267
  14. package/dist-mjs/agent/fetch.mjs +0 -34
  15. package/dist-mjs/agent/file.mjs +0 -43
  16. package/dist-mjs/agent/fix-function-call-arguments.mjs +0 -150
  17. package/dist-mjs/agent/no-fixture.mjs +0 -336
  18. package/dist-mjs/agent/no-mapped-response.mjs +0 -75
  19. package/dist-mjs/agent/no-service-wrapper.mjs +0 -185
  20. package/dist-mjs/agent/no-status-code.mjs +0 -59
  21. package/dist-mjs/agent/no-unused-function-argument.mjs +0 -79
  22. package/dist-mjs/agent/no-unused-imports.mjs +0 -81
  23. package/dist-mjs/agent/no-unused-service-variable.mjs +0 -74
  24. package/dist-mjs/agent/response-reference.mjs +0 -67
  25. package/dist-mjs/agent/url.mjs +0 -32
  26. package/dist-types/agent/add-assert-import.d.ts +0 -4
  27. package/dist-types/agent/add-base-path-const.d.ts +0 -4
  28. package/dist-types/agent/add-base-path-import.d.ts +0 -4
  29. package/dist-types/agent/add-url-domain.d.ts +0 -4
  30. package/dist-types/agent/agent-test-wiring.d.ts +0 -4
  31. package/dist-types/agent/fetch-response-body-json.d.ts +0 -4
  32. package/dist-types/agent/fetch-response-header-getter.d.ts +0 -4
  33. package/dist-types/agent/fetch-then.d.ts +0 -4
  34. package/dist-types/agent/fetch.d.ts +0 -4
  35. package/dist-types/agent/file.d.ts +0 -7
  36. package/dist-types/agent/fix-function-call-arguments.d.ts +0 -9
  37. package/dist-types/agent/no-fixture.d.ts +0 -4
  38. package/dist-types/agent/no-mapped-response.d.ts +0 -4
  39. package/dist-types/agent/no-service-wrapper.d.ts +0 -4
  40. package/dist-types/agent/no-status-code.d.ts +0 -4
  41. package/dist-types/agent/no-unused-function-argument.d.ts +0 -4
  42. package/dist-types/agent/no-unused-imports.d.ts +0 -4
  43. package/dist-types/agent/no-unused-service-variable.d.ts +0 -4
  44. package/dist-types/agent/response-reference.d.ts +0 -16
  45. package/dist-types/agent/url.d.ts +0 -4
  46. package/src/agent/add-assert-import.ts +0 -74
  47. package/src/agent/add-base-path-const.ts +0 -81
  48. package/src/agent/add-base-path-import.ts +0 -69
  49. package/src/agent/add-url-domain.ts +0 -76
  50. package/src/agent/agent-test-wiring.ts +0 -246
  51. package/src/agent/fetch-response-body-json.ts +0 -178
  52. package/src/agent/fetch-response-header-getter.ts +0 -148
  53. package/src/agent/fetch-then.ts +0 -355
  54. package/src/agent/fetch.ts +0 -53
  55. package/src/agent/file.ts +0 -42
  56. package/src/agent/fix-function-call-arguments.ts +0 -188
  57. package/src/agent/no-fixture.ts +0 -480
  58. package/src/agent/no-mapped-response.ts +0 -84
  59. package/src/agent/no-service-wrapper.ts +0 -241
  60. package/src/agent/no-status-code.ts +0 -72
  61. package/src/agent/no-unused-function-argument.ts +0 -98
  62. package/src/agent/no-unused-imports.ts +0 -103
  63. package/src/agent/no-unused-service-variable.ts +0 -93
  64. package/src/agent/response-reference.ts +0 -122
  65. package/src/agent/url.ts +0 -32
@@ -1,148 +0,0 @@
1
- // agent/fetch-response-header-getter-ts.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 { AST_NODE_TYPES, ESLintUtils, TSESTree } from '@typescript-eslint/utils';
10
-
11
- import getDocumentationUrl from '../get-documentation-url';
12
-
13
- export const ruleId = 'fetch-response-header-getter-ts';
14
- const HEADER_BUILTIN_FUNCTIONS = Object.keys(Headers.prototype);
15
-
16
- const createRule = ESLintUtils.RuleCreator((name) => getDocumentationUrl(name));
17
-
18
- const rule: ESLintUtils.RuleModule<'unknownError' | 'useGetter'> = createRule({
19
- name: ruleId,
20
- meta: {
21
- type: 'suggestion',
22
- docs: {
23
- description: 'Use "get()" method to get header value from the headers object of the fetch response.',
24
- },
25
- messages: {
26
- useGetter: 'Use "get()" method to get header value from the headers object of the fetch response.',
27
- unknownError: 'Unknown error occurred in file "{{fileName}}": {{ error }}.',
28
- },
29
- fixable: 'code',
30
- schema: [],
31
- },
32
- defaultOptions: [],
33
- create(context) {
34
- const parserServices = ESLintUtils.getParserServices(context);
35
- const typeChecker = parserServices.program.getTypeChecker();
36
- const sourceCode = context.sourceCode;
37
-
38
- return {
39
- MemberExpression: (responseHeadersAccess: TSESTree.MemberExpression) => {
40
- try {
41
- if (
42
- responseHeadersAccess.property.type === AST_NODE_TYPES.Identifier &&
43
- HEADER_BUILTIN_FUNCTIONS.includes(responseHeadersAccess.property.name)
44
- ) {
45
- // skip Headers's built-in function calls
46
- return;
47
- }
48
-
49
- const responseHeadersTsNode = parserServices.esTreeNodeToTSNodeMap.get(responseHeadersAccess.object);
50
- let responseHeadersType = typeChecker.getTypeAtLocation(responseHeadersTsNode);
51
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
52
- responseHeadersType = responseHeadersType.isUnion() ? responseHeadersType.types[0]! : responseHeadersType;
53
- const responseHeadersTypeName = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
54
- (responseHeadersType.symbol ?? responseHeadersType.aliasSymbol)?.escapedName;
55
- // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison
56
- if (responseHeadersTypeName !== 'Headers' && responseHeadersTypeName !== 'HeaderGetter') {
57
- return;
58
- }
59
-
60
- let replacementText: string;
61
- if (!responseHeadersAccess.computed) {
62
- // e.g. headers.etag
63
- replacementText = `${sourceCode.getText(responseHeadersAccess.object)}.get('${sourceCode.getText(responseHeadersAccess.property)}')`;
64
- } else if (
65
- responseHeadersAccess.property.type === AST_NODE_TYPES.Identifier ||
66
- responseHeadersAccess.property.type === AST_NODE_TYPES.Literal ||
67
- responseHeadersAccess.property.type === AST_NODE_TYPES.TemplateLiteral
68
- ) {
69
- replacementText = `${sourceCode.getText(responseHeadersAccess.object)}.get(${sourceCode.getText(responseHeadersAccess.property)})`;
70
- } else {
71
- throw new Error(`Unexpected property type: ${responseHeadersAccess.property.type}`);
72
- }
73
-
74
- context.report({
75
- messageId: 'useGetter',
76
- node: responseHeadersAccess.property,
77
- fix(fixer) {
78
- return fixer.replaceText(responseHeadersAccess, replacementText);
79
- },
80
- });
81
- } catch (error) {
82
- // eslint-disable-next-line no-console
83
- console.error(`Failed to apply ${ruleId} rule for file "${context.filename}":`, error);
84
- context.report({
85
- node: responseHeadersAccess,
86
- messageId: 'unknownError',
87
- data: {
88
- fileName: context.filename,
89
- error: error instanceof Error ? error.toString() : JSON.stringify(error),
90
- },
91
- });
92
- }
93
- },
94
-
95
- // convert response.get() to response.headers.get()
96
- 'CallExpression[callee.property.name="get"]': (responseHeadersAccess: TSESTree.CallExpression) => {
97
- try {
98
- if (responseHeadersAccess.callee.type !== AST_NODE_TYPES.MemberExpression) {
99
- return;
100
- }
101
-
102
- // skip request-like calls
103
- if (
104
- responseHeadersAccess.callee.object.type !== AST_NODE_TYPES.Identifier ||
105
- responseHeadersAccess.callee.object.name === 'request'
106
- ) {
107
- return;
108
- }
109
- const responseNode = responseHeadersAccess.callee.object;
110
- const responseHeadersTsNode = parserServices.esTreeNodeToTSNodeMap.get(responseNode);
111
- const responseType = typeChecker.getTypeAtLocation(responseHeadersTsNode);
112
- const typeName = typeChecker.typeToString(responseType);
113
- if (typeName === 'InboundContext' || typeName.endsWith('RequestType')) {
114
- return;
115
- }
116
-
117
- // make sure the response type has "headers" property
118
- const hasHeadersProperty = responseType.getProperties().some((symbol) => symbol.name === 'headers');
119
- if (!hasHeadersProperty) {
120
- return;
121
- }
122
-
123
- const replacementText = `${sourceCode.getText(responseNode)}.headers`;
124
- context.report({
125
- messageId: 'useGetter',
126
- node: responseHeadersAccess,
127
- fix(fixer) {
128
- return fixer.replaceText(responseNode, replacementText);
129
- },
130
- });
131
- } catch (error) {
132
- // eslint-disable-next-line no-console
133
- console.error(`Failed to apply ${ruleId} rule for file "${context.filename}":`, error);
134
- context.report({
135
- node: responseHeadersAccess,
136
- messageId: 'unknownError',
137
- data: {
138
- fileName: context.filename,
139
- error: error instanceof Error ? error.toString() : JSON.stringify(error),
140
- },
141
- });
142
- }
143
- },
144
- };
145
- },
146
- });
147
-
148
- export default rule;
@@ -1,355 +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.ok(${functionBody})`);
107
- } else if (assertionArgument.type === 'Identifier') {
108
- // callback assertion using function reference
109
- nonStatusAssertions.push(`assert.ok(${sourceCode.getText(assertionArgument)}(${responseVariableName}))`);
110
- } else if (assertionArgument.type === 'ObjectExpression' || assertionArgument.type === 'CallExpression') {
111
- // body deep equal assertion
112
- nonStatusAssertions.push(
113
- `assert.deepEqual(await ${responseVariableName}.json(), ${sourceCode.getText(assertionArgument)})`,
114
- );
115
- } else {
116
- throw new Error(`Unexpected Supertest assertion argument: ".expect(${sourceCode.getText(assertionArgument)})`);
117
- }
118
- } else if (expectArguments.length === 2) {
119
- // header assertion
120
- const [headerName, headerValue] = expectArguments;
121
- assert.ok(headerName && headerValue);
122
- const headersReference = `${responseVariableName}.headers`;
123
- if (headerValue.type === 'Literal' && headerValue.value instanceof RegExp) {
124
- nonStatusAssertions.push(
125
- `assert.ok(${headersReference}.get(${sourceCode.getText(headerName)}).match(${sourceCode.getText(headerValue)}))`,
126
- );
127
- } else {
128
- nonStatusAssertions.push(
129
- `assert.equal(${headersReference}.get(${sourceCode.getText(headerName)}), ${sourceCode.getText(headerValue)})`,
130
- );
131
- }
132
- }
133
- }
134
- return {
135
- statusAssertion,
136
- nonStatusAssertions,
137
- };
138
- }
139
-
140
- function getResponseHeadersAccesses(
141
- responseVariables: Scope.Variable[],
142
- scopeManager: Scope.ScopeManager,
143
- sourceCode: SourceCode,
144
- ) {
145
- const responseHeadersAccesses: MemberExpression[] = [];
146
- for (const responseVariable of responseVariables) {
147
- for (const responseReference of responseVariable.references) {
148
- const responseAccess = getParent(responseReference.identifier);
149
- if (!responseAccess || responseAccess.type !== 'MemberExpression') {
150
- continue;
151
- }
152
-
153
- const responseAccessParent = getParent(responseAccess);
154
- if (!responseAccessParent) {
155
- continue;
156
- }
157
-
158
- if (
159
- responseAccessParent.type === 'CallExpression' &&
160
- responseAccessParent.arguments[0]?.type === 'ArrowFunctionExpression'
161
- ) {
162
- // map-like operation against responses, e.g. responses.map((response) => response.headers.etag)
163
- responseHeadersAccesses.push(
164
- ...getResponseHeadersAccesses(
165
- scopeManager.getDeclaredVariables(responseAccessParent.arguments[0]),
166
- scopeManager,
167
- sourceCode,
168
- ),
169
- );
170
- continue;
171
- }
172
-
173
- if (
174
- responseAccess.computed &&
175
- responseAccess.property.type === 'Literal' &&
176
- responseAccessParent.type === 'MemberExpression'
177
- ) {
178
- // header access through indexed responses array, e.g. responses[0].headers, responses[1].get(...), etc.
179
- responseHeadersAccesses.push(responseAccessParent);
180
- } else {
181
- responseHeadersAccesses.push(responseAccess);
182
- }
183
- }
184
- }
185
- return responseHeadersAccesses;
186
- }
187
-
188
- const rule: Rule.RuleModule = {
189
- meta: {
190
- type: 'suggestion',
191
- docs: {
192
- description: 'Prefer native fetch API over customized fixture API.',
193
- url: getDocumentationUrl(ruleId),
194
- },
195
- messages: {
196
- preferNativeFetch: 'Prefer native fetch API over customized fixture API.',
197
- shouldUseHeaderGetter: 'Getter should be used to access response headers.',
198
- unknownError: 'Unknown error occurred in file "{{fileName}}": {{ error }}.',
199
- },
200
- fixable: 'code',
201
- schema: [],
202
- },
203
-
204
- create(context) {
205
- const sourceCode = context.sourceCode;
206
- const scopeManager = sourceCode.scopeManager;
207
-
208
- return {
209
- 'CallExpression[callee.object.object.name="fixture"][callee.object.property.name="api"]': (
210
- fixtureCall: CallExpression,
211
- // eslint-disable-next-line sonarjs/cognitive-complexity
212
- ) => {
213
- try {
214
- if (!hasAssertions(fixtureCall)) {
215
- // skip if there are no assertions, let "no-fixture" rule to handle the conversion
216
- return;
217
- }
218
-
219
- if (!(isUsedInArrayOrAsArgument(fixtureCall) || getEnclosingFunction(fixtureCall)?.async === false)) {
220
- return;
221
- }
222
-
223
- assert.ok(fixtureCall.type === 'CallExpression');
224
- const fixtureFunction = fixtureCall.callee; // e.g. fixture.api.get
225
- assert.ok(fixtureFunction.type === 'MemberExpression');
226
- const indentation = getIndentation(fixtureCall, sourceCode);
227
-
228
- const [urlArgumentNode] = fixtureCall.arguments; // e.g. `/sample-service/v1/ping`
229
- assert.ok(urlArgumentNode !== undefined);
230
-
231
- const fixtureCallInformation = {} as FixtureCallInformation;
232
- analyzeFixtureCall(fixtureCall, fixtureCallInformation, sourceCode);
233
-
234
- // convert url from `/sample-service/v1/ping` to `${BASE_PATH}/ping`
235
- const originalUrlArgumentText = sourceCode.getText(urlArgumentNode);
236
- const fetchUrlArgumentText = replaceEndpointUrlPrefixWithBasePath(originalUrlArgumentText);
237
-
238
- // fetch request argument
239
- const methodNode = fixtureFunction.property; // get/put/etc.
240
- assert.ok(methodNode.type === 'Identifier');
241
- const fetchRequestArgumentLines = [
242
- '{',
243
- ` method: '${methodNode.name.toUpperCase()}',`,
244
- ...(fixtureCallInformation.requestBody
245
- ? [` body: JSON.stringify(${sourceCode.getText(fixtureCallInformation.requestBody)}),`]
246
- : []),
247
- ...(fixtureCallInformation.requestHeaders
248
- ? [
249
- ` headers: {`,
250
- ...fixtureCallInformation.requestHeaders.map(
251
- ({ name, value }) =>
252
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions, no-nested-ternary, sonarjs/no-nested-template-literals
253
- ` ${name.type === 'Literal' ? (isValidPropertyName(name.value) ? name.value : `'${name.value}'`) : `[${sourceCode.getText(name)}]`}: ${sourceCode.getText(value)},`,
254
- ),
255
- ` },`,
256
- ]
257
- : []),
258
- '}',
259
- ].join(`\n${indentation}`);
260
-
261
- const responseVariableNameToUse = 'res';
262
- const { statusAssertion, nonStatusAssertions } = createResponseAssertions(
263
- fixtureCallInformation,
264
- sourceCode,
265
- responseVariableNameToUse,
266
- );
267
-
268
- // add variable declaration if needed
269
- const disableLintComment = '// eslint-disable-next-line @checkdigit/no-promise-instance-method';
270
- const fetchCallText = `fetch(${fetchUrlArgumentText}, ${fetchRequestArgumentLines})`;
271
- const appendingAssignmentAndAssertionText = [
272
- ...(statusAssertion !== undefined ? [statusAssertion] : []),
273
- ...nonStatusAssertions,
274
- ].join(`;\n${indentation}`);
275
- const replacementText = fixtureCallInformation.assertions
276
- ? [
277
- disableLintComment,
278
- `${fetchCallText}.then((${responseVariableNameToUse}) => {`,
279
- appendingAssignmentAndAssertionText === '' ? '' : ` ${appendingAssignmentAndAssertionText};`,
280
- ` return ${responseVariableNameToUse};`,
281
- `})`,
282
- ].join(`\n${indentation}`)
283
- : fetchCallText;
284
-
285
- context.report({
286
- node: fixtureCall,
287
- messageId: 'preferNativeFetch',
288
- fix(fixer) {
289
- return fixer.replaceText(fixtureCallInformation.fixtureNode, replacementText);
290
- },
291
- });
292
-
293
- const responsesVariable = getEnclosingStatement(fixtureCallInformation.fixtureNode);
294
- if (!responsesVariable) {
295
- return;
296
- }
297
-
298
- const responseVariableReferences = scopeManager.getDeclaredVariables(responsesVariable);
299
- const responseHeadersAccesses = getResponseHeadersAccesses(
300
- responseVariableReferences,
301
- scopeManager,
302
- sourceCode,
303
- );
304
- for (const responseHeadersAccess of responseHeadersAccesses) {
305
- if (isInvalidResponseHeadersAccess(responseHeadersAccess)) {
306
- const headerAccess = getParent(responseHeadersAccess);
307
- if (headerAccess?.type === 'MemberExpression') {
308
- const headerNameNode = headerAccess.property;
309
- const headerName = headerAccess.computed
310
- ? sourceCode.getText(headerNameNode)
311
- : `'${sourceCode.getText(headerNameNode)}'`;
312
- const headerAccessReplacementText = `${sourceCode.getText(headerAccess.object)}.get(${headerName})`;
313
-
314
- context.report({
315
- node: headerAccess,
316
- messageId: 'shouldUseHeaderGetter',
317
- fix(fixer) {
318
- return fixer.replaceText(headerAccess, headerAccessReplacementText);
319
- },
320
- });
321
- } else if (
322
- headerAccess?.type === 'CallExpression' &&
323
- responseHeadersAccess.property.type === 'Identifier' &&
324
- responseHeadersAccess.property.name === 'get'
325
- ) {
326
- const headerAccessReplacementText = `${sourceCode.getText(responseHeadersAccess.object)}.headers.get(${sourceCode.getText(headerAccess.arguments[0])})`;
327
-
328
- context.report({
329
- node: headerAccess,
330
- messageId: 'shouldUseHeaderGetter',
331
- fix(fixer) {
332
- return fixer.replaceText(headerAccess, headerAccessReplacementText);
333
- },
334
- });
335
- }
336
- }
337
- }
338
- } catch (error) {
339
- // eslint-disable-next-line no-console
340
- console.error(`Failed to apply ${ruleId} rule for file "${context.filename}":`, error);
341
- context.report({
342
- node: fixtureCall,
343
- messageId: 'unknownError',
344
- data: {
345
- fileName: context.filename,
346
- error: error instanceof Error ? error.toString() : JSON.stringify(error),
347
- },
348
- });
349
- }
350
- },
351
- };
352
- },
353
- };
354
-
355
- export default rule;
@@ -1,53 +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 isInvalidResponseHeadersAccess(responseHeadersAccess: Node): boolean {
12
- const responseHeaderAccessParent = getParent(responseHeadersAccess);
13
- if (responseHeaderAccessParent?.type === 'VariableDeclarator') {
14
- return false;
15
- }
16
-
17
- if (
18
- responseHeaderAccessParent?.type === 'CallExpression' &&
19
- responseHeaderAccessParent.callee.type === 'MemberExpression' &&
20
- responseHeaderAccessParent.callee.property.type === 'Identifier' &&
21
- responseHeaderAccessParent.callee.property.name === 'get'
22
- ) {
23
- return true;
24
- }
25
-
26
- return !(
27
- responseHeaderAccessParent?.type === 'MemberExpression' &&
28
- responseHeaderAccessParent.property.type === 'Identifier' &&
29
- responseHeaderAccessParent.property.name === 'get'
30
- );
31
- }
32
-
33
- export function hasAssertions(fixtureCall: Node): boolean {
34
- if (isBlockStatement(fixtureCall)) {
35
- return false;
36
- }
37
-
38
- const parent = getParent(fixtureCall);
39
- if (!parent) {
40
- return false;
41
- }
42
-
43
- if (
44
- parent.type === 'MemberExpression' &&
45
- parent.property.type === 'Identifier' &&
46
- parent.property.name === 'expect' &&
47
- getParent(parent)?.type === 'CallExpression'
48
- ) {
49
- return true;
50
- }
51
-
52
- return hasAssertions(parent);
53
- }
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
- }