@webpieces/dev-config 0.2.95 → 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 (181) 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/src/executors/validate-eslint-sync/executor.js.map +1 -0
  7. package/{executors → src/executors}/validate-versions-locked/executor.js +2 -1
  8. package/src/executors/validate-versions-locked/executor.js.map +1 -0
  9. package/src/index.d.ts +1 -1
  10. package/src/index.js +1 -1
  11. package/src/index.js.map +1 -1
  12. package/src/plugin.d.ts +86 -0
  13. package/{plugin.js → src/plugin.js} +31 -15
  14. package/src/plugin.js.map +1 -0
  15. package/src/toError.d.ts +5 -0
  16. package/src/toError.js +37 -0
  17. package/src/toError.js.map +1 -0
  18. package/templates/eslint.webpieces.config.mjs +1 -1
  19. package/architecture/executors/diff-utils.d.ts +0 -24
  20. package/architecture/executors/diff-utils.js +0 -119
  21. package/architecture/executors/diff-utils.js.map +0 -1
  22. package/architecture/executors/diff-utils.ts +0 -127
  23. package/architecture/executors/generate/executor.d.ts +0 -16
  24. package/architecture/executors/generate/executor.js +0 -44
  25. package/architecture/executors/generate/executor.js.map +0 -1
  26. package/architecture/executors/generate/executor.ts +0 -59
  27. package/architecture/executors/generate/schema.json +0 -14
  28. package/architecture/executors/validate-architecture-unchanged/executor.d.ts +0 -17
  29. package/architecture/executors/validate-architecture-unchanged/executor.js +0 -229
  30. package/architecture/executors/validate-architecture-unchanged/executor.js.map +0 -1
  31. package/architecture/executors/validate-architecture-unchanged/executor.ts +0 -251
  32. package/architecture/executors/validate-architecture-unchanged/schema.json +0 -14
  33. package/architecture/executors/validate-code/executor.d.ts +0 -78
  34. package/architecture/executors/validate-code/executor.js +0 -243
  35. package/architecture/executors/validate-code/executor.js.map +0 -1
  36. package/architecture/executors/validate-code/executor.ts +0 -406
  37. package/architecture/executors/validate-code/schema.json +0 -227
  38. package/architecture/executors/validate-dtos/executor.d.ts +0 -42
  39. package/architecture/executors/validate-dtos/executor.js +0 -561
  40. package/architecture/executors/validate-dtos/executor.js.map +0 -1
  41. package/architecture/executors/validate-dtos/executor.ts +0 -689
  42. package/architecture/executors/validate-dtos/schema.json +0 -33
  43. package/architecture/executors/validate-modified-files/executor.d.ts +0 -25
  44. package/architecture/executors/validate-modified-files/executor.js +0 -501
  45. package/architecture/executors/validate-modified-files/executor.js.map +0 -1
  46. package/architecture/executors/validate-modified-files/executor.ts +0 -571
  47. package/architecture/executors/validate-modified-files/schema.json +0 -25
  48. package/architecture/executors/validate-modified-methods/executor.d.ts +0 -31
  49. package/architecture/executors/validate-modified-methods/executor.js +0 -694
  50. package/architecture/executors/validate-modified-methods/executor.js.map +0 -1
  51. package/architecture/executors/validate-modified-methods/executor.ts +0 -797
  52. package/architecture/executors/validate-modified-methods/schema.json +0 -25
  53. package/architecture/executors/validate-new-methods/executor.d.ts +0 -28
  54. package/architecture/executors/validate-new-methods/executor.js +0 -513
  55. package/architecture/executors/validate-new-methods/executor.js.map +0 -1
  56. package/architecture/executors/validate-new-methods/executor.ts +0 -584
  57. package/architecture/executors/validate-new-methods/schema.json +0 -25
  58. package/architecture/executors/validate-no-any-unknown/executor.d.ts +0 -42
  59. package/architecture/executors/validate-no-any-unknown/executor.js +0 -462
  60. package/architecture/executors/validate-no-any-unknown/executor.js.map +0 -1
  61. package/architecture/executors/validate-no-any-unknown/executor.ts +0 -540
  62. package/architecture/executors/validate-no-any-unknown/schema.json +0 -24
  63. package/architecture/executors/validate-no-architecture-cycles/executor.d.ts +0 -16
  64. package/architecture/executors/validate-no-architecture-cycles/executor.js +0 -48
  65. package/architecture/executors/validate-no-architecture-cycles/executor.js.map +0 -1
  66. package/architecture/executors/validate-no-architecture-cycles/executor.ts +0 -60
  67. package/architecture/executors/validate-no-architecture-cycles/schema.json +0 -8
  68. package/architecture/executors/validate-no-destructure/executor.d.ts +0 -52
  69. package/architecture/executors/validate-no-destructure/executor.js +0 -491
  70. package/architecture/executors/validate-no-destructure/executor.js.map +0 -1
  71. package/architecture/executors/validate-no-destructure/executor.ts +0 -578
  72. package/architecture/executors/validate-no-destructure/schema.json +0 -24
  73. package/architecture/executors/validate-no-direct-api-resolver/executor.d.ts +0 -47
  74. package/architecture/executors/validate-no-direct-api-resolver/executor.js +0 -566
  75. package/architecture/executors/validate-no-direct-api-resolver/executor.js.map +0 -1
  76. package/architecture/executors/validate-no-direct-api-resolver/executor.ts +0 -666
  77. package/architecture/executors/validate-no-direct-api-resolver/schema.json +0 -29
  78. package/architecture/executors/validate-no-inline-types/executor.d.ts +0 -91
  79. package/architecture/executors/validate-no-inline-types/executor.js +0 -669
  80. package/architecture/executors/validate-no-inline-types/executor.js.map +0 -1
  81. package/architecture/executors/validate-no-inline-types/executor.ts +0 -775
  82. package/architecture/executors/validate-no-inline-types/schema.json +0 -24
  83. package/architecture/executors/validate-no-skiplevel-deps/executor.d.ts +0 -19
  84. package/architecture/executors/validate-no-skiplevel-deps/executor.js +0 -227
  85. package/architecture/executors/validate-no-skiplevel-deps/executor.js.map +0 -1
  86. package/architecture/executors/validate-no-skiplevel-deps/executor.ts +0 -267
  87. package/architecture/executors/validate-no-skiplevel-deps/schema.json +0 -8
  88. package/architecture/executors/validate-packagejson/executor.d.ts +0 -16
  89. package/architecture/executors/validate-packagejson/executor.js +0 -57
  90. package/architecture/executors/validate-packagejson/executor.js.map +0 -1
  91. package/architecture/executors/validate-packagejson/executor.ts +0 -74
  92. package/architecture/executors/validate-packagejson/schema.json +0 -8
  93. package/architecture/executors/validate-prisma-converters/executor.d.ts +0 -60
  94. package/architecture/executors/validate-prisma-converters/executor.js +0 -634
  95. package/architecture/executors/validate-prisma-converters/executor.js.map +0 -1
  96. package/architecture/executors/validate-prisma-converters/executor.ts +0 -822
  97. package/architecture/executors/validate-prisma-converters/schema.json +0 -38
  98. package/architecture/executors/validate-return-types/executor.d.ts +0 -29
  99. package/architecture/executors/validate-return-types/executor.js +0 -439
  100. package/architecture/executors/validate-return-types/executor.js.map +0 -1
  101. package/architecture/executors/validate-return-types/executor.ts +0 -524
  102. package/architecture/executors/validate-return-types/schema.json +0 -24
  103. package/architecture/executors/visualize/executor.d.ts +0 -17
  104. package/architecture/executors/visualize/executor.js +0 -49
  105. package/architecture/executors/visualize/executor.js.map +0 -1
  106. package/architecture/executors/visualize/executor.ts +0 -63
  107. package/architecture/executors/visualize/schema.json +0 -14
  108. package/architecture/index.d.ts +0 -19
  109. package/architecture/index.js +0 -23
  110. package/architecture/index.js.map +0 -1
  111. package/architecture/index.ts +0 -20
  112. package/architecture/lib/graph-comparator.d.ts +0 -39
  113. package/architecture/lib/graph-comparator.js +0 -100
  114. package/architecture/lib/graph-comparator.js.map +0 -1
  115. package/architecture/lib/graph-comparator.ts +0 -141
  116. package/architecture/lib/graph-generator.d.ts +0 -19
  117. package/architecture/lib/graph-generator.js +0 -84
  118. package/architecture/lib/graph-generator.js.map +0 -1
  119. package/architecture/lib/graph-generator.ts +0 -97
  120. package/architecture/lib/graph-loader.d.ts +0 -31
  121. package/architecture/lib/graph-loader.js +0 -98
  122. package/architecture/lib/graph-loader.js.map +0 -1
  123. package/architecture/lib/graph-loader.ts +0 -116
  124. package/architecture/lib/graph-sorter.d.ts +0 -37
  125. package/architecture/lib/graph-sorter.js +0 -110
  126. package/architecture/lib/graph-sorter.js.map +0 -1
  127. package/architecture/lib/graph-sorter.ts +0 -137
  128. package/architecture/lib/graph-visualizer.d.ts +0 -29
  129. package/architecture/lib/graph-visualizer.js +0 -217
  130. package/architecture/lib/graph-visualizer.js.map +0 -1
  131. package/architecture/lib/graph-visualizer.ts +0 -231
  132. package/architecture/lib/package-validator.d.ts +0 -38
  133. package/architecture/lib/package-validator.js +0 -126
  134. package/architecture/lib/package-validator.js.map +0 -1
  135. package/architecture/lib/package-validator.ts +0 -170
  136. package/eslint-plugin/__tests__/catch-error-pattern.test.ts +0 -374
  137. package/eslint-plugin/__tests__/max-file-lines.test.ts +0 -207
  138. package/eslint-plugin/__tests__/max-method-lines.test.ts +0 -258
  139. package/eslint-plugin/__tests__/no-unmanaged-exceptions.test.ts +0 -359
  140. package/eslint-plugin/index.d.ts +0 -23
  141. package/eslint-plugin/index.js +0 -30
  142. package/eslint-plugin/index.js.map +0 -1
  143. package/eslint-plugin/index.ts +0 -29
  144. package/eslint-plugin/rules/catch-error-pattern.d.ts +0 -11
  145. package/eslint-plugin/rules/catch-error-pattern.js +0 -143
  146. package/eslint-plugin/rules/catch-error-pattern.js.map +0 -1
  147. package/eslint-plugin/rules/catch-error-pattern.ts +0 -246
  148. package/eslint-plugin/rules/enforce-architecture.d.ts +0 -15
  149. package/eslint-plugin/rules/enforce-architecture.js +0 -476
  150. package/eslint-plugin/rules/enforce-architecture.js.map +0 -1
  151. package/eslint-plugin/rules/enforce-architecture.ts +0 -543
  152. package/eslint-plugin/rules/max-file-lines.d.ts +0 -12
  153. package/eslint-plugin/rules/max-file-lines.js +0 -257
  154. package/eslint-plugin/rules/max-file-lines.js.map +0 -1
  155. package/eslint-plugin/rules/max-file-lines.ts +0 -272
  156. package/eslint-plugin/rules/max-method-lines.d.ts +0 -12
  157. package/eslint-plugin/rules/max-method-lines.js +0 -240
  158. package/eslint-plugin/rules/max-method-lines.js.map +0 -1
  159. package/eslint-plugin/rules/max-method-lines.ts +0 -287
  160. package/eslint-plugin/rules/no-unmanaged-exceptions.d.ts +0 -22
  161. package/eslint-plugin/rules/no-unmanaged-exceptions.js +0 -160
  162. package/eslint-plugin/rules/no-unmanaged-exceptions.js.map +0 -1
  163. package/eslint-plugin/rules/no-unmanaged-exceptions.ts +0 -179
  164. package/executors/help/executor.js.map +0 -1
  165. package/executors/help/executor.ts +0 -61
  166. package/executors/validate-eslint-sync/executor.js.map +0 -1
  167. package/executors/validate-eslint-sync/executor.ts +0 -87
  168. package/executors/validate-versions-locked/executor.js.map +0 -1
  169. package/executors/validate-versions-locked/executor.ts +0 -368
  170. package/plugin/README.md +0 -243
  171. package/plugin/index.d.ts +0 -4
  172. package/plugin/index.js +0 -8
  173. package/plugin/index.js.map +0 -1
  174. package/plugin/index.ts +0 -4
  175. /package/{executors → src/executors}/help/executor.js +0 -0
  176. /package/{executors → src/executors}/help/schema.json +0 -0
  177. /package/{executors → src/executors}/validate-eslint-sync/executor.d.ts +0 -0
  178. /package/{executors → src/executors}/validate-eslint-sync/executor.js +0 -0
  179. /package/{executors → src/executors}/validate-eslint-sync/schema.json +0 -0
  180. /package/{executors → src/executors}/validate-versions-locked/executor.d.ts +0 -0
  181. /package/{executors → src/executors}/validate-versions-locked/schema.json +0 -0
