@webpieces/dev-config 0.2.94 → 0.2.97

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 (183) hide show
  1. package/config/eslint/base.mjs +1 -1
  2. package/executors.json +6 -91
  3. package/package.json +6 -19
  4. package/{executors → src/executors}/help/executor.d.ts +4 -2
  5. package/src/executors/help/executor.js.map +1 -0
  6. package/{executors → src/executors}/validate-eslint-sync/executor.d.ts +3 -2
  7. package/src/executors/validate-eslint-sync/executor.js.map +1 -0
  8. package/{executors → src/executors}/validate-versions-locked/executor.js +5 -3
  9. package/src/executors/validate-versions-locked/executor.js.map +1 -0
  10. package/src/generators/init/generator.js.map +1 -1
  11. package/src/index.d.ts +1 -1
  12. package/src/index.js +1 -1
  13. package/src/index.js.map +1 -1
  14. package/src/plugin.d.ts +86 -0
  15. package/{plugin.js → src/plugin.js} +31 -15
  16. package/src/plugin.js.map +1 -0
  17. package/src/toError.d.ts +5 -0
  18. package/src/toError.js +37 -0
  19. package/src/toError.js.map +1 -0
  20. package/templates/eslint.webpieces.config.mjs +1 -1
  21. package/templates/webpieces.exceptions.md +15 -15
  22. package/architecture/executors/diff-utils.d.ts +0 -24
  23. package/architecture/executors/diff-utils.js +0 -119
  24. package/architecture/executors/diff-utils.js.map +0 -1
  25. package/architecture/executors/diff-utils.ts +0 -127
  26. package/architecture/executors/generate/executor.d.ts +0 -16
  27. package/architecture/executors/generate/executor.js +0 -44
  28. package/architecture/executors/generate/executor.js.map +0 -1
  29. package/architecture/executors/generate/executor.ts +0 -59
  30. package/architecture/executors/generate/schema.json +0 -14
  31. package/architecture/executors/validate-architecture-unchanged/executor.d.ts +0 -17
  32. package/architecture/executors/validate-architecture-unchanged/executor.js +0 -229
  33. package/architecture/executors/validate-architecture-unchanged/executor.js.map +0 -1
  34. package/architecture/executors/validate-architecture-unchanged/executor.ts +0 -251
  35. package/architecture/executors/validate-architecture-unchanged/schema.json +0 -14
  36. package/architecture/executors/validate-code/executor.d.ts +0 -78
  37. package/architecture/executors/validate-code/executor.js +0 -243
  38. package/architecture/executors/validate-code/executor.js.map +0 -1
  39. package/architecture/executors/validate-code/executor.ts +0 -406
  40. package/architecture/executors/validate-code/schema.json +0 -227
  41. package/architecture/executors/validate-dtos/executor.d.ts +0 -42
  42. package/architecture/executors/validate-dtos/executor.js +0 -561
  43. package/architecture/executors/validate-dtos/executor.js.map +0 -1
  44. package/architecture/executors/validate-dtos/executor.ts +0 -689
  45. package/architecture/executors/validate-dtos/schema.json +0 -33
  46. package/architecture/executors/validate-modified-files/executor.d.ts +0 -25
  47. package/architecture/executors/validate-modified-files/executor.js +0 -501
  48. package/architecture/executors/validate-modified-files/executor.js.map +0 -1
  49. package/architecture/executors/validate-modified-files/executor.ts +0 -571
  50. package/architecture/executors/validate-modified-files/schema.json +0 -25
  51. package/architecture/executors/validate-modified-methods/executor.d.ts +0 -31
  52. package/architecture/executors/validate-modified-methods/executor.js +0 -694
  53. package/architecture/executors/validate-modified-methods/executor.js.map +0 -1
  54. package/architecture/executors/validate-modified-methods/executor.ts +0 -797
  55. package/architecture/executors/validate-modified-methods/schema.json +0 -25
  56. package/architecture/executors/validate-new-methods/executor.d.ts +0 -28
  57. package/architecture/executors/validate-new-methods/executor.js +0 -513
  58. package/architecture/executors/validate-new-methods/executor.js.map +0 -1
  59. package/architecture/executors/validate-new-methods/executor.ts +0 -584
  60. package/architecture/executors/validate-new-methods/schema.json +0 -25
  61. package/architecture/executors/validate-no-any-unknown/executor.d.ts +0 -42
  62. package/architecture/executors/validate-no-any-unknown/executor.js +0 -462
  63. package/architecture/executors/validate-no-any-unknown/executor.js.map +0 -1
  64. package/architecture/executors/validate-no-any-unknown/executor.ts +0 -540
  65. package/architecture/executors/validate-no-any-unknown/schema.json +0 -24
  66. package/architecture/executors/validate-no-architecture-cycles/executor.d.ts +0 -16
  67. package/architecture/executors/validate-no-architecture-cycles/executor.js +0 -48
  68. package/architecture/executors/validate-no-architecture-cycles/executor.js.map +0 -1
  69. package/architecture/executors/validate-no-architecture-cycles/executor.ts +0 -60
  70. package/architecture/executors/validate-no-architecture-cycles/schema.json +0 -8
  71. package/architecture/executors/validate-no-destructure/executor.d.ts +0 -52
  72. package/architecture/executors/validate-no-destructure/executor.js +0 -491
  73. package/architecture/executors/validate-no-destructure/executor.js.map +0 -1
  74. package/architecture/executors/validate-no-destructure/executor.ts +0 -578
  75. package/architecture/executors/validate-no-destructure/schema.json +0 -24
  76. package/architecture/executors/validate-no-direct-api-resolver/executor.d.ts +0 -47
  77. package/architecture/executors/validate-no-direct-api-resolver/executor.js +0 -566
  78. package/architecture/executors/validate-no-direct-api-resolver/executor.js.map +0 -1
  79. package/architecture/executors/validate-no-direct-api-resolver/executor.ts +0 -666
  80. package/architecture/executors/validate-no-direct-api-resolver/schema.json +0 -29
  81. package/architecture/executors/validate-no-inline-types/executor.d.ts +0 -91
  82. package/architecture/executors/validate-no-inline-types/executor.js +0 -669
  83. package/architecture/executors/validate-no-inline-types/executor.js.map +0 -1
  84. package/architecture/executors/validate-no-inline-types/executor.ts +0 -775
  85. package/architecture/executors/validate-no-inline-types/schema.json +0 -24
  86. package/architecture/executors/validate-no-skiplevel-deps/executor.d.ts +0 -19
  87. package/architecture/executors/validate-no-skiplevel-deps/executor.js +0 -227
  88. package/architecture/executors/validate-no-skiplevel-deps/executor.js.map +0 -1
  89. package/architecture/executors/validate-no-skiplevel-deps/executor.ts +0 -267
  90. package/architecture/executors/validate-no-skiplevel-deps/schema.json +0 -8
  91. package/architecture/executors/validate-packagejson/executor.d.ts +0 -16
  92. package/architecture/executors/validate-packagejson/executor.js +0 -57
  93. package/architecture/executors/validate-packagejson/executor.js.map +0 -1
  94. package/architecture/executors/validate-packagejson/executor.ts +0 -74
  95. package/architecture/executors/validate-packagejson/schema.json +0 -8
  96. package/architecture/executors/validate-prisma-converters/executor.d.ts +0 -60
  97. package/architecture/executors/validate-prisma-converters/executor.js +0 -634
  98. package/architecture/executors/validate-prisma-converters/executor.js.map +0 -1
  99. package/architecture/executors/validate-prisma-converters/executor.ts +0 -822
  100. package/architecture/executors/validate-prisma-converters/schema.json +0 -38
  101. package/architecture/executors/validate-return-types/executor.d.ts +0 -29
  102. package/architecture/executors/validate-return-types/executor.js +0 -439
  103. package/architecture/executors/validate-return-types/executor.js.map +0 -1
  104. package/architecture/executors/validate-return-types/executor.ts +0 -524
  105. package/architecture/executors/validate-return-types/schema.json +0 -24
  106. package/architecture/executors/visualize/executor.d.ts +0 -17
  107. package/architecture/executors/visualize/executor.js +0 -49
  108. package/architecture/executors/visualize/executor.js.map +0 -1
  109. package/architecture/executors/visualize/executor.ts +0 -63
  110. package/architecture/executors/visualize/schema.json +0 -14
  111. package/architecture/index.d.ts +0 -19
  112. package/architecture/index.js +0 -23
  113. package/architecture/index.js.map +0 -1
  114. package/architecture/index.ts +0 -20
  115. package/architecture/lib/graph-comparator.d.ts +0 -39
  116. package/architecture/lib/graph-comparator.js +0 -100
  117. package/architecture/lib/graph-comparator.js.map +0 -1
  118. package/architecture/lib/graph-comparator.ts +0 -141
  119. package/architecture/lib/graph-generator.d.ts +0 -19
  120. package/architecture/lib/graph-generator.js +0 -84
  121. package/architecture/lib/graph-generator.js.map +0 -1
  122. package/architecture/lib/graph-generator.ts +0 -97
  123. package/architecture/lib/graph-loader.d.ts +0 -31
  124. package/architecture/lib/graph-loader.js +0 -98
  125. package/architecture/lib/graph-loader.js.map +0 -1
  126. package/architecture/lib/graph-loader.ts +0 -116
  127. package/architecture/lib/graph-sorter.d.ts +0 -37
  128. package/architecture/lib/graph-sorter.js +0 -110
  129. package/architecture/lib/graph-sorter.js.map +0 -1
  130. package/architecture/lib/graph-sorter.ts +0 -137
  131. package/architecture/lib/graph-visualizer.d.ts +0 -29
  132. package/architecture/lib/graph-visualizer.js +0 -217
  133. package/architecture/lib/graph-visualizer.js.map +0 -1
  134. package/architecture/lib/graph-visualizer.ts +0 -231
  135. package/architecture/lib/package-validator.d.ts +0 -38
  136. package/architecture/lib/package-validator.js +0 -126
  137. package/architecture/lib/package-validator.js.map +0 -1
  138. package/architecture/lib/package-validator.ts +0 -170
  139. package/eslint-plugin/__tests__/catch-error-pattern.test.ts +0 -359
  140. package/eslint-plugin/__tests__/max-file-lines.test.ts +0 -207
  141. package/eslint-plugin/__tests__/max-method-lines.test.ts +0 -258
  142. package/eslint-plugin/__tests__/no-unmanaged-exceptions.test.ts +0 -359
  143. package/eslint-plugin/index.d.ts +0 -23
  144. package/eslint-plugin/index.js +0 -30
  145. package/eslint-plugin/index.js.map +0 -1
  146. package/eslint-plugin/index.ts +0 -29
  147. package/eslint-plugin/rules/catch-error-pattern.d.ts +0 -11
  148. package/eslint-plugin/rules/catch-error-pattern.js +0 -196
  149. package/eslint-plugin/rules/catch-error-pattern.js.map +0 -1
  150. package/eslint-plugin/rules/catch-error-pattern.ts +0 -281
  151. package/eslint-plugin/rules/enforce-architecture.d.ts +0 -15
  152. package/eslint-plugin/rules/enforce-architecture.js +0 -476
  153. package/eslint-plugin/rules/enforce-architecture.js.map +0 -1
  154. package/eslint-plugin/rules/enforce-architecture.ts +0 -543
  155. package/eslint-plugin/rules/max-file-lines.d.ts +0 -12
  156. package/eslint-plugin/rules/max-file-lines.js +0 -257
  157. package/eslint-plugin/rules/max-file-lines.js.map +0 -1
  158. package/eslint-plugin/rules/max-file-lines.ts +0 -272
  159. package/eslint-plugin/rules/max-method-lines.d.ts +0 -12
  160. package/eslint-plugin/rules/max-method-lines.js +0 -240
  161. package/eslint-plugin/rules/max-method-lines.js.map +0 -1
  162. package/eslint-plugin/rules/max-method-lines.ts +0 -287
  163. package/eslint-plugin/rules/no-unmanaged-exceptions.d.ts +0 -22
  164. package/eslint-plugin/rules/no-unmanaged-exceptions.js +0 -160
  165. package/eslint-plugin/rules/no-unmanaged-exceptions.js.map +0 -1
  166. package/eslint-plugin/rules/no-unmanaged-exceptions.ts +0 -179
  167. package/executors/help/executor.js.map +0 -1
  168. package/executors/help/executor.ts +0 -61
  169. package/executors/validate-eslint-sync/executor.js.map +0 -1
  170. package/executors/validate-eslint-sync/executor.ts +0 -83
  171. package/executors/validate-versions-locked/executor.js.map +0 -1
  172. package/executors/validate-versions-locked/executor.ts +0 -367
  173. package/plugin/README.md +0 -243
  174. package/plugin/index.d.ts +0 -4
  175. package/plugin/index.js +0 -8
  176. package/plugin/index.js.map +0 -1
  177. package/plugin/index.ts +0 -4
  178. /package/{executors → src/executors}/help/executor.js +0 -0
  179. /package/{executors → src/executors}/help/schema.json +0 -0
  180. /package/{executors → src/executors}/validate-eslint-sync/executor.js +0 -0
  181. /package/{executors → src/executors}/validate-eslint-sync/schema.json +0 -0
  182. /package/{executors → src/executors}/validate-versions-locked/executor.d.ts +0 -0
  183. /package/{executors → src/executors}/validate-versions-locked/schema.json +0 -0
