@webpieces/dev-config 0.2.61 → 0.2.62

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.
@@ -0,0 +1,510 @@
1
+ /**
2
+ * Validate Modified Files Executor
3
+ *
4
+ * Validates that modified files don't exceed a maximum line count (default 900).
5
+ * This encourages keeping files small and focused - when you touch a file,
6
+ * you must bring it under the limit.
7
+ *
8
+ * Usage:
9
+ * nx affected --target=validate-modified-files --base=origin/main
10
+ *
11
+ * Escape hatch: Add webpieces-disable max-lines-modified-files comment with date and justification
12
+ * Format: // webpieces-disable max-lines-modified-files 2025/01/15 -- [reason]
13
+ * The disable expires after 1 month from the date specified.
14
+ */
15
+
16
+ import type { ExecutorContext } from '@nx/devkit';
17
+ import { execSync } from 'child_process';
18
+ import * as fs from 'fs';
19
+ import * as path from 'path';
20
+
21
+ export interface ValidateModifiedFilesOptions {
22
+ max?: number;
23
+ }
24
+
25
+ export interface ExecutorResult {
26
+ success: boolean;
27
+ }
28
+
29
+ interface FileViolation {
30
+ file: string;
31
+ lines: number;
32
+ expiredDisable?: boolean;
33
+ expiredDate?: string;
34
+ }
35
+
36
+ const TMP_DIR = 'tmp/webpieces';
37
+ const TMP_MD_FILE = 'webpieces.filesize.md';
38
+
39
+ const FILESIZE_DOC_CONTENT = `# AI Agent Instructions: File Too Long
40
+
41
+ **READ THIS FILE to fix files that are too long**
42
+
43
+ ## Core Principle
44
+
45
+ With **stateless systems + dependency injection, refactor is trivial**.
46
+ Pick a method or a few and move to new class XXXXX, then inject XXXXX
47
+ into all users of those methods via the constructor.
48
+ Delete those methods from original class.
49
+
50
+ **99% of files can be less than the configured max lines of code.**
51
+
52
+ Files should contain a SINGLE COHESIVE UNIT.
53
+ - One class per file (Java convention)
54
+ - If class is too large, extract child responsibilities
55
+ - Use dependency injection to compose functionality
56
+
57
+ ## Command: Reduce File Size
58
+
59
+ ### Step 1: Check for Multiple Classes
60
+ If the file contains multiple classes, **SEPARATE each class into its own file**.
61
+
62
+ \`\`\`typescript
63
+ // BAD: UserController.ts (multiple classes)
64
+ export class UserController { /* ... */ }
65
+ export class UserValidator { /* ... */ }
66
+ export class UserNotifier { /* ... */ }
67
+
68
+ // GOOD: Three separate files
69
+ // UserController.ts
70
+ export class UserController { /* ... */ }
71
+
72
+ // UserValidator.ts
73
+ export class UserValidator { /* ... */ }
74
+
75
+ // UserNotifier.ts
76
+ export class UserNotifier { /* ... */ }
77
+ \`\`\`
78
+
79
+ ### Step 2: Extract Child Responsibilities (if single class is too large)
80
+
81
+ #### Pattern: Create New Service Class with Dependency Injection
82
+
83
+ \`\`\`typescript
84
+ // BAD: UserController.ts (800 lines, single class)
85
+ @provideSingleton()
86
+ @Controller()
87
+ export class UserController {
88
+ // 200 lines: CRUD operations
89
+ // 300 lines: validation logic
90
+ // 200 lines: notification logic
91
+ // 100 lines: analytics logic
92
+ }
93
+
94
+ // GOOD: Extract validation service
95
+ // 1. Create UserValidationService.ts
96
+ @provideSingleton()
97
+ export class UserValidationService {
98
+ validateUserData(data: UserData): ValidationResult {
99
+ // 300 lines of validation logic moved here
100
+ }
101
+
102
+ validateEmail(email: string): boolean { /* ... */ }
103
+ validatePassword(password: string): boolean { /* ... */ }
104
+ }
105
+
106
+ // 2. Inject into UserController.ts
107
+ @provideSingleton()
108
+ @Controller()
109
+ export class UserController {
110
+ constructor(
111
+ @inject(TYPES.UserValidationService)
112
+ private validator: UserValidationService
113
+ ) {}
114
+
115
+ async createUser(data: UserData): Promise<User> {
116
+ const validation = this.validator.validateUserData(data);
117
+ if (!validation.isValid) {
118
+ throw new ValidationError(validation.errors);
119
+ }
120
+ // ... rest of logic
121
+ }
122
+ }
123
+ \`\`\`
124
+
125
+ ## AI Agent Action Steps
126
+
127
+ 1. **ANALYZE** the file structure:
128
+ - Count classes (if >1, separate immediately)
129
+ - Identify logical responsibilities within single class
130
+
131
+ 2. **IDENTIFY** "child code" to extract:
132
+ - Validation logic -> ValidationService
133
+ - Notification logic -> NotificationService
134
+ - Data transformation -> TransformerService
135
+ - External API calls -> ApiService
136
+ - Business rules -> RulesEngine
137
+
138
+ 3. **CREATE** new service file(s):
139
+ - Start with temporary name: \`XXXX.ts\` or \`ChildService.ts\`
140
+ - Add \`@provideSingleton()\` decorator
141
+ - Move child methods to new class
142
+
143
+ 4. **UPDATE** dependency injection:
144
+ - Add to \`TYPES\` constants (if using symbol-based DI)
145
+ - Inject new service into original class constructor
146
+ - Replace direct method calls with \`this.serviceName.method()\`
147
+
148
+ 5. **RENAME** extracted file:
149
+ - Read the extracted code to understand its purpose
150
+ - Rename \`XXXX.ts\` to logical name (e.g., \`UserValidationService.ts\`)
151
+
152
+ 6. **VERIFY** file sizes:
153
+ - Original file should now be under the limit
154
+ - Each extracted file should be under the limit
155
+ - If still too large, extract more services
156
+
157
+ ## Examples of Child Responsibilities to Extract
158
+
159
+ | If File Contains | Extract To | Pattern |
160
+ |-----------------|------------|---------|
161
+ | Validation logic (200+ lines) | \`XValidator.ts\` or \`XValidationService.ts\` | Singleton service |
162
+ | Notification logic (150+ lines) | \`XNotifier.ts\` or \`XNotificationService.ts\` | Singleton service |
163
+ | Data transformation (200+ lines) | \`XTransformer.ts\` | Singleton service |
164
+ | External API calls (200+ lines) | \`XApiClient.ts\` | Singleton service |
165
+ | Complex business rules (300+ lines) | \`XRulesEngine.ts\` | Singleton service |
166
+ | Database queries (200+ lines) | \`XRepository.ts\` | Singleton service |
167
+
168
+ ## WebPieces Dependency Injection Pattern
169
+
170
+ \`\`\`typescript
171
+ // 1. Define service with @provideSingleton
172
+ import { provideSingleton } from '@webpieces/http-routing';
173
+
174
+ @provideSingleton()
175
+ export class MyService {
176
+ doSomething(): void { /* ... */ }
177
+ }
178
+
179
+ // 2. Inject into consumer
180
+ import { inject } from 'inversify';
181
+ import { TYPES } from './types';
182
+
183
+ @provideSingleton()
184
+ @Controller()
185
+ export class MyController {
186
+ constructor(
187
+ @inject(TYPES.MyService) private service: MyService
188
+ ) {}
189
+ }
190
+ \`\`\`
191
+
192
+ ## Escape Hatch
193
+
194
+ If refactoring is genuinely not feasible (generated files, complex algorithms, etc.),
195
+ add a disable comment at the TOP of the file (within first 5 lines) with a DATE:
196
+
197
+ \`\`\`typescript
198
+ // webpieces-disable max-lines-modified-files 2025/01/15 -- Complex generated file, refactoring would break generation
199
+ \`\`\`
200
+
201
+ **IMPORTANT**: The date format is yyyy/mm/dd. The disable will EXPIRE after 1 month from this date.
202
+ After expiration, you must either fix the file or update the date to get another month.
203
+ This ensures that disable comments are reviewed periodically.
204
+
205
+ Remember: Find the "child code" and pull it down into a new class. Once moved, the code's purpose becomes clear, making it easy to rename to a logical name.
206
+ `;
207
+
208
+ /**
209
+ * Write the instructions documentation to tmp directory
210
+ */
211
+ function writeTmpInstructions(workspaceRoot: string): string {
212
+ const tmpDir = path.join(workspaceRoot, TMP_DIR);
213
+ const mdPath = path.join(tmpDir, TMP_MD_FILE);
214
+
215
+ fs.mkdirSync(tmpDir, { recursive: true });
216
+ fs.writeFileSync(mdPath, FILESIZE_DOC_CONTENT);
217
+
218
+ return mdPath;
219
+ }
220
+
221
+ /**
222
+ * Get changed TypeScript files between base and working tree.
223
+ * Uses `git diff base` (no three-dots) to match what `nx affected` does -
224
+ * this includes both committed and uncommitted changes in one diff.
225
+ */
226
+ function getChangedTypeScriptFiles(workspaceRoot: string, base: string): string[] {
227
+ try {
228
+ // Use two-dot diff (base to working tree) - same as nx affected
229
+ const output = execSync(`git diff --name-only ${base} -- '*.ts' '*.tsx'`, {
230
+ cwd: workspaceRoot,
231
+ encoding: 'utf-8',
232
+ });
233
+ return output
234
+ .trim()
235
+ .split('\n')
236
+ .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
237
+ } catch {
238
+ return [];
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Parse a date string in yyyy/mm/dd format and return a Date object.
244
+ * Returns null if the format is invalid.
245
+ */
246
+ function parseDisableDate(dateStr: string): Date | null {
247
+ // Match yyyy/mm/dd format
248
+ const match = dateStr.match(/^(\d{4})\/(\d{2})\/(\d{2})$/);
249
+ if (!match) return null;
250
+
251
+ const year = parseInt(match[1], 10);
252
+ const month = parseInt(match[2], 10) - 1; // JS months are 0-indexed
253
+ const day = parseInt(match[3], 10);
254
+
255
+ const date = new Date(year, month, day);
256
+
257
+ // Validate the date is valid (e.g., not Feb 30)
258
+ if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) {
259
+ return null;
260
+ }
261
+
262
+ return date;
263
+ }
264
+
265
+ /**
266
+ * Check if a date is within the last month (not expired).
267
+ */
268
+ function isDateWithinMonth(date: Date): boolean {
269
+ const now = new Date();
270
+ const oneMonthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
271
+ return date >= oneMonthAgo;
272
+ }
273
+
274
+ interface DisableStatus {
275
+ hasDisable: boolean;
276
+ isValid: boolean;
277
+ isExpired: boolean;
278
+ date?: string;
279
+ }
280
+
281
+ /**
282
+ * Check if a file has a valid, non-expired disable comment at the top (within first 5 lines).
283
+ * Returns status object with details about the disable comment.
284
+ */
285
+ // webpieces-disable max-lines-new-methods -- Date validation logic requires checking multiple conditions
286
+ function checkDisableComment(content: string): DisableStatus {
287
+ const lines = content.split('\n').slice(0, 5);
288
+
289
+ for (const line of lines) {
290
+ if (line.includes('webpieces-disable') && line.includes('max-lines-modified-files')) {
291
+ // Found disable comment, now check for date
292
+ // Format: // webpieces-disable max-lines-modified-files yyyy/mm/dd -- reason
293
+ const dateMatch = line.match(/max-lines-modified-files\s+(\d{4}\/\d{2}\/\d{2}|XXXX\/XX\/XX)/);
294
+
295
+ if (!dateMatch) {
296
+ // No date found - invalid disable comment
297
+ return { hasDisable: true, isValid: false, isExpired: false };
298
+ }
299
+
300
+ const dateStr = dateMatch[1];
301
+
302
+ // Secret permanent disable
303
+ if (dateStr === 'XXXX/XX/XX') {
304
+ return { hasDisable: true, isValid: true, isExpired: false, date: dateStr };
305
+ }
306
+
307
+ const date = parseDisableDate(dateStr);
308
+ if (!date) {
309
+ // Invalid date format
310
+ return { hasDisable: true, isValid: false, isExpired: false, date: dateStr };
311
+ }
312
+
313
+ if (!isDateWithinMonth(date)) {
314
+ // Date is expired (older than 1 month)
315
+ return { hasDisable: true, isValid: true, isExpired: true, date: dateStr };
316
+ }
317
+
318
+ // Valid and not expired
319
+ return { hasDisable: true, isValid: true, isExpired: false, date: dateStr };
320
+ }
321
+ }
322
+
323
+ return { hasDisable: false, isValid: false, isExpired: false };
324
+ }
325
+
326
+ /**
327
+ * Count lines in a file and check for violations
328
+ */
329
+ // webpieces-disable max-lines-new-methods -- File iteration with disable checking logic
330
+ function findViolations(workspaceRoot: string, changedFiles: string[], maxLines: number): FileViolation[] {
331
+ const violations: FileViolation[] = [];
332
+
333
+ for (const file of changedFiles) {
334
+ const fullPath = path.join(workspaceRoot, file);
335
+
336
+ if (!fs.existsSync(fullPath)) continue;
337
+
338
+ const content = fs.readFileSync(fullPath, 'utf-8');
339
+ const lineCount = content.split('\n').length;
340
+
341
+ // Skip files under the limit
342
+ if (lineCount <= maxLines) continue;
343
+
344
+ // Check for disable comment
345
+ const disableStatus = checkDisableComment(content);
346
+
347
+ if (disableStatus.hasDisable) {
348
+ if (disableStatus.isValid && !disableStatus.isExpired) {
349
+ // Valid, non-expired disable - skip this file
350
+ continue;
351
+ }
352
+
353
+ if (disableStatus.isExpired) {
354
+ // Expired disable - report as violation with expired info
355
+ violations.push({
356
+ file,
357
+ lines: lineCount,
358
+ expiredDisable: true,
359
+ expiredDate: disableStatus.date,
360
+ });
361
+ continue;
362
+ }
363
+
364
+ // Invalid disable (missing/bad date) - fall through to report as violation
365
+ }
366
+
367
+ violations.push({
368
+ file,
369
+ lines: lineCount,
370
+ });
371
+ }
372
+
373
+ return violations;
374
+ }
375
+
376
+ /**
377
+ * Auto-detect the base branch by finding the merge-base with origin/main.
378
+ */
379
+ function detectBase(workspaceRoot: string): string | null {
380
+ try {
381
+ const mergeBase = execSync('git merge-base HEAD origin/main', {
382
+ cwd: workspaceRoot,
383
+ encoding: 'utf-8',
384
+ stdio: ['pipe', 'pipe', 'pipe'],
385
+ }).trim();
386
+
387
+ if (mergeBase) {
388
+ return mergeBase;
389
+ }
390
+ } catch {
391
+ try {
392
+ const mergeBase = execSync('git merge-base HEAD main', {
393
+ cwd: workspaceRoot,
394
+ encoding: 'utf-8',
395
+ stdio: ['pipe', 'pipe', 'pipe'],
396
+ }).trim();
397
+
398
+ if (mergeBase) {
399
+ return mergeBase;
400
+ }
401
+ } catch {
402
+ // Ignore
403
+ }
404
+ }
405
+ return null;
406
+ }
407
+
408
+ /**
409
+ * Get today's date in yyyy/mm/dd format for error messages
410
+ */
411
+ function getTodayDateString(): string {
412
+ const now = new Date();
413
+ const year = now.getFullYear();
414
+ const month = String(now.getMonth() + 1).padStart(2, '0');
415
+ const day = String(now.getDate()).padStart(2, '0');
416
+ return `${year}/${month}/${day}`;
417
+ }
418
+
419
+ /**
420
+ * Report violations to console
421
+ */
422
+ // webpieces-disable max-lines-new-methods -- Error output formatting with multiple message sections
423
+ function reportViolations(violations: FileViolation[], maxLines: number): void {
424
+ console.error('');
425
+ console.error('āŒ YOU MUST FIX THIS AND NOT be more than ' + maxLines + ' lines of code per file');
426
+ console.error(' as it slows down IDEs AND is VERY VERY EASY to refactor.');
427
+ console.error('');
428
+ console.error('šŸ“š With stateless systems + dependency injection, refactor is trivial:');
429
+ console.error(' Pick a method or a few and move to new class XXXXX, then inject XXXXX');
430
+ console.error(' into all users of those methods via the constructor.');
431
+ console.error(' Delete those methods from original class.');
432
+ console.error(' 99% of files can be less than ' + maxLines + ' lines of code.');
433
+ console.error('');
434
+ console.error('āš ļø *** READ tmp/webpieces/webpieces.filesize.md for detailed guidance on how to fix this easily *** āš ļø');
435
+ console.error('');
436
+
437
+ for (const v of violations) {
438
+ if (v.expiredDisable) {
439
+ console.error(` āŒ ${v.file} (${v.lines} lines, max: ${maxLines})`);
440
+ console.error(` ā° EXPIRED DISABLE: Your disable comment dated ${v.expiredDate} has expired (>1 month old).`);
441
+ console.error(` You must either FIX the file or UPDATE the date to get another month.`);
442
+ } else {
443
+ console.error(` āŒ ${v.file} (${v.lines} lines, max: ${maxLines})`);
444
+ }
445
+ }
446
+ console.error('');
447
+
448
+ console.error(' You can disable this error, but you will be forced to fix again in 1 month');
449
+ console.error(' since 99% of files can be less than ' + maxLines + ' lines of code.');
450
+ console.error('');
451
+ console.error(' Use escape with DATE (expires in 1 month):');
452
+ console.error(` // webpieces-disable max-lines-modified-files ${getTodayDateString()} -- [your reason]`);
453
+ console.error('');
454
+ }
455
+
456
+ export default async function runExecutor(
457
+ options: ValidateModifiedFilesOptions,
458
+ context: ExecutorContext
459
+ ): Promise<ExecutorResult> {
460
+ const workspaceRoot = context.root;
461
+ const maxLines = options.max ?? 900;
462
+
463
+ let base = process.env['NX_BASE'];
464
+
465
+ if (!base) {
466
+ base = detectBase(workspaceRoot) ?? undefined;
467
+
468
+ if (!base) {
469
+ console.log('\nā­ļø Skipping modified files validation (could not detect base branch)');
470
+ console.log(' To run explicitly: nx affected --target=validate-modified-files --base=origin/main');
471
+ console.log('');
472
+ return { success: true };
473
+ }
474
+
475
+ console.log('\nšŸ“ Validating Modified File Sizes (auto-detected base)\n');
476
+ } else {
477
+ console.log('\nšŸ“ Validating Modified File Sizes\n');
478
+ }
479
+
480
+ console.log(` Base: ${base}`);
481
+ console.log(' Comparing to: working tree (includes uncommitted changes)');
482
+ console.log(` Max lines for modified files: ${maxLines}`);
483
+ console.log('');
484
+
485
+ try {
486
+ const changedFiles = getChangedTypeScriptFiles(workspaceRoot, base);
487
+
488
+ if (changedFiles.length === 0) {
489
+ console.log('āœ… No TypeScript files changed');
490
+ return { success: true };
491
+ }
492
+
493
+ console.log(`šŸ“‚ Checking ${changedFiles.length} changed file(s)...`);
494
+
495
+ const violations = findViolations(workspaceRoot, changedFiles, maxLines);
496
+
497
+ if (violations.length === 0) {
498
+ console.log('āœ… All modified files are under ' + maxLines + ' lines');
499
+ return { success: true };
500
+ }
501
+
502
+ writeTmpInstructions(workspaceRoot);
503
+ reportViolations(violations, maxLines);
504
+ return { success: false };
505
+ } catch (err: unknown) {
506
+ const error = err instanceof Error ? err : new Error(String(err));
507
+ console.error('āŒ Modified files validation failed:', error.message);
508
+ return { success: false };
509
+ }
510
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "$schema": "http://json-schema.org/schema",
3
+ "title": "Validate Modified Files Executor",
4
+ "description": "Validates that modified files don't exceed a maximum line count. Encourages keeping files small and focused.",
5
+ "type": "object",
6
+ "properties": {
7
+ "max": {
8
+ "type": "number",
9
+ "description": "Maximum number of lines allowed for modified files",
10
+ "default": 900
11
+ }
12
+ },
13
+ "required": []
14
+ }
@@ -14,7 +14,9 @@
14
14
  * Usage:
15
15
  * nx affected --target=validate-modified-methods --base=origin/main
16
16
  *
17
- * Escape hatch: Add webpieces-disable max-lines-new-and-modified comment with justification
17
+ * Escape hatch: Add webpieces-disable max-lines-new-and-modified comment with date and justification
18
+ * Format: // webpieces-disable max-lines-new-and-modified 2025/01/15 -- [reason]
19
+ * The disable expires after 1 month from the date specified.
18
20
  */
19
21
  import type { ExecutorContext } from '@nx/devkit';
20
22
  export interface ValidateModifiedMethodsOptions {