@@ -1,694 +0,0 @@
1
- "use strict";
2
- /**
3
- * Validate Modified Methods Executor
4
- *
5
- * Validates that modified methods don't exceed a maximum line count (default 80).
6
- * This encourages gradual cleanup of legacy long methods - when you touch a method,
7
- * you must bring it under the limit.
8
- *
9
- * Combined with validate-new-methods, this creates a gradual
10
- * transition to cleaner code:
11
- * - New methods: must be under limit
12
- * - Modified methods: must be under limit (cleanup when touched)
13
- * - Untouched methods: no limit (legacy allowed)
14
- *
15
- * Usage:
16
- * nx affected --target=validate-modified-methods --base=origin/main
17
- *
18
- * Escape hatch: Add webpieces-disable max-lines-modified comment with date and justification
19
- * Format: // webpieces-disable max-lines-modified 2025/01/15 -- [reason]
20
- * The disable expires after 1 month from the date specified.
21
- */
22
- Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.default = runExecutor;
24
- const tslib_1 = require("tslib");
25
- const child_process_1 = require("child_process");
26
- const fs = tslib_1.__importStar(require("fs"));
27
- const path = tslib_1.__importStar(require("path"));
28
- const ts = tslib_1.__importStar(require("typescript"));
29
- const TMP_DIR = 'tmp/webpieces';
30
- const TMP_MD_FILE = 'webpieces.methodsize.md';
31
- const METHODSIZE_DOC_CONTENT = `# Instructions: Method Too Long
32
-
33
- ## Requirement
34
-
35
- **~99% of the time**, you can stay under the \`limit\` from nx.json
36
- by extracting logical units into well-named methods.
37
- Nearly all software can be written with methods under this size.
38
- Take the extra time to refactor - it's worth it for long-term maintainability.
39
-
40
- ## The "Table of Contents" Principle
41
-
42
- Good code reads like a book's table of contents:
43
- - Chapter titles (method names) tell you WHAT happens
44
- - Reading chapter titles gives you the full story
45
- - You can dive into chapters (implementations) for details
46
-
47
- ## Why Limit Method Sizes?
48
-
49
- Methods under reasonable limits are:
50
- - Easy to review in a single screen
51
- - Simple to understand without scrolling
52
- - Quick for AI to analyze and suggest improvements
53
- - More testable in isolation
54
- - Self-documenting through well-named extracted methods
55
-
56
- ## Gradual Cleanup Strategy
57
-
58
- This codebase uses a gradual cleanup approach:
59
- - **New methods**: Must be under \`limit\` from nx.json
60
- - **Modified methods**: Must be under \`limit\` from nx.json
61
- - **Untouched methods**: No limit (legacy code is allowed until touched)
62
-
63
- ## How to Refactor
64
-
65
- Instead of:
66
- \`\`\`typescript
67
- async processOrder(order: Order): Promise<Result> {
68
- // 100 lines of validation, transformation, saving, notifications...
69
- }
70
- \`\`\`
71
-
72
- Write:
73
- \`\`\`typescript
74
- async processOrder(order: Order): Promise<Result> {
75
- const validated = this.validateOrder(order);
76
- const transformed = this.applyBusinessRules(validated);
77
- const saved = await this.saveToDatabase(transformed);
78
- await this.notifyStakeholders(saved);
79
- return this.buildResult(saved);
80
- }
81
- \`\`\`
82
-
83
- Now the main method is a "table of contents" - each line tells part of the story!
84
-
85
- ## Patterns for Extraction
86
-
87
- ### Pattern 1: Extract Loop Bodies
88
- \`\`\`typescript
89
- // BEFORE
90
- for (const item of items) {
91
- // 20 lines of processing
92
- }
93
-
94
- // AFTER
95
- for (const item of items) {
96
- this.processItem(item);
97
- }
98
- \`\`\`
99
-
100
- ### Pattern 2: Extract Conditional Blocks
101
- \`\`\`typescript
102
- // BEFORE
103
- if (isAdmin(user)) {
104
- // 15 lines of admin logic
105
- }
106
-
107
- // AFTER
108
- if (isAdmin(user)) {
109
- this.handleAdminUser(user);
110
- }
111
- \`\`\`
112
-
113
- ### Pattern 3: Extract Data Transformations
114
- \`\`\`typescript
115
- // BEFORE
116
- const result = {
117
- // 10+ lines of object construction
118
- };
119
-
120
- // AFTER
121
- const result = this.buildResultObject(data);
122
- \`\`\`
123
-
124
- ## If Refactoring Is Not Feasible
125
-
126
- Sometimes methods genuinely need to be longer (complex algorithms, state machines, etc.).
127
-
128
- **Escape hatch**: Add a webpieces-disable comment with DATE and justification:
129
-
130
- \`\`\`typescript
131
- // webpieces-disable max-lines-modified 2025/01/15 -- Complex state machine, splitting reduces clarity
132
- async complexStateMachine(): Promise<void> {
133
- // ... longer method with justification
134
- }
135
- \`\`\`
136
-
137
- **IMPORTANT**: The date format is yyyy/mm/dd. The disable will EXPIRE after 1 month from this date.
138
- After expiration, you must either fix the method or update the date to get another month.
139
- This ensures that disable comments are reviewed periodically.
140
-
141
- ## AI Agent Action Steps
142
-
143
- 1. **READ** the method to understand its logical sections
144
- 2. **IDENTIFY** logical units that can be extracted
145
- 3. **EXTRACT** into well-named private methods
146
- 4. **VERIFY** the main method now reads like a table of contents
147
- 5. **IF NOT FEASIBLE**: Add webpieces-disable max-lines-modified comment with clear justification
148
-
149
- ## Remember
150
-
151
- - Every method you write today will be read many times tomorrow
152
- - The best code explains itself through structure
153
- - When in doubt, extract and name it
154
- `;
155
- /**
156
- * Write the instructions documentation to tmp directory
157
- */
158
- function writeTmpInstructions(workspaceRoot) {
159
- const tmpDir = path.join(workspaceRoot, TMP_DIR);
160
- const mdPath = path.join(tmpDir, TMP_MD_FILE);
161
- fs.mkdirSync(tmpDir, { recursive: true });
162
- fs.writeFileSync(mdPath, METHODSIZE_DOC_CONTENT);
163
- return mdPath;
164
- }
165
- /**
166
- * Get changed TypeScript files between base and head (or working tree if head not specified).
167
- * Uses `git diff base [head]` to match what `nx affected` does.
168
- * When head is NOT specified, also includes untracked files (matching nx affected behavior).
169
- */
170
- function getChangedTypeScriptFiles(workspaceRoot, base, head) {
171
- try {
172
- // If head is specified, diff base to head; otherwise diff base to working tree
173
- const diffTarget = head ? `${base} ${head}` : base;
174
- const output = (0, child_process_1.execSync)(`git diff --name-only ${diffTarget} -- '*.ts' '*.tsx'`, {
175
- cwd: workspaceRoot,
176
- encoding: 'utf-8',
177
- });
178
- const changedFiles = output
179
- .trim()
180
- .split('\n')
181
- .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
182
- // When comparing to working tree (no head specified), also include untracked files
183
- // This matches what nx affected does: "All modified files not yet committed or tracked will also be added"
184
- if (!head) {
185
- try {
186
- const untrackedOutput = (0, child_process_1.execSync)(`git ls-files --others --exclude-standard '*.ts' '*.tsx'`, {
187
- cwd: workspaceRoot,
188
- encoding: 'utf-8',
189
- });
190
- const untrackedFiles = untrackedOutput
191
- .trim()
192
- .split('\n')
193
- .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
194
- // Merge and dedupe
195
- const allFiles = new Set([...changedFiles, ...untrackedFiles]);
196
- return Array.from(allFiles);
197
- }
198
- catch {
199
- // If ls-files fails, just return the changed files
200
- return changedFiles;
201
- }
202
- }
203
- return changedFiles;
204
- }
205
- catch {
206
- return [];
207
- }
208
- }
209
- /**
210
- * Get the diff content for a specific file between base and head (or working tree if head not specified).
211
- * Uses `git diff base [head]` to match what `nx affected` does.
212
- * For untracked files, returns the entire file content as additions.
213
- */
214
- function getFileDiff(workspaceRoot, file, base, head) {
215
- try {
216
- // If head is specified, diff base to head; otherwise diff base to working tree
217
- const diffTarget = head ? `${base} ${head}` : base;
218
- const diff = (0, child_process_1.execSync)(`git diff ${diffTarget} -- "${file}"`, {
219
- cwd: workspaceRoot,
220
- encoding: 'utf-8',
221
- });
222
- // If diff is empty and we're comparing to working tree, check if it's an untracked file
223
- if (!diff && !head) {
224
- const fullPath = path.join(workspaceRoot, file);
225
- if (fs.existsSync(fullPath)) {
226
- // Check if file is untracked
227
- const isUntracked = (0, child_process_1.execSync)(`git ls-files --others --exclude-standard "${file}"`, {
228
- cwd: workspaceRoot,
229
- encoding: 'utf-8',
230
- }).trim();
231
- if (isUntracked) {
232
- // For untracked files, treat entire content as additions
233
- const content = fs.readFileSync(fullPath, 'utf-8');
234
- const lines = content.split('\n');
235
- // Create a pseudo-diff where all lines are additions
236
- return lines.map((line) => `+${line}`).join('\n');
237
- }
238
- }
239
- }
240
- return diff;
241
- }
242
- catch {
243
- return '';
244
- }
245
- }
246
- /**
247
- * Parse diff to find NEW method signatures.
248
- * Must handle: export function, async function, const/let arrow functions, class methods
249
- */
250
- // webpieces-disable max-lines-new-methods -- Regex patterns require inline documentation
251
- function findNewMethodSignaturesInDiff(diffContent) {
252
- const newMethods = new Set();
253
- const lines = diffContent.split('\n');
254
- // Patterns to match method definitions (same as validate-new-methods)
255
- const patterns = [
256
- // [export] [async] function methodName( - most explicit, check first
257
- /^\+\s*(?:export\s+)?(?:async\s+)?function\s+(\w+)\s*\(/,
258
- // [export] const/let methodName = [async] (
259
- /^\+\s*(?:export\s+)?(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/,
260
- // [export] const/let methodName = [async] function
261
- /^\+\s*(?:export\s+)?(?:const|let)\s+(\w+)\s*=\s*(?:async\s+)?function/,
262
- // class method: [public/private/protected] [static] [async] methodName( - but NOT constructor, if, for, while, etc.
263
- /^\+\s*(?:(?:public|private|protected)\s+)?(?:static\s+)?(?:async\s+)?(\w+)\s*\(/,
264
- ];
265
- for (const line of lines) {
266
- if (line.startsWith('+') && !line.startsWith('+++')) {
267
- for (const pattern of patterns) {
268
- const match = line.match(pattern);
269
- if (match) {
270
- // Extract method name - now always in capture group 1
271
- const methodName = match[1];
272
- if (methodName && !['if', 'for', 'while', 'switch', 'catch', 'constructor'].includes(methodName)) {
273
- newMethods.add(methodName);
274
- }
275
- break;
276
- }
277
- }
278
- }
279
- }
280
- return newMethods;
281
- }
282
- /**
283
- * Parse diff to find line numbers that have changes in the new file
284
- */
285
- function getChangedLineNumbers(diffContent) {
286
- const changedLines = new Set();
287
- const lines = diffContent.split('\n');
288
- let currentNewLine = 0;
289
- for (const line of lines) {
290
- // Parse hunk header: @@ -oldStart,oldCount +newStart,newCount @@
291
- const hunkMatch = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
292
- if (hunkMatch) {
293
- currentNewLine = parseInt(hunkMatch[1], 10);
294
- continue;
295
- }
296
- if (currentNewLine === 0)
297
- continue;
298
- if (line.startsWith('+') && !line.startsWith('+++')) {
299
- // Added line
300
- changedLines.add(currentNewLine);
301
- currentNewLine++;
302
- }
303
- else if (line.startsWith('-') && !line.startsWith('---')) {
304
- // Removed line - doesn't increment new line counter
305
- }
306
- else if (!line.startsWith('\\')) {
307
- // Context line (unchanged)
308
- currentNewLine++;
309
- }
310
- }
311
- return changedLines;
312
- }
313
- /**
314
- * Parse a date string in yyyy/mm/dd format and return a Date object.
315
- * Returns null if the format is invalid.
316
- */
317
- function parseDisableDate(dateStr) {
318
- // Match yyyy/mm/dd format
319
- const match = dateStr.match(/^(\d{4})\/(\d{2})\/(\d{2})$/);
320
- if (!match)
321
- return null;
322
- const year = parseInt(match[1], 10);
323
- const month = parseInt(match[2], 10) - 1; // JS months are 0-indexed
324
- const day = parseInt(match[3], 10);
325
- const date = new Date(year, month, day);
326
- // Validate the date is valid (e.g., not Feb 30)
327
- if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) {
328
- return null;
329
- }
330
- return date;
331
- }
332
- /**
333
- * Check if a date is within the last month (not expired).
334
- */
335
- function isDateWithinMonth(date) {
336
- const now = new Date();
337
- const oneMonthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
338
- return date >= oneMonthAgo;
339
- }
340
- /**
341
- * Get today's date in yyyy/mm/dd format for error messages
342
- */
343
- function getTodayDateString() {
344
- const now = new Date();
345
- const year = now.getFullYear();
346
- const month = String(now.getMonth() + 1).padStart(2, '0');
347
- const day = String(now.getDate()).padStart(2, '0');
348
- return `${year}/${month}/${day}`;
349
- }
350
- /**
351
- * Check what kind of webpieces-disable comment is present for a method.
352
- * Returns: DisableInfo with type, expiration status, and date
353
- * - 'full': max-lines-modified (ultimate escape, skips both validators)
354
- * - 'new-only': max-lines-new-methods (escaped 30-line check, still needs 80-line check)
355
- * - 'none': no escape hatch
356
- */
357
- // webpieces-disable max-lines-new-methods -- Complex validation logic with multiple escape hatch types
358
- function getDisableInfo(lines, lineNumber) {
359
- const startCheck = Math.max(0, lineNumber - 5);
360
- for (let i = lineNumber - 2; i >= startCheck; i--) {
361
- const line = lines[i]?.trim() ?? '';
362
- if (line.startsWith('function ') || line.startsWith('class ') || line.endsWith('}')) {
363
- break;
364
- }
365
- if (line.includes('webpieces-disable')) {
366
- if (line.includes('max-lines-modified')) {
367
- // Check for date in format: max-lines-modified yyyy/mm/dd
368
- const dateMatch = line.match(/max-lines-modified\s+(\d{4}\/\d{2}\/\d{2}|XXXX\/XX\/XX)/);
369
- if (!dateMatch) {
370
- // No date found - treat as expired (invalid)
371
- return { type: 'full', isExpired: true, date: undefined };
372
- }
373
- const dateStr = dateMatch[1];
374
- // Secret permanent disable
375
- if (dateStr === 'XXXX/XX/XX') {
376
- return { type: 'full', isExpired: false, date: dateStr };
377
- }
378
- const date = parseDisableDate(dateStr);
379
- if (!date) {
380
- // Invalid date format - treat as expired
381
- return { type: 'full', isExpired: true, date: dateStr };
382
- }
383
- if (!isDateWithinMonth(date)) {
384
- // Date is expired (older than 1 month)
385
- return { type: 'full', isExpired: true, date: dateStr };
386
- }
387
- // Valid and not expired
388
- return { type: 'full', isExpired: false, date: dateStr };
389
- }
390
- if (line.includes('max-lines-new-methods')) {
391
- // Check for date in format: max-lines-new-methods yyyy/mm/dd
392
- const dateMatch = line.match(/max-lines-new-methods\s+(\d{4}\/\d{2}\/\d{2}|XXXX\/XX\/XX)/);
393
- if (!dateMatch) {
394
- // No date found - treat as expired (invalid)
395
- return { type: 'new-only', isExpired: true, date: undefined };
396
- }
397
- const dateStr = dateMatch[1];
398
- // Secret permanent disable
399
- if (dateStr === 'XXXX/XX/XX') {
400
- return { type: 'new-only', isExpired: false, date: dateStr };
401
- }
402
- const date = parseDisableDate(dateStr);
403
- if (!date) {
404
- // Invalid date format - treat as expired
405
- return { type: 'new-only', isExpired: true, date: dateStr };
406
- }
407
- if (!isDateWithinMonth(date)) {
408
- // Date is expired (older than 1 month)
409
- return { type: 'new-only', isExpired: true, date: dateStr };
410
- }
411
- // Valid and not expired
412
- return { type: 'new-only', isExpired: false, date: dateStr };
413
- }
414
- }
415
- }
416
- return { type: 'none', isExpired: false };
417
- }
418
- /**
419
- * Parse a TypeScript file and find methods with their line counts
420
- */
421
- // webpieces-disable max-lines-new-methods -- AST traversal requires inline visitor function
422
- function findMethodsInFile(filePath, workspaceRoot) {
423
- const fullPath = path.join(workspaceRoot, filePath);
424
- if (!fs.existsSync(fullPath))
425
- return [];
426
- const content = fs.readFileSync(fullPath, 'utf-8');
427
- const fileLines = content.split('\n');
428
- const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
429
- const methods = [];
430
- // webpieces-disable max-lines-new-methods -- AST visitor pattern requires handling multiple node types
431
- function visit(node) {
432
- let methodName;
433
- let startLine;
434
- let endLine;
435
- if (ts.isMethodDeclaration(node) && node.name) {
436
- methodName = node.name.getText(sourceFile);
437
- const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
438
- const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
439
- startLine = start.line + 1;
440
- endLine = end.line + 1;
441
- }
442
- else if (ts.isFunctionDeclaration(node) && node.name) {
443
- methodName = node.name.getText(sourceFile);
444
- const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
445
- const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
446
- startLine = start.line + 1;
447
- endLine = end.line + 1;
448
- }
449
- else if (ts.isArrowFunction(node)) {
450
- if (ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name)) {
451
- methodName = node.parent.name.getText(sourceFile);
452
- const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
453
- const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
454
- startLine = start.line + 1;
455
- endLine = end.line + 1;
456
- }
457
- }
458
- if (methodName && startLine !== undefined && endLine !== undefined) {
459
- methods.push({
460
- name: methodName,
461
- line: startLine,
462
- endLine: endLine,
463
- lines: endLine - startLine + 1,
464
- disableInfo: getDisableInfo(fileLines, startLine),
465
- });
466
- }
467
- ts.forEachChild(node, visit);
468
- }
469
- visit(sourceFile);
470
- return methods;
471
- }
472
- /**
473
- * Check if a method has any changes within its line range
474
- */
475
- function methodHasChanges(method, changedLineNumbers) {
476
- for (let line = method.line; line <= method.endLine; line++) {
477
- if (changedLineNumbers.has(line))
478
- return true;
479
- }
480
- return false;
481
- }
482
- /**
483
- * Check a NEW method and return violation if applicable
484
- */
485
- function checkNewMethodViolation(file, method, disableAllowed) {
486
- const { type: disableType, isExpired, date: disableDate } = method.disableInfo;
487
- if (!disableAllowed) {
488
- // When disableAllowed is false, skip NEW methods without escape (let validate-new-methods handle)
489
- if (disableType === 'none')
490
- return null;
491
- return { file, methodName: method.name, line: method.line, lines: method.lines };
492
- }
493
- if (disableType === 'full' && isExpired) {
494
- return { file, methodName: method.name, line: method.line, lines: method.lines, expiredDisable: true, expiredDate: disableDate };
495
- }
496
- if (disableType !== 'new-only')
497
- return null;
498
- if (isExpired) {
499
- return { file, methodName: method.name, line: method.line, lines: method.lines, expiredDisable: true, expiredDate: disableDate };
500
- }
501
- return { file, methodName: method.name, line: method.line, lines: method.lines };
502
- }
503
- /**
504
- * Check a MODIFIED method and return violation if applicable
505
- */
506
- function checkModifiedMethodViolation(file, method, disableAllowed) {
507
- const { type: disableType, isExpired, date: disableDate } = method.disableInfo;
508
- if (!disableAllowed) {
509
- return { file, methodName: method.name, line: method.line, lines: method.lines };
510
- }
511
- if (disableType === 'full' && !isExpired) {
512
- // Valid escape, no violation
513
- return null;
514
- }
515
- if (disableType === 'full' && isExpired) {
516
- return { file, methodName: method.name, line: method.line, lines: method.lines, expiredDisable: true, expiredDate: disableDate };
517
- }
518
- return { file, methodName: method.name, line: method.line, lines: method.lines };
519
- }
520
- /**
521
- * Find methods that exceed the limit.
522
- * Checks NEW methods with escape hatches and MODIFIED methods.
523
- */
524
- function findViolations(workspaceRoot, changedFiles, base, limit, disableAllowed, head) {
525
- const violations = [];
526
- for (const file of changedFiles) {
527
- const diff = getFileDiff(workspaceRoot, file, base, head);
528
- if (!diff)
529
- continue;
530
- const newMethodNames = findNewMethodSignaturesInDiff(diff);
531
- const changedLineNumbers = getChangedLineNumbers(diff);
532
- if (changedLineNumbers.size === 0)
533
- continue;
534
- const methods = findMethodsInFile(file, workspaceRoot);
535
- for (const method of methods) {
536
- const { type: disableType, isExpired } = method.disableInfo;
537
- // Skip methods with valid, non-expired full escape - unless disableAllowed is false
538
- if (disableAllowed && disableType === 'full' && !isExpired)
539
- continue;
540
- if (method.lines <= limit)
541
- continue;
542
- const isNewMethod = newMethodNames.has(method.name);
543
- if (isNewMethod) {
544
- const violation = checkNewMethodViolation(file, method, disableAllowed);
545
- if (violation)
546
- violations.push(violation);
547
- }
548
- else if (methodHasChanges(method, changedLineNumbers)) {
549
- const violation = checkModifiedMethodViolation(file, method, disableAllowed);
550
- if (violation)
551
- violations.push(violation);
552
- }
553
- }
554
- }
555
- return violations;
556
- }
557
- /**
558
- * Auto-detect the base branch by finding the merge-base with origin/main.
559
- */
560
- function detectBase(workspaceRoot) {
561
- try {
562
- const mergeBase = (0, child_process_1.execSync)('git merge-base HEAD origin/main', {
563
- cwd: workspaceRoot,
564
- encoding: 'utf-8',
565
- stdio: ['pipe', 'pipe', 'pipe'],
566
- }).trim();
567
- if (mergeBase) {
568
- return mergeBase;
569
- }
570
- }
571
- catch {
572
- try {
573
- const mergeBase = (0, child_process_1.execSync)('git merge-base HEAD main', {
574
- cwd: workspaceRoot,
575
- encoding: 'utf-8',
576
- stdio: ['pipe', 'pipe', 'pipe'],
577
- }).trim();
578
- if (mergeBase) {
579
- return mergeBase;
580
- }
581
- }
582
- catch {
583
- // Ignore
584
- }
585
- }
586
- return null;
587
- }
588
- /**
589
- * Report violations to console
590
- */
591
- // webpieces-disable max-lines-new-methods -- Error output formatting with multiple message sections
592
- function reportViolations(violations, limit, disableAllowed) {
593
- console.error('');
594
- console.error('\u274c Modified methods exceed ' + limit + ' lines!');
595
- console.error('');
596
- console.error('\ud83d\udcda When you modify a method, you must bring it under ' + limit + ' lines.');
597
- console.error(' This rule encourages GRADUAL cleanup so even though you did not cause it,');
598
- console.error(' you touched it, so you should fix now as part of your PR');
599
- console.error(' (this is for vibe coding and AI to fix as it touches things).');
600
- console.error(' You can refactor to stay under the limit 50% of the time. If not feasible, use the escape hatch.');
601
- console.error('');
602
- console.error('\u26a0\ufe0f *** READ tmp/webpieces/webpieces.methodsize.md for detailed guidance on how to fix this easily *** \u26a0\ufe0f');
603
- console.error('');
604
- for (const v of violations) {
605
- if (v.expiredDisable) {
606
- console.error(` \u274c ${v.file}:${v.line}`);
607
- console.error(` Method: ${v.methodName} (${v.lines} lines, max: ${limit})`);
608
- console.error(` \u23f0 EXPIRED DISABLE: Your disable comment dated ${v.expiredDate ?? 'unknown'} has expired (>1 month old).`);
609
- console.error(` You must either FIX the method or UPDATE the date to get another month.`);
610
- }
611
- else {
612
- console.error(` \u274c ${v.file}:${v.line}`);
613
- console.error(` Method: ${v.methodName} (${v.lines} lines, max: ${limit})`);
614
- }
615
- }
616
- console.error('');
617
- // Only show escape hatch instructions when disableAllowed is true
618
- if (disableAllowed) {
619
- console.error(' You can disable this error, but you will be forced to fix again in 1 month');
620
- console.error(' since 99% of methods can be less than ' + limit + ' lines of code.');
621
- console.error('');
622
- console.error(' Use escape with DATE (expires in 1 month):');
623
- console.error(` // webpieces-disable max-lines-modified ${getTodayDateString()} -- [your reason]`);
624
- console.error('');
625
- }
626
- else {
627
- console.error(' \u26a0\ufe0f disableAllowed is false - disable comments are NOT allowed.');
628
- console.error(' This rule must be met and cannot be disabled since nx.json disableAllowed is set to false.');
629
- console.error(' You MUST refactor to reduce method size.');
630
- console.error('');
631
- console.error(' For a major refactor, a human can add "ignoreModifiedUntilEpoch" to nx.json validate-code options.');
632
- console.error(' This is an expiry timestamp (epoch ms) for when we start forcing everyone to meet size rules again.');
633
- console.error(' Sometimes for speed, we allow methods to expand during a refactor and over time,');
634
- console.error(' each PR reduces methods as they get touched.');
635
- console.error(' AI agents should NOT add ignoreModifiedUntilEpoch - ask a human to do it.');
636
- console.error('');
637
- }
638
- }
639
- async function runExecutor(options, context) {
640
- const workspaceRoot = context.root;
641
- const limit = options.limit ?? 80;
642
- const mode = options.mode ?? 'NEW_AND_MODIFIED_METHODS';
643
- const disableAllowed = options.disableAllowed ?? true;
644
- // Skip validation entirely if mode is OFF
645
- if (mode === 'OFF') {
646
- console.log('\n\u23ed\ufe0f Skipping modified method validation (mode: OFF)');
647
- console.log('');
648
- return { success: true };
649
- }
650
- // If NX_HEAD is set (via nx affected --head=X), use it; otherwise compare to working tree
651
- let base = process.env['NX_BASE'];
652
- const head = process.env['NX_HEAD'];
653
- if (!base) {
654
- base = detectBase(workspaceRoot) ?? undefined;
655
- if (!base) {
656
- console.log('\n\u23ed\ufe0f Skipping modified method validation (could not detect base branch)');
657
- console.log(' To run explicitly: nx affected --target=validate-modified-methods --base=origin/main');
658
- console.log('');
659
- return { success: true };
660
- }
661
- console.log('\n\ud83d\udccf Validating Modified Method Sizes (auto-detected base)\n');
662
- }
663
- else {
664
- console.log('\n\ud83d\udccf Validating Modified Method Sizes\n');
665
- }
666
- console.log(` Base: ${base}`);
667
- console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);
668
- console.log(` Mode: ${mode}`);
669
- console.log(` Limit for modified methods: ${limit}`);
670
- console.log(` Disable allowed: ${disableAllowed}${!disableAllowed ? ' (no escape hatch)' : ''}`);
671
- console.log('');
672
- try {
673
- const changedFiles = getChangedTypeScriptFiles(workspaceRoot, base, head);
674
- if (changedFiles.length === 0) {
675
- console.log('\u2705 No TypeScript files changed');
676
- return { success: true };
677
- }
678
- console.log(`\ud83d\udcc2 Checking ${changedFiles.length} changed file(s)...`);
679
- const violations = findViolations(workspaceRoot, changedFiles, base, limit, disableAllowed, head);
680
- if (violations.length === 0) {
681
- console.log('\u2705 All modified methods are under ' + limit + ' lines');
682
- return { success: true };
683
- }
684
- writeTmpInstructions(workspaceRoot);
685
- reportViolations(violations, limit, disableAllowed);
686
- return { success: false };
687
- }
688
- catch (err) {
689
- const error = err instanceof Error ? err : new Error(String(err));
690
- console.error('\u274c Modified method validation failed:', error.message);
691
- return { success: false };
692
- }
693
- }
694
- //# sourceMappingURL=executor.js.map