@@ -1,666 +0,0 @@
1
- /**
2
- * Validate No Direct API in Resolver Executor
3
- *
4
- * Validates two Angular anti-patterns using LINE-BASED detection:
5
- *
6
- * ============================================================================
7
- * VIOLATIONS (BAD) - These patterns are flagged:
8
- * ============================================================================
9
- *
10
- * 1. In *.routes.ts files: inject(XxxApi) — resolvers should inject services, not APIs directly
11
- * 2. In *.component.ts files: this.<field>.snapshot.data — components should subscribe to
12
- * service BehaviorSubjects, not read route snapshot data
13
- *
14
- * ============================================================================
15
- * CORRECT PATTERNS (GOOD)
16
- * ============================================================================
17
- *
18
- * 1. In resolvers: inject(XxxService) which calls the API internally
19
- * 2. In components: this.myService.someObservable$ (subscribe to service BehaviorSubjects)
20
- *
21
- * ============================================================================
22
- * MODES (LINE-BASED)
23
- * ============================================================================
24
- * - OFF: Skip validation entirely
25
- * - MODIFIED_CODE: Flag violations on changed lines (lines in diff hunks)
26
- * - NEW_AND_MODIFIED_METHODS: Flag violations in new/modified method/route scopes
27
- * - MODIFIED_FILES: Flag ALL violations in files that were modified
28
- *
29
- * ============================================================================
30
- * ESCAPE HATCH
31
- * ============================================================================
32
- * Add comment above the violation:
33
- * // webpieces-disable no-direct-api-resolver -- [your justification]
34
- * const myApi = inject(MyApi);
35
- */
36
-
37
- import type { ExecutorContext } from '@nx/devkit';
38
- import { execSync } from 'child_process';
39
- import * as fs from 'fs';
40
- import * as path from 'path';
41
- import * as ts from 'typescript';
42
- import { getFileDiff, getChangedLineNumbers, findNewMethodSignaturesInDiff } from '../diff-utils';
43
-
44
- export type NoDirectApiResolverMode = 'OFF' | 'MODIFIED_CODE' | 'NEW_AND_MODIFIED_METHODS' | 'MODIFIED_FILES';
45
-
46
- export interface ValidateNoDirectApiResolverOptions {
47
- mode?: NoDirectApiResolverMode;
48
- disableAllowed?: boolean;
49
- ignoreModifiedUntilEpoch?: number;
50
- enforcePaths?: string[];
51
- }
52
-
53
- export interface ExecutorResult {
54
- success: boolean;
55
- }
56
-
57
- interface Violation {
58
- file: string;
59
- line: number;
60
- column: number;
61
- context: string;
62
- }
63
-
64
- interface ViolationInfo {
65
- line: number;
66
- column: number;
67
- context: string;
68
- hasDisableComment: boolean;
69
- }
70
-
71
- /**
72
- * Get changed TypeScript files between base and head (or working tree if head not specified).
73
- */
74
- // webpieces-disable max-lines-new-methods -- Git command handling with untracked files requires multiple code paths
75
- function getChangedTypeScriptFiles(workspaceRoot: string, base: string, head?: string): string[] {
76
- try {
77
- const diffTarget = head ? `${base} ${head}` : base;
78
- const output = execSync(`git diff --name-only ${diffTarget} -- '*.ts' '*.tsx'`, {
79
- cwd: workspaceRoot,
80
- encoding: 'utf-8',
81
- });
82
- const changedFiles = output
83
- .trim()
84
- .split('\n')
85
- .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
86
-
87
- if (!head) {
88
- try {
89
- const untrackedOutput = execSync(`git ls-files --others --exclude-standard '*.ts' '*.tsx'`, {
90
- cwd: workspaceRoot,
91
- encoding: 'utf-8',
92
- });
93
- const untrackedFiles = untrackedOutput
94
- .trim()
95
- .split('\n')
96
- .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
97
- const allFiles = new Set([...changedFiles, ...untrackedFiles]);
98
- return Array.from(allFiles);
99
- } catch {
100
- return changedFiles;
101
- }
102
- }
103
-
104
- return changedFiles;
105
- } catch {
106
- return [];
107
- }
108
- }
109
-
110
- /**
111
- * Check if a line contains a webpieces-disable comment for no-direct-api-resolver.
112
- */
113
- function hasDisableComment(lines: string[], lineNumber: number): boolean {
114
- const startCheck = Math.max(0, lineNumber - 5);
115
- for (let i = lineNumber - 2; i >= startCheck; i--) {
116
- const line = lines[i]?.trim() ?? '';
117
- if (line.startsWith('function ') || line.startsWith('class ') || line.endsWith('}')) {
118
- break;
119
- }
120
- if (line.includes('webpieces-disable') && line.includes('no-direct-api-resolver')) {
121
- return true;
122
- }
123
- }
124
- return false;
125
- }
126
-
127
- /**
128
- * Auto-detect the base branch by finding the merge-base with origin/main.
129
- */
130
- function detectBase(workspaceRoot: string): string | null {
131
- try {
132
- const mergeBase = execSync('git merge-base HEAD origin/main', {
133
- cwd: workspaceRoot,
134
- encoding: 'utf-8',
135
- stdio: ['pipe', 'pipe', 'pipe'],
136
- }).trim();
137
-
138
- if (mergeBase) {
139
- return mergeBase;
140
- }
141
- } catch {
142
- try {
143
- const mergeBase = execSync('git merge-base HEAD main', {
144
- cwd: workspaceRoot,
145
- encoding: 'utf-8',
146
- stdio: ['pipe', 'pipe', 'pipe'],
147
- }).trim();
148
-
149
- if (mergeBase) {
150
- return mergeBase;
151
- }
152
- } catch {
153
- // Ignore
154
- }
155
- }
156
- return null;
157
- }
158
-
159
- /**
160
- * Find inject(XxxApi) calls in *.routes.ts files.
161
- * Flags any CallExpression where callee is `inject` and the first argument is an identifier ending with `Api`.
162
- */
163
- function findDirectApiInjections(filePath: string, workspaceRoot: string, disableAllowed: boolean): ViolationInfo[] {
164
- if (!filePath.endsWith('.routes.ts')) return [];
165
-
166
- const fullPath = path.join(workspaceRoot, filePath);
167
- if (!fs.existsSync(fullPath)) return [];
168
-
169
- const content = fs.readFileSync(fullPath, 'utf-8');
170
- const fileLines = content.split('\n');
171
- const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
172
-
173
- const violations: ViolationInfo[] = [];
174
-
175
- function visit(node: ts.Node): void {
176
- try {
177
- if (ts.isCallExpression(node)) {
178
- const callee = node.expression;
179
- if (ts.isIdentifier(callee) && callee.text === 'inject') {
180
- const firstArg = node.arguments[0];
181
- if (firstArg && ts.isIdentifier(firstArg) && firstArg.text.endsWith('Api')) {
182
- const startPos = node.getStart(sourceFile);
183
- if (startPos >= 0) {
184
- const pos = sourceFile.getLineAndCharacterOfPosition(startPos);
185
- const line = pos.line + 1;
186
- const column = pos.character + 1;
187
- const disabled = hasDisableComment(fileLines, line);
188
-
189
- if (!disableAllowed && disabled) {
190
- violations.push({ line, column, context: `inject(${firstArg.text}) in route resolver`, hasDisableComment: false });
191
- } else {
192
- violations.push({ line, column, context: `inject(${firstArg.text}) in route resolver`, hasDisableComment: disabled });
193
- }
194
- }
195
- }
196
- }
197
- }
198
- } catch {
199
- // Skip nodes that cause errors during analysis
200
- }
201
-
202
- ts.forEachChild(node, visit);
203
- }
204
-
205
- visit(sourceFile);
206
- return violations;
207
- }
208
-
209
- /**
210
- * Find this.<field>.snapshot.data access patterns in *.component.ts files.
211
- * Flags PropertyAccessExpression chains: this.<anything>.snapshot.data
212
- */
213
- function findSnapshotDataAccess(filePath: string, workspaceRoot: string, disableAllowed: boolean): ViolationInfo[] {
214
- if (!filePath.endsWith('.component.ts')) return [];
215
-
216
- const fullPath = path.join(workspaceRoot, filePath);
217
- if (!fs.existsSync(fullPath)) return [];
218
-
219
- const content = fs.readFileSync(fullPath, 'utf-8');
220
- const fileLines = content.split('\n');
221
- const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
222
-
223
- const violations: ViolationInfo[] = [];
224
-
225
- function visit(node: ts.Node): void {
226
- try {
227
- // Looking for: this.<field>.snapshot.data
228
- // AST shape: PropertyAccessExpression(.data) -> PropertyAccessExpression(.snapshot) -> PropertyAccessExpression(.<field>) -> this
229
- if (ts.isPropertyAccessExpression(node) && node.name.text === 'data') {
230
- const snapshotAccess = node.expression;
231
- if (ts.isPropertyAccessExpression(snapshotAccess) && snapshotAccess.name.text === 'snapshot') {
232
- const fieldAccess = snapshotAccess.expression;
233
- if (ts.isPropertyAccessExpression(fieldAccess)) {
234
- const receiver = fieldAccess.expression;
235
- if (receiver.kind === ts.SyntaxKind.ThisKeyword) {
236
- const fieldName = fieldAccess.name.text;
237
- const startPos = node.getStart(sourceFile);
238
- if (startPos >= 0) {
239
- const pos = sourceFile.getLineAndCharacterOfPosition(startPos);
240
- const line = pos.line + 1;
241
- const column = pos.character + 1;
242
- const disabled = hasDisableComment(fileLines, line);
243
-
244
- if (!disableAllowed && disabled) {
245
- violations.push({ line, column, context: `this.${fieldName}.snapshot.data in component`, hasDisableComment: false });
246
- } else {
247
- violations.push({ line, column, context: `this.${fieldName}.snapshot.data in component`, hasDisableComment: disabled });
248
- }
249
- }
250
- }
251
- }
252
- }
253
- }
254
- } catch {
255
- // Skip nodes that cause errors during analysis
256
- }
257
-
258
- ts.forEachChild(node, visit);
259
- }
260
-
261
- visit(sourceFile);
262
- return violations;
263
- }
264
-
265
- /**
266
- * Find all violations in a file (both inject(Api) and snapshot.data patterns).
267
- */
268
- function findViolationsInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean): ViolationInfo[] {
269
- const apiViolations = findDirectApiInjections(filePath, workspaceRoot, disableAllowed);
270
- const snapshotViolations = findSnapshotDataAccess(filePath, workspaceRoot, disableAllowed);
271
- return [...apiViolations, ...snapshotViolations];
272
- }
273
-
274
- /**
275
- * MODIFIED_CODE mode: Flag violations on changed lines in diff hunks.
276
- */
277
- // webpieces-disable max-lines-new-methods -- File iteration with diff parsing and line filtering
278
- function findViolationsForModifiedCode(
279
- workspaceRoot: string,
280
- changedFiles: string[],
281
- base: string,
282
- head: string | undefined,
283
- disableAllowed: boolean
284
- ): Violation[] {
285
- const violations: Violation[] = [];
286
-
287
- for (const file of changedFiles) {
288
- const diff = getFileDiff(workspaceRoot, file, base, head);
289
- const changedLines = getChangedLineNumbers(diff);
290
-
291
- if (changedLines.size === 0) continue;
292
-
293
- const allViolations = findViolationsInFile(file, workspaceRoot, disableAllowed);
294
-
295
- for (const v of allViolations) {
296
- if (disableAllowed && v.hasDisableComment) continue;
297
- // LINE-BASED: Only include if the violation is on a changed line
298
- if (!changedLines.has(v.line)) continue;
299
-
300
- violations.push({
301
- file,
302
- line: v.line,
303
- column: v.column,
304
- context: v.context,
305
- });
306
- }
307
- }
308
-
309
- return violations;
310
- }
311
-
312
- /**
313
- * MODIFIED_FILES mode: Flag ALL violations in files that were modified.
314
- */
315
- function findViolationsForModifiedFiles(workspaceRoot: string, changedFiles: string[], disableAllowed: boolean): Violation[] {
316
- const violations: Violation[] = [];
317
-
318
- for (const file of changedFiles) {
319
- const allViolations = findViolationsInFile(file, workspaceRoot, disableAllowed);
320
-
321
- for (const v of allViolations) {
322
- if (disableAllowed && v.hasDisableComment) continue;
323
-
324
- violations.push({
325
- file,
326
- line: v.line,
327
- column: v.column,
328
- context: v.context,
329
- });
330
- }
331
- }
332
-
333
- return violations;
334
- }
335
-
336
- interface RangeInfo {
337
- name: string;
338
- startLine: number;
339
- endLine: number;
340
- }
341
-
342
- /**
343
- * Find route object ranges in *.routes.ts files.
344
- * A route object is an ObjectLiteralExpression that contains (directly or in descendants)
345
- * a `resolve` property. Returns the line range of each such top-level route object.
346
- */
347
- function findRouteObjectRanges(filePath: string, workspaceRoot: string): RangeInfo[] {
348
- const fullPath = path.join(workspaceRoot, filePath);
349
- if (!fs.existsSync(fullPath)) return [];
350
-
351
- const content = fs.readFileSync(fullPath, 'utf-8');
352
- const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
353
-
354
- const ranges: RangeInfo[] = [];
355
-
356
- function hasResolveProperty(node: ts.Node): boolean {
357
- if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === 'resolve') {
358
- return true;
359
- }
360
- let found = false;
361
- ts.forEachChild(node, (child) => {
362
- if (hasResolveProperty(child)) {
363
- found = true;
364
- }
365
- });
366
- return found;
367
- }
368
-
369
- function visitTopLevel(node: ts.Node): void {
370
- if (ts.isObjectLiteralExpression(node) && hasResolveProperty(node)) {
371
- const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
372
- const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
373
- ranges.push({
374
- name: `route@${start.line + 1}`,
375
- startLine: start.line + 1,
376
- endLine: end.line + 1,
377
- });
378
- return;
379
- }
380
- ts.forEachChild(node, visitTopLevel);
381
- }
382
-
383
- visitTopLevel(sourceFile);
384
- return ranges;
385
- }
386
-
387
- /**
388
- * Find method/function ranges in *.component.ts files.
389
- * Returns ranges for class methods, function declarations, and arrow functions in variable declarations.
390
- */
391
- function findMethodRanges(filePath: string, workspaceRoot: string): RangeInfo[] {
392
- const fullPath = path.join(workspaceRoot, filePath);
393
- if (!fs.existsSync(fullPath)) return [];
394
-
395
- const content = fs.readFileSync(fullPath, 'utf-8');
396
- const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
397
-
398
- const ranges: RangeInfo[] = [];
399
-
400
- function visit(node: ts.Node): void {
401
- let methodName: string | undefined;
402
- let startLine: number | undefined;
403
- let endLine: number | undefined;
404
-
405
- if (ts.isMethodDeclaration(node) && node.name) {
406
- methodName = node.name.getText(sourceFile);
407
- const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
408
- const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
409
- startLine = start.line + 1;
410
- endLine = end.line + 1;
411
- } else if (ts.isFunctionDeclaration(node) && node.name) {
412
- methodName = node.name.getText(sourceFile);
413
- const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
414
- const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
415
- startLine = start.line + 1;
416
- endLine = end.line + 1;
417
- } else if (ts.isArrowFunction(node)) {
418
- if (ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name)) {
419
- methodName = node.parent.name.getText(sourceFile);
420
- const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
421
- const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
422
- startLine = start.line + 1;
423
- endLine = end.line + 1;
424
- }
425
- }
426
-
427
- if (methodName && startLine !== undefined && endLine !== undefined) {
428
- ranges.push({ name: methodName, startLine, endLine });
429
- }
430
-
431
- ts.forEachChild(node, visit);
432
- }
433
-
434
- visit(sourceFile);
435
- return ranges;
436
- }
437
-
438
- /**
439
- * NEW_AND_MODIFIED_METHODS mode: Flag violations in new/modified method/route scopes.
440
- * - For *.routes.ts: If any line in a route object is changed, flag all inject(XxxApi) violations in that route
441
- * - For *.component.ts: If a method is new/modified, flag all snapshot.data violations in that method
442
- */
443
- // webpieces-disable max-lines-new-methods -- Method-scoped validation with route objects and component methods
444
- function findViolationsForModifiedMethods(
445
- workspaceRoot: string,
446
- changedFiles: string[],
447
- base: string,
448
- head: string | undefined,
449
- disableAllowed: boolean
450
- ): Violation[] {
451
- const violations: Violation[] = [];
452
-
453
- for (const file of changedFiles) {
454
- const diff = getFileDiff(workspaceRoot, file, base, head);
455
- const changedLines = getChangedLineNumbers(diff);
456
- const newMethodNames = findNewMethodSignaturesInDiff(diff);
457
-
458
- if (changedLines.size === 0 && newMethodNames.size === 0) continue;
459
-
460
- if (file.endsWith('.routes.ts')) {
461
- const routeRanges = findRouteObjectRanges(file, workspaceRoot);
462
- const allViolations = findDirectApiInjections(file, workspaceRoot, disableAllowed);
463
-
464
- for (const range of routeRanges) {
465
- let rangeHasChanges = false;
466
- for (let line = range.startLine; line <= range.endLine; line++) {
467
- if (changedLines.has(line)) {
468
- rangeHasChanges = true;
469
- break;
470
- }
471
- }
472
- if (!rangeHasChanges) continue;
473
-
474
- for (const v of allViolations) {
475
- if (disableAllowed && v.hasDisableComment) continue;
476
- if (v.line >= range.startLine && v.line <= range.endLine) {
477
- violations.push({
478
- file,
479
- line: v.line,
480
- column: v.column,
481
- context: v.context,
482
- });
483
- }
484
- }
485
- }
486
- } else if (file.endsWith('.component.ts')) {
487
- const methodRanges = findMethodRanges(file, workspaceRoot);
488
- const allViolations = findSnapshotDataAccess(file, workspaceRoot, disableAllowed);
489
-
490
- for (const range of methodRanges) {
491
- const isNewMethod = newMethodNames.has(range.name);
492
- let rangeHasChanges = false;
493
- if (!isNewMethod) {
494
- for (let line = range.startLine; line <= range.endLine; line++) {
495
- if (changedLines.has(line)) {
496
- rangeHasChanges = true;
497
- break;
498
- }
499
- }
500
- }
501
- if (!isNewMethod && !rangeHasChanges) continue;
502
-
503
- for (const v of allViolations) {
504
- if (disableAllowed && v.hasDisableComment) continue;
505
- if (v.line >= range.startLine && v.line <= range.endLine) {
506
- violations.push({
507
- file,
508
- line: v.line,
509
- column: v.column,
510
- context: v.context,
511
- });
512
- }
513
- }
514
- }
515
- }
516
- }
517
-
518
- return violations;
519
- }
520
-
521
- /**
522
- * Report violations to console.
523
- */
524
- // webpieces-disable max-lines-new-methods -- Console output with examples and escape hatch information
525
- function reportViolations(violations: Violation[], mode: NoDirectApiResolverMode, disableAllowed: boolean): void {
526
- console.error('');
527
- console.error('\u274c Direct API usage in resolvers or snapshot.data in components found!');
528
- console.error('');
529
- console.error('\ud83d\udcda Resolvers should use services, and components should subscribe to service observables:');
530
- console.error('');
531
- console.error(' BAD (in *.routes.ts resolver):');
532
- console.error(' const myApi = inject(MyApi);');
533
- console.error(' resolve: () => inject(MyApi).fetchData()');
534
- console.error('');
535
- console.error(' GOOD (in *.routes.ts resolver):');
536
- console.error(' const myService = inject(MyService);');
537
- console.error(' resolve: () => inject(MyService).loadData()');
538
- console.error('');
539
- console.error(' BAD (in *.component.ts):');
540
- console.error(' const data = this.route.snapshot.data;');
541
- console.error('');
542
- console.error(' GOOD (in *.component.ts):');
543
- console.error(' this.myService.data$.subscribe(data => ...)');
544
- console.error('');
545
-
546
- for (const v of violations) {
547
- console.error(` \u274c ${v.file}:${v.line}:${v.column}`);
548
- console.error(` ${v.context}`);
549
- }
550
- console.error('');
551
-
552
- if (disableAllowed) {
553
- console.error(' Escape hatch (use sparingly):');
554
- console.error(' // webpieces-disable no-direct-api-resolver -- [your reason]');
555
- } else {
556
- console.error(' Escape hatch: DISABLED (disableAllowed: false)');
557
- console.error(' Disable comments are ignored. Fix the pattern directly.');
558
- }
559
- console.error('');
560
- console.error(` Current mode: ${mode}`);
561
- console.error('');
562
- }
563
-
564
- /**
565
- * Resolve mode considering ignoreModifiedUntilEpoch override.
566
- * When active, downgrades to OFF. When expired, logs a warning.
567
- */
568
- function resolveMode(normalMode: NoDirectApiResolverMode, epoch: number | undefined): NoDirectApiResolverMode {
569
- if (epoch === undefined || normalMode === 'OFF') {
570
- return normalMode;
571
- }
572
- const nowSeconds = Date.now() / 1000;
573
- if (nowSeconds < epoch) {
574
- const expiresDate = new Date(epoch * 1000).toISOString().split('T')[0];
575
- console.log(`\n\u23ed\ufe0f Skipping no-direct-api-resolver validation (ignoreModifiedUntilEpoch active, expires: ${expiresDate})`);
576
- console.log('');
577
- return 'OFF';
578
- }
579
- return normalMode;
580
- }
581
-
582
- /**
583
- * Filter changed files to only those under enforcePaths (if configured).
584
- */
585
- function filterByEnforcePaths(changedFiles: string[], enforcePaths: string[] | undefined): string[] {
586
- if (!enforcePaths || enforcePaths.length === 0) {
587
- return changedFiles;
588
- }
589
- return changedFiles.filter((file) =>
590
- enforcePaths.some((prefix) => file.startsWith(prefix))
591
- );
592
- }
593
-
594
- /**
595
- * Filter to only relevant Angular files (*.routes.ts and *.component.ts).
596
- */
597
- function filterRelevantFiles(changedFiles: string[]): string[] {
598
- return changedFiles.filter((file) =>
599
- file.endsWith('.routes.ts') || file.endsWith('.component.ts')
600
- );
601
- }
602
-
603
- export default async function runExecutor(
604
- options: ValidateNoDirectApiResolverOptions,
605
- context: ExecutorContext
606
- ): Promise<ExecutorResult> {
607
- const workspaceRoot = context.root;
608
- const mode: NoDirectApiResolverMode = resolveMode(options.mode ?? 'OFF', options.ignoreModifiedUntilEpoch);
609
- const disableAllowed = options.disableAllowed ?? true;
610
-
611
- if (mode === 'OFF') {
612
- console.log('\n\u23ed\ufe0f Skipping no-direct-api-resolver validation (mode: OFF)');
613
- console.log('');
614
- return { success: true };
615
- }
616
-
617
- console.log('\n\ud83d\udccf Validating No Direct API in Resolver\n');
618
- console.log(` Mode: ${mode}`);
619
-
620
- let base = process.env['NX_BASE'];
621
- const head = process.env['NX_HEAD'];
622
-
623
- if (!base) {
624
- base = detectBase(workspaceRoot) ?? undefined;
625
-
626
- if (!base) {
627
- console.log('\n\u23ed\ufe0f Skipping no-direct-api-resolver validation (could not detect base branch)');
628
- console.log('');
629
- return { success: true };
630
- }
631
- }
632
-
633
- console.log(` Base: ${base}`);
634
- console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);
635
- console.log('');
636
-
637
- const allChangedFiles = getChangedTypeScriptFiles(workspaceRoot, base, head);
638
- const scopedFiles = filterByEnforcePaths(allChangedFiles, options.enforcePaths);
639
- const changedFiles = filterRelevantFiles(scopedFiles);
640
-
641
- if (changedFiles.length === 0) {
642
- console.log('\u2705 No relevant Angular files changed (*.routes.ts, *.component.ts)');
643
- return { success: true };
644
- }
645
-
646
- console.log(`\ud83d\udcc2 Checking ${changedFiles.length} changed file(s)...`);
647
-
648
- let violations: Violation[] = [];
649
-
650
- if (mode === 'MODIFIED_CODE') {
651
- violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);
652
- } else if (mode === 'NEW_AND_MODIFIED_METHODS') {
653
- violations = findViolationsForModifiedMethods(workspaceRoot, changedFiles, base, head, disableAllowed);
654
- } else if (mode === 'MODIFIED_FILES') {
655
- violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);
656
- }
657
-
658
- if (violations.length === 0) {
659
- console.log('\u2705 No direct API resolver patterns found');
660
- return { success: true };
661
- }
662
-
663
- reportViolations(violations, mode, disableAllowed);
664
-
665
- return { success: false };
666
- }
@@ -1,29 +0,0 @@
1
- {
2
- "$schema": "http://json-schema.org/schema",
3
- "title": "Validate No Direct API in Resolver Executor",
4
- "description": "Validates resolvers use services (not APIs) and components subscribe to service observables (not route.snapshot.data). Uses LINE-BASED detection for git diff filtering.",
5
- "type": "object",
6
- "properties": {
7
- "mode": {
8
- "type": "string",
9
- "enum": ["OFF", "MODIFIED_CODE", "NEW_AND_MODIFIED_METHODS", "MODIFIED_FILES"],
10
- "description": "OFF: skip validation. MODIFIED_CODE: only changed lines in diff. NEW_AND_MODIFIED_METHODS: violations in new/modified method/route scopes. MODIFIED_FILES: all in modified files.",
11
- "default": "OFF"
12
- },
13
- "disableAllowed": {
14
- "type": "boolean",
15
- "description": "Whether disable comments work. When false, no escape hatch.",
16
- "default": true
17
- },
18
- "ignoreModifiedUntilEpoch": {
19
- "type": "number",
20
- "description": "Epoch seconds. Until this time, skip validation entirely. When expired, normal mode resumes. Omit when not needed."
21
- },
22
- "enforcePaths": {
23
- "type": "array",
24
- "items": { "type": "string" },
25
- "description": "Array of directory prefixes (relative to workspace root) to scope validation to. When set, only files under these paths are checked. When empty/omitted, all changed files are checked."
26
- }
27
- },
28
- "required": []
29
- }