@ihelpee/prumo-plugin-node-jest 0.0.0-stage → 0.8.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,59 @@
1
- # Temporary Holding Version
1
+ # @ihelpee/prumo-plugin-node-jest
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <p align="center">
4
+ <a href="https://www.npmjs.com/package/@ihelpee/prumo-plugin-jest"><img src="https://img.shields.io/npm/v/@ihelpee/prumo-plugin-jest?logo=npm&color=cb3837&label=npm" alt="npm version" /></a>
5
+ <a href="https://www.apache.org/licenses/LICENSE-2.0"><img src="https://img.shields.io/badge/license-Apache--2.0-blue?logo=apache&logoColor=white" alt="Apache 2.0 license" /></a>
6
+ <a href="https://github.com/ihelpee/prumo"><img src="https://img.shields.io/badge/telemetry-zero-brightgreen?logo=ghost&logoColor=white" alt="Zero telemetry" /></a>
7
+ <a href="https://nodejs.org/"><img src="https://img.shields.io/badge/node-%3E%3D20.11-339933?logo=node.js&logoColor=white" alt="Node >= 20.11" /></a>
8
+ </p>
9
+
10
+ Jest & test suite audit plugin for [Prumo](https://www.npmjs.com/package/@ihelpee/prumo). Inspects test ASTs for framework redundancies, mock tautologies, and performs surgical pruning of empty test suites.
11
+
12
+ ## Features
13
+
14
+ - **Redundant Guard Checks:** Identifies test cases asserting 401/403 HTTP status codes already proven by static invariants.
15
+ - **Redundant DTO Schema Checks:** Identifies tests checking 400 Bad Request on missing fields already guarded by `class-validator` / schema validation.
16
+ - **Tautological Mocks:** Detects circular mock verification (`jest.spyOn(...).toHaveBeenCalled()`) that only tests the mock setup.
17
+ - **DI Boot Checks:** Identifies boilerplate `toBeDefined()` checks duplicated across unit tests.
18
+ - **Surgical AST Prune:** Prunes redundant test blocks cleanly and automatically deletes empty test suites and orphan test files.
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ pnpm add -D @ihelpee/prumo-plugin-node-jest
24
+ ```
25
+
26
+ ## Usage
27
+
28
+ In your `prumo.config.ts`:
29
+
30
+ ```typescript
31
+ import { defineConfig } from '@ihelpee/prumo';
32
+ import jest from '@ihelpee/prumo-plugin-node-jest';
33
+
34
+ export default defineConfig({
35
+ plugins: [
36
+ jest(),
37
+ ],
38
+ });
39
+ ```
40
+
41
+ Or run via CLI:
42
+
43
+ ```bash
44
+ npx prumo plugin node-jest
45
+ npx prumo test-audit --prune all
46
+ ```
47
+
48
+ ## Author & Maintainer
49
+
50
+ **Alex Gotardi**
51
+ - 📧 Email: [alexgotardi@gmail.com](mailto:alexgotardi@gmail.com)
52
+ - 🐙 GitHub: [@alexgotardi](https://github.com/alexgotardi)
53
+ - 💼 LinkedIn: [linkedin.com/in/alexgotardi](https://www.linkedin.com/in/alexgotardi/)
54
+
55
+ ## Corporate Ownership & License
56
+
57
+ Copyright © 2026 **IHELPEE TECNOLOGIA LTDA** (<https://ihelpee.com>). Created and authored by [Alex Gotardi](https://github.com/alexgotardi).
58
+
59
+ Licensed under the [Apache License, Version 2.0](https://github.com/ihelpee/prumo/blob/main/LICENSE). Free for commercial and private use; attribution and the [`NOTICE`](https://github.com/ihelpee/prumo/blob/main/NOTICE) file must be preserved. The **"Prumo"** name and logo are trademarks of IHELPEE TECNOLOGIA LTDA and are not licensed under Apache 2.0 — see [Brand Protection](https://github.com/ihelpee/prumo#-corporate-ownership-licensing--brand-protection).
@@ -0,0 +1,69 @@
1
+ import { type CallExpression } from 'ts-morph';
2
+ import { type PrumoPlugin } from '@ihelpee/prumo/invariants';
3
+ export type RedundantTestCategory = 'REDUNDANT_GUARD_CHECK' | 'REDUNDANT_DTO_SCHEMA_CHECK' | 'TAUTOLOGICAL_MOCK_CHECK' | 'REDUNDANT_DI_BOOT_CHECK';
4
+ export interface RedundantTestCandidate {
5
+ id: string;
6
+ file: string;
7
+ line: number;
8
+ testName: string;
9
+ category: RedundantTestCategory;
10
+ testType: 'feature' | 'unit';
11
+ estimatedSecondsSaved: number;
12
+ reason: string;
13
+ snippet: string;
14
+ }
15
+ export interface TestAuditReport {
16
+ scannedFiles: number;
17
+ totalTestsFound: number;
18
+ redundantTestsFound: number;
19
+ estimatedTotalSecondsSaved: number;
20
+ byCategory: Record<RedundantTestCategory, number>;
21
+ byType: {
22
+ feature: number;
23
+ unit: number;
24
+ };
25
+ candidates: RedundantTestCandidate[];
26
+ }
27
+ export interface PruneResult {
28
+ prunedCount: number;
29
+ estimatedSecondsSaved: number;
30
+ prunedFiles: string[];
31
+ removedFiles: string[];
32
+ prunedCandidates: RedundantTestCandidate[];
33
+ }
34
+ export declare const DEFAULT_TEST_PATTERNS: string[];
35
+ /**
36
+ * Determina se o arquivo de teste é um Feature/Integration test pesado
37
+ * ou um Unit test rápido.
38
+ */
39
+ export declare function classifyTestType(filePath: string, fileContent: string): 'feature' | 'unit';
40
+ export declare function isTestCall(call: CallExpression): boolean;
41
+ export declare function isSuiteCall(call: CallExpression): boolean;
42
+ export declare function suiteHasTests(call: CallExpression): boolean;
43
+ export declare function removeFileAndEmptyParents(absPath: string, root: string): Promise<void>;
44
+ export declare function extractTestName(call: CallExpression): string;
45
+ export interface TestAnalysis {
46
+ isRedundant: boolean;
47
+ category?: RedundantTestCategory;
48
+ reason?: string;
49
+ }
50
+ export declare function analyzeTestBlock(call: CallExpression): TestAnalysis;
51
+ /**
52
+ * Realiza auditoria estática completa da suíte de testes.
53
+ */
54
+ export declare function auditTestSuites(root: string, patterns?: string[], ignore?: string[], knownTestFiles?: string[]): Promise<TestAuditReport>;
55
+ /**
56
+ * Poda com precisão cirúrgica de AST os testes redundantes selecionados (ou todos).
57
+ * Elimina automaticamente suítes vazias e arquivos de teste órfãos.
58
+ */
59
+ export declare function pruneRedundantTests(root: string, testIds: string[] | 'all', patterns?: string[]): Promise<PruneResult>;
60
+ export interface JestPluginOptions {
61
+ patterns?: string[];
62
+ pruneEmptySuites?: boolean;
63
+ }
64
+ /**
65
+ * Definição canônica do plugin Jest para Prumo.
66
+ */
67
+ export declare function jestPlugin(options?: JestPluginOptions): PrumoPlugin;
68
+ export default jestPlugin;
69
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"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"}
package/dist/index.js ADDED
@@ -0,0 +1,410 @@
1
+ import { Project, Node, SyntaxKind } from 'ts-morph';
2
+ import { walk, norm } from '@ihelpee/prumo/core';
3
+ import { definePlugin } from '@ihelpee/prumo/invariants';
4
+ import { resolve } from 'node:path';
5
+ import pkg from '../package.json' with { type: 'json' };
6
+ function toRelPath(root, abs) {
7
+ const nRoot = norm(root).replace(/\/+$/, '');
8
+ const nAbs = norm(abs);
9
+ return nAbs.startsWith(nRoot + '/') ? nAbs.slice(nRoot.length + 1) : nAbs;
10
+ }
11
+ export const DEFAULT_TEST_PATTERNS = [
12
+ '**/*.spec.ts',
13
+ '**/*.test.ts',
14
+ '**/*.e2e-spec.ts',
15
+ 'test/**/*.ts',
16
+ 'tests/**/*.ts',
17
+ ];
18
+ const FEATURE_TEST_HEURISTICS = [
19
+ 'supertest',
20
+ '@nestjs/testing',
21
+ 'Test.createTestingModule',
22
+ 'global.events',
23
+ 'inject(',
24
+ 'prisma',
25
+ 'typeorm',
26
+ 'pg',
27
+ 'ioredis',
28
+ ];
29
+ const FEATURE_TIME_SECONDS = 3.5;
30
+ const UNIT_TIME_SECONDS = 0.05;
31
+ /**
32
+ * Determina se o arquivo de teste é um Feature/Integration test pesado
33
+ * ou um Unit test rápido.
34
+ */
35
+ export function classifyTestType(filePath, fileContent) {
36
+ const normalized = filePath.toLowerCase();
37
+ if (normalized.endsWith('.test.ts') ||
38
+ normalized.includes('/e2e/') ||
39
+ normalized.includes('/integration/') ||
40
+ normalized.includes('/features/')) {
41
+ return 'feature';
42
+ }
43
+ for (const token of FEATURE_TEST_HEURISTICS) {
44
+ if (fileContent.includes(token))
45
+ return 'feature';
46
+ }
47
+ return 'unit';
48
+ }
49
+ export function isTestCall(call) {
50
+ const expr = call.getExpression();
51
+ const text = expr.getText();
52
+ return (text === 'test' ||
53
+ text === 'it' ||
54
+ text === 'test.only' ||
55
+ text === 'it.only' ||
56
+ text === 'test.skip' ||
57
+ text === 'it.skip' ||
58
+ text === 'test.concurrent' ||
59
+ text === 'it.concurrent' ||
60
+ text.startsWith('test.') ||
61
+ text.startsWith('it.'));
62
+ }
63
+ export function isSuiteCall(call) {
64
+ const expr = call.getExpression();
65
+ const text = expr.getText();
66
+ return (text === 'describe' ||
67
+ text === 'describe.only' ||
68
+ text === 'describe.skip' ||
69
+ text === 'describe.concurrent' ||
70
+ text === 'suite' ||
71
+ text === 'suite.only' ||
72
+ text === 'suite.skip' ||
73
+ text === 'context' ||
74
+ text === 'context.only' ||
75
+ text === 'context.skip' ||
76
+ text.startsWith('describe.') ||
77
+ text.startsWith('suite.') ||
78
+ text.startsWith('context.'));
79
+ }
80
+ export function suiteHasTests(call) {
81
+ return call.getDescendantsOfKind(SyntaxKind.CallExpression).some(isTestCall);
82
+ }
83
+ export async function removeFileAndEmptyParents(absPath, root) {
84
+ const { rm, readdir } = await import('node:fs/promises');
85
+ const { dirname } = await import('node:path');
86
+ await rm(absPath, { force: true });
87
+ let curDir = dirname(absPath);
88
+ const normalizedRoot = norm(root).replace(/\/+$/, '');
89
+ while (norm(curDir) !== normalizedRoot && norm(curDir).startsWith(normalizedRoot)) {
90
+ try {
91
+ const entries = await readdir(curDir);
92
+ if (entries.length === 0) {
93
+ await rm(curDir, { recursive: true, force: true });
94
+ curDir = dirname(curDir);
95
+ }
96
+ else {
97
+ break;
98
+ }
99
+ }
100
+ catch {
101
+ break;
102
+ }
103
+ }
104
+ }
105
+ export function extractTestName(call) {
106
+ const args = call.getArguments();
107
+ if (args.length > 0 && Node.isStringLiteral(args[0])) {
108
+ return args[0].getLiteralText();
109
+ }
110
+ return '(anonymous test)';
111
+ }
112
+ export function analyzeTestBlock(call) {
113
+ const testName = extractTestName(call).toLowerCase();
114
+ const args = call.getArguments();
115
+ if (args.length < 2)
116
+ return { isRedundant: false };
117
+ const fnArg = args[1];
118
+ if (!fnArg)
119
+ return { isRedundant: false };
120
+ const allExpectCalls = fnArg.getDescendantsOfKind(SyntaxKind.CallExpression).filter((c) => {
121
+ const exprText = c.getExpression().getText();
122
+ return exprText === 'expect' || exprText.endsWith('.expect');
123
+ });
124
+ if (allExpectCalls.length === 0) {
125
+ return { isRedundant: false };
126
+ }
127
+ // 1. DI Boot Check: apenas verifica toBeDefined() / toBeTruthy() / toBeInstanceOf
128
+ const allAreBootChecks = allExpectCalls.every((c) => {
129
+ const parent = c.getParent();
130
+ if (parent && Node.isPropertyAccessExpression(parent)) {
131
+ const parentCall = parent.getParent();
132
+ if (parentCall && Node.isCallExpression(parentCall)) {
133
+ const matcher = parent.getName();
134
+ return matcher === 'toBeDefined' || matcher === 'toBeTruthy' || matcher === 'toBeInstanceOf';
135
+ }
136
+ }
137
+ return false;
138
+ });
139
+ if (allAreBootChecks) {
140
+ return {
141
+ isRedundant: true,
142
+ category: 'REDUNDANT_DI_BOOT_CHECK',
143
+ reason: 'Apenas checa se service/controller foi instanciado (toBeDefined), duplicando o compilador do Nest.',
144
+ };
145
+ }
146
+ const fnBodyText = fnArg.getText();
147
+ // 2. Tautological Mock: apenas configura jest.spyOn / jest.fn() e espera toHaveBeenCalled()
148
+ const hasSpies = fnBodyText.includes('spyOn(') || fnBodyText.includes('jest.fn(');
149
+ const onlyCallsMockAssertions = allExpectCalls.every((c) => {
150
+ const parent = c.getParent();
151
+ if (parent && Node.isPropertyAccessExpression(parent)) {
152
+ const matcher = parent.getName();
153
+ return (matcher === 'toHaveBeenCalled' ||
154
+ matcher === 'toHaveBeenCalledTimes' ||
155
+ matcher === 'toHaveBeenCalledWith');
156
+ }
157
+ return false;
158
+ });
159
+ if (hasSpies && onlyCallsMockAssertions && !fnBodyText.includes('expect(' + 'result') && !fnBodyText.includes('expect(' + 'res')) {
160
+ return {
161
+ isRedundant: true,
162
+ category: 'TAUTOLOGICAL_MOCK_CHECK',
163
+ reason: 'Teste tautológico: mocka um método e apenas testa se o mock foi chamado.',
164
+ };
165
+ }
166
+ // 3. Guard Check: apenas asserção de 401 / 403 / Forbidden / Unauthorized
167
+ const assertsUnauthorized = fnBodyText.includes('401') ||
168
+ fnBodyText.includes('403') ||
169
+ fnBodyText.includes('Unauthorized') ||
170
+ fnBodyText.includes('Forbidden');
171
+ const isGuardName = testName.includes('unauthenticated') ||
172
+ testName.includes('unauthorized') ||
173
+ testName.includes('forbidden') ||
174
+ testName.includes('without token') ||
175
+ testName.includes('no auth') ||
176
+ testName.includes('guard') ||
177
+ testName.includes('401') ||
178
+ testName.includes('403');
179
+ if (isGuardName && assertsUnauthorized) {
180
+ const hasDomainExpectations = allExpectCalls.some((c) => {
181
+ const text = c.getText();
182
+ return text.includes('.body') || text.includes('.json()') || text.includes('service.');
183
+ });
184
+ if (!hasDomainExpectations) {
185
+ return {
186
+ isRedundant: true,
187
+ category: 'REDUNDANT_GUARD_CHECK',
188
+ reason: 'Verificação redundante de HTTP 401/403: o guard já é garantido via invariante AST mutation-routes-guarded.',
189
+ };
190
+ }
191
+ }
192
+ // 4. DTO Validation Check: apenas asserção de 400 Bad Request
193
+ const assertsBadRequest = fnBodyText.includes('400') || fnBodyText.includes('Bad Request');
194
+ const isDtoName = testName.includes('missing') ||
195
+ testName.includes('invalid') ||
196
+ testName.includes('validation') ||
197
+ testName.includes('payload') ||
198
+ testName.includes('dto') ||
199
+ testName.includes('400');
200
+ if (isDtoName && assertsBadRequest) {
201
+ const hasDeepExpectations = allExpectCalls.length > 2;
202
+ if (!hasDeepExpectations) {
203
+ return {
204
+ isRedundant: true,
205
+ category: 'REDUNDANT_DTO_SCHEMA_CHECK',
206
+ reason: 'Verificação redundante de DTO schema: class-validator já é garantido estaticamente pela invariante dto-has-validation.',
207
+ };
208
+ }
209
+ }
210
+ return { isRedundant: false };
211
+ }
212
+ /**
213
+ * Realiza auditoria estática completa da suíte de testes.
214
+ */
215
+ export async function auditTestSuites(root, patterns = DEFAULT_TEST_PATTERNS, ignore, knownTestFiles) {
216
+ const picomatch = (await import('picomatch')).default;
217
+ const isMatch = picomatch(patterns, { dot: true });
218
+ const isIgnored = ignore && ignore.length > 0 ? picomatch(ignore, { dot: true }) : () => false;
219
+ let testFiles;
220
+ if (knownTestFiles) {
221
+ testFiles = knownTestFiles.filter((f) => isMatch(norm(f)) && !isIgnored(norm(f)));
222
+ }
223
+ else {
224
+ const allFiles = await walk(root, '.', {
225
+ extensions: ['.ts', '.tsx', '.js'],
226
+ ignorePatterns: ignore,
227
+ });
228
+ testFiles = allFiles
229
+ .filter((f) => !f.includes('node_modules') && !f.includes('/dist/'))
230
+ .filter((f) => isMatch(norm(f)) && !isIgnored(norm(f)));
231
+ }
232
+ const project = new Project({
233
+ useInMemoryFileSystem: false,
234
+ compilerOptions: {
235
+ target: 99,
236
+ experimentalDecorators: true,
237
+ emitDecoratorMetadata: true,
238
+ strict: false,
239
+ noResolve: true,
240
+ },
241
+ });
242
+ for (const file of testFiles) {
243
+ project.addSourceFileAtPath(resolve(root, file));
244
+ }
245
+ const sourceFiles = project.getSourceFiles();
246
+ let totalTestsFound = 0;
247
+ const candidates = [];
248
+ const byCategory = {
249
+ REDUNDANT_GUARD_CHECK: 0,
250
+ REDUNDANT_DTO_SCHEMA_CHECK: 0,
251
+ TAUTOLOGICAL_MOCK_CHECK: 0,
252
+ REDUNDANT_DI_BOOT_CHECK: 0,
253
+ };
254
+ const byType = {
255
+ feature: 0,
256
+ unit: 0,
257
+ };
258
+ for (const sf of sourceFiles) {
259
+ const relFile = norm(toRelPath(root, sf.getFilePath()));
260
+ const content = sf.getFullText();
261
+ const testType = classifyTestType(relFile, content);
262
+ const callExpressions = sf.getDescendantsOfKind(SyntaxKind.CallExpression);
263
+ for (const call of callExpressions) {
264
+ if (!isTestCall(call))
265
+ continue;
266
+ totalTestsFound++;
267
+ const analysis = analyzeTestBlock(call);
268
+ if (analysis.isRedundant && analysis.category) {
269
+ const line = call.getStartLineNumber();
270
+ const testName = extractTestName(call);
271
+ const estimatedSecondsSaved = testType === 'feature' ? FEATURE_TIME_SECONDS : UNIT_TIME_SECONDS;
272
+ byCategory[analysis.category]++;
273
+ byType[testType]++;
274
+ candidates.push({
275
+ id: `${relFile}:${line}`,
276
+ file: relFile,
277
+ line,
278
+ testName,
279
+ category: analysis.category,
280
+ testType,
281
+ estimatedSecondsSaved,
282
+ reason: analysis.reason ?? 'Redundant framework test duplicating Prumo AST invariants.',
283
+ snippet: call.getText().slice(0, 300),
284
+ });
285
+ }
286
+ }
287
+ }
288
+ const estimatedTotalSecondsSaved = Number(candidates.reduce((acc, c) => acc + c.estimatedSecondsSaved, 0).toFixed(2));
289
+ return {
290
+ scannedFiles: sourceFiles.length,
291
+ totalTestsFound,
292
+ redundantTestsFound: candidates.length,
293
+ estimatedTotalSecondsSaved,
294
+ byCategory,
295
+ byType,
296
+ candidates,
297
+ };
298
+ }
299
+ /**
300
+ * Poda com precisão cirúrgica de AST os testes redundantes selecionados (ou todos).
301
+ * Elimina automaticamente suítes vazias e arquivos de teste órfãos.
302
+ */
303
+ export async function pruneRedundantTests(root, testIds, patterns = DEFAULT_TEST_PATTERNS) {
304
+ const audit = await auditTestSuites(root, patterns);
305
+ const isAll = testIds === 'all' ||
306
+ (Array.isArray(testIds) && (testIds.length === 0 || testIds.includes('all')));
307
+ const targetIds = isAll
308
+ ? new Set(audit.candidates.map((c) => c.id))
309
+ : new Set(testIds);
310
+ const candidatesToPrune = audit.candidates.filter((c) => targetIds.has(c.id));
311
+ if (candidatesToPrune.length === 0) {
312
+ return {
313
+ prunedCount: 0,
314
+ estimatedSecondsSaved: 0,
315
+ prunedFiles: [],
316
+ removedFiles: [],
317
+ prunedCandidates: [],
318
+ };
319
+ }
320
+ const byFile = new Map();
321
+ for (const c of candidatesToPrune) {
322
+ const list = byFile.get(c.file) ?? [];
323
+ list.push(c);
324
+ byFile.set(c.file, list);
325
+ }
326
+ const project = new Project({
327
+ useInMemoryFileSystem: false,
328
+ compilerOptions: {
329
+ target: 99,
330
+ experimentalDecorators: true,
331
+ emitDecoratorMetadata: true,
332
+ strict: false,
333
+ noResolve: true,
334
+ },
335
+ });
336
+ const prunedFiles = [];
337
+ const removedFiles = [];
338
+ for (const [file, candidates] of byFile.entries()) {
339
+ const absPath = resolve(root, file);
340
+ const sf = project.addSourceFileAtPath(absPath);
341
+ const targetLines = new Set(candidates.map((c) => c.line));
342
+ const calls = sf.getDescendantsOfKind(SyntaxKind.CallExpression).filter(isTestCall);
343
+ const toRemove = calls.filter((c) => targetLines.has(c.getStartLineNumber()));
344
+ for (const call of toRemove) {
345
+ const stmt = call.getParentIfKind(SyntaxKind.ExpressionStatement);
346
+ if (stmt && !stmt.wasForgotten()) {
347
+ stmt.remove();
348
+ }
349
+ else if (!call.wasForgotten()) {
350
+ call.replaceWithText('');
351
+ }
352
+ }
353
+ // Remove suítes (describe/suite/context) que ficaram vazias (sem nenhum teste restante)
354
+ let removedSuite = true;
355
+ while (removedSuite) {
356
+ removedSuite = false;
357
+ const suiteCalls = sf
358
+ .getDescendantsOfKind(SyntaxKind.CallExpression)
359
+ .filter(isSuiteCall);
360
+ for (const call of suiteCalls.reverse()) {
361
+ if (call.wasForgotten())
362
+ continue;
363
+ if (!suiteHasTests(call)) {
364
+ const stmt = call.getParentIfKind(SyntaxKind.ExpressionStatement);
365
+ if (stmt && !stmt.wasForgotten()) {
366
+ stmt.remove();
367
+ removedSuite = true;
368
+ }
369
+ else if (!call.wasForgotten()) {
370
+ call.replaceWithText('');
371
+ removedSuite = true;
372
+ }
373
+ }
374
+ }
375
+ }
376
+ const remainingTests = sf
377
+ .getDescendantsOfKind(SyntaxKind.CallExpression)
378
+ .filter(isTestCall);
379
+ if (remainingTests.length === 0) {
380
+ // Todos os testes da suíte/arquivo foram purgados: remove o arquivo de teste
381
+ project.removeSourceFile(sf);
382
+ await removeFileAndEmptyParents(absPath, root);
383
+ removedFiles.push(file);
384
+ }
385
+ else {
386
+ await sf.save();
387
+ prunedFiles.push(file);
388
+ }
389
+ }
390
+ const estimatedSecondsSaved = Number(candidatesToPrune.reduce((acc, c) => acc + c.estimatedSecondsSaved, 0).toFixed(2));
391
+ return {
392
+ prunedCount: candidatesToPrune.length,
393
+ estimatedSecondsSaved,
394
+ prunedFiles,
395
+ removedFiles,
396
+ prunedCandidates: candidatesToPrune,
397
+ };
398
+ }
399
+ /**
400
+ * Definição canônica do plugin Jest para Prumo.
401
+ */
402
+ export function jestPlugin(options = {}) {
403
+ return definePlugin({
404
+ name: 'jest',
405
+ version: pkg.version,
406
+ description: 'Jest AST inspection, mock tautology analysis, and surgical test pruning.',
407
+ rules: [],
408
+ });
409
+ }
410
+ export default jestPlugin;
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@ihelpee/prumo-plugin-node-jest",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.8.4",
4
+ "type": "module",
5
+ "description": "Jest & test suite audit plugin for Prumo: AST redundancy detection, mock analysis, and surgical test pruning.",
6
+ "author": "Alex Gotardi <alexgotardi@gmail.com> (https://github.com/alexgotardi)",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "package.json",
19
+ "README.md"
20
+ ],
21
+ "sideEffects": false,
22
+ "license": "Apache-2.0",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/ihelpee/prumo.git"
26
+ },
27
+ "engines": {
28
+ "node": ">=20.11"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "dependencies": {
34
+ "@ihelpee/prumo": "0.9.0",
35
+ "picomatch": "^4.0.2",
36
+ "ts-morph": "^24.0.0"
37
+ },
38
+ "devDependencies": {
39
+ "@types/picomatch": "^3.0.1"
40
+ }
6
41
  }