@webpieces/eslint-plugin 0.0.0-dev

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,258 @@
1
+ "use strict";
2
+ /**
3
+ * ESLint rule to enforce maximum file length
4
+ *
5
+ * Enforces a configurable maximum line count for files.
6
+ * Default: 700 lines
7
+ *
8
+ * Configuration:
9
+ * '@webpieces/max-file-lines': ['error', { max: 700 }]
10
+ */
11
+ const tslib_1 = require("tslib");
12
+ const fs = tslib_1.__importStar(require("fs"));
13
+ const path = tslib_1.__importStar(require("path"));
14
+ const toError_1 = require("../toError");
15
+ const FILE_DOC_CONTENT = `# AI Agent Instructions: File Too Long
16
+
17
+ **READ THIS FILE to fix files that are too long**
18
+
19
+ ## Core Principle
20
+ Files should contain a SINGLE COHESIVE UNIT.
21
+ - One class per file (Java convention)
22
+ - If class is too large, extract child responsibilities
23
+ - Use dependency injection to compose functionality
24
+
25
+ ## Command: Reduce File Size
26
+
27
+ ### Step 1: Check for Multiple Classes
28
+ If the file contains multiple classes, **SEPARATE each class into its own file**.
29
+
30
+ \`\`\`typescript
31
+ // BAD: UserController.ts (multiple classes)
32
+ export class UserController { /* ... */ }
33
+ export class UserValidator { /* ... */ }
34
+ export class UserNotifier { /* ... */ }
35
+
36
+ // GOOD: Three separate files
37
+ // UserController.ts
38
+ export class UserController { /* ... */ }
39
+
40
+ // UserValidator.ts
41
+ export class UserValidator { /* ... */ }
42
+
43
+ // UserNotifier.ts
44
+ export class UserNotifier { /* ... */ }
45
+ \`\`\`
46
+
47
+ ### Step 2: Extract Child Responsibilities (if single class is too large)
48
+
49
+ #### Pattern: Create New Service Class with Dependency Injection
50
+
51
+ \`\`\`typescript
52
+ // BAD: UserController.ts (800 lines, single class)
53
+ @provideSingleton()
54
+ @Controller()
55
+ export class UserController {
56
+ // 200 lines: CRUD operations
57
+ // 300 lines: validation logic
58
+ // 200 lines: notification logic
59
+ // 100 lines: analytics logic
60
+ }
61
+
62
+ // GOOD: Extract validation service
63
+ // 1. Create UserValidationService.ts
64
+ @provideSingleton()
65
+ export class UserValidationService {
66
+ validateUserData(data: UserData): ValidationResult {
67
+ // 300 lines of validation logic moved here
68
+ }
69
+
70
+ validateEmail(email: string): boolean { /* ... */ }
71
+ validatePassword(password: string): boolean { /* ... */ }
72
+ }
73
+
74
+ // 2. Inject into UserController.ts
75
+ @provideSingleton()
76
+ @Controller()
77
+ export class UserController {
78
+ constructor(
79
+ @inject(TYPES.UserValidationService)
80
+ private validator: UserValidationService
81
+ ) {}
82
+
83
+ async createUser(data: UserData): Promise<User> {
84
+ const validation = this.validator.validateUserData(data);
85
+ if (!validation.isValid) {
86
+ throw new ValidationError(validation.errors);
87
+ }
88
+ // ... rest of logic
89
+ }
90
+ }
91
+ \`\`\`
92
+
93
+ ## AI Agent Action Steps
94
+
95
+ 1. **ANALYZE** the file structure:
96
+ - Count classes (if >1, separate immediately)
97
+ - Identify logical responsibilities within single class
98
+
99
+ 2. **IDENTIFY** "child code" to extract:
100
+ - Validation logic -> ValidationService
101
+ - Notification logic -> NotificationService
102
+ - Data transformation -> TransformerService
103
+ - External API calls -> ApiService
104
+ - Business rules -> RulesEngine
105
+
106
+ 3. **CREATE** new service file(s):
107
+ - Start with temporary name: \`XXXX.ts\` or \`ChildService.ts\`
108
+ - Add \`@provideSingleton()\` decorator
109
+ - Move child methods to new class
110
+
111
+ 4. **UPDATE** dependency injection:
112
+ - Add to \`TYPES\` constants (if using symbol-based DI)
113
+ - Inject new service into original class constructor
114
+ - Replace direct method calls with \`this.serviceName.method()\`
115
+
116
+ 5. **RENAME** extracted file:
117
+ - Read the extracted code to understand its purpose
118
+ - Rename \`XXXX.ts\` to logical name (e.g., \`UserValidationService.ts\`)
119
+
120
+ 6. **VERIFY** file sizes:
121
+ - Original file should now be <700 lines
122
+ - Each extracted file should be <700 lines
123
+ - If still too large, extract more services
124
+
125
+ ## Examples of Child Responsibilities to Extract
126
+
127
+ | If File Contains | Extract To | Pattern |
128
+ |-----------------|------------|---------|
129
+ | Validation logic (200+ lines) | \`XValidator.ts\` or \`XValidationService.ts\` | Singleton service |
130
+ | Notification logic (150+ lines) | \`XNotifier.ts\` or \`XNotificationService.ts\` | Singleton service |
131
+ | Data transformation (200+ lines) | \`XTransformer.ts\` | Singleton service |
132
+ | External API calls (200+ lines) | \`XApiClient.ts\` | Singleton service |
133
+ | Complex business rules (300+ lines) | \`XRulesEngine.ts\` | Singleton service |
134
+ | Database queries (200+ lines) | \`XRepository.ts\` | Singleton service |
135
+
136
+ ## WebPieces Dependency Injection Pattern
137
+
138
+ \`\`\`typescript
139
+ // 1. Define service with @provideSingleton
140
+ import { provideSingleton } from '@webpieces/http-routing';
141
+
142
+ @provideSingleton()
143
+ export class MyService {
144
+ doSomething(): void { /* ... */ }
145
+ }
146
+
147
+ // 2. Inject into consumer
148
+ import { inject } from 'inversify';
149
+ import { TYPES } from './types';
150
+
151
+ @provideSingleton()
152
+ @Controller()
153
+ export class MyController {
154
+ constructor(
155
+ @inject(TYPES.MyService) private service: MyService
156
+ ) {}
157
+ }
158
+ \`\`\`
159
+
160
+ 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.
161
+ `;
162
+ // Module-level flag to prevent redundant file creation
163
+ let fileDocCreated = false;
164
+ function getWorkspaceRoot(context) {
165
+ const filename = context.filename || context.getFilename();
166
+ let dir = path.dirname(filename);
167
+ // Walk up directory tree to find workspace root
168
+ while (dir !== path.dirname(dir)) {
169
+ const pkgPath = path.join(dir, 'package.json');
170
+ if (fs.existsSync(pkgPath)) {
171
+ try {
172
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
173
+ if (pkg.workspaces || pkg.name === 'webpieces-ts') {
174
+ return dir;
175
+ }
176
+ }
177
+ catch (err) {
178
+ //const error = toError(err);
179
+ void err; // Continue searching if JSON parse fails
180
+ }
181
+ }
182
+ dir = path.dirname(dir);
183
+ }
184
+ return process.cwd(); // Fallback
185
+ }
186
+ function ensureDocFile(docPath, content) {
187
+ try {
188
+ fs.mkdirSync(path.dirname(docPath), { recursive: true });
189
+ fs.writeFileSync(docPath, content, 'utf-8');
190
+ return true;
191
+ }
192
+ catch (err) {
193
+ const error = (0, toError_1.toError)(err);
194
+ console.warn(`[webpieces] Could not create doc file: ${docPath}`, error);
195
+ return false;
196
+ }
197
+ }
198
+ function ensureFileDoc(context) {
199
+ if (fileDocCreated)
200
+ return; // Performance: only create once per lint run
201
+ const workspaceRoot = getWorkspaceRoot(context);
202
+ const docPath = path.join(workspaceRoot, 'tmp', 'webpieces', 'webpieces.filesize.md');
203
+ if (ensureDocFile(docPath, FILE_DOC_CONTENT)) {
204
+ fileDocCreated = true;
205
+ }
206
+ }
207
+ const rule = {
208
+ meta: {
209
+ type: 'suggestion',
210
+ docs: {
211
+ description: 'Enforce maximum file length',
212
+ category: 'Best Practices',
213
+ recommended: false,
214
+ url: 'https://github.com/deanhiller/webpieces-ts',
215
+ },
216
+ messages: {
217
+ tooLong: 'AI Agent: READ tmp/webpieces/webpieces.filesize.md for fix instructions. File has {{actual}} lines (max: {{max}})',
218
+ },
219
+ fixable: undefined,
220
+ schema: [
221
+ {
222
+ type: 'object',
223
+ properties: {
224
+ max: {
225
+ type: 'integer',
226
+ minimum: 1,
227
+ },
228
+ },
229
+ additionalProperties: false,
230
+ },
231
+ ],
232
+ },
233
+ create(context) {
234
+ const options = context.options[0];
235
+ const maxLines = options?.max ?? 700;
236
+ return {
237
+ // webpieces-disable no-any-unknown -- ESTree AST nodes require any for dynamic properties
238
+ Program(node) {
239
+ ensureFileDoc(context);
240
+ const sourceCode = context.sourceCode || context.getSourceCode();
241
+ const lines = sourceCode.lines;
242
+ const lineCount = lines.length;
243
+ if (lineCount > maxLines) {
244
+ context.report({
245
+ node,
246
+ messageId: 'tooLong',
247
+ data: {
248
+ actual: String(lineCount),
249
+ max: String(maxLines),
250
+ },
251
+ });
252
+ }
253
+ },
254
+ };
255
+ },
256
+ };
257
+ module.exports = rule;
258
+ //# sourceMappingURL=max-file-lines.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"max-file-lines.js","sourceRoot":"","sources":["../../../../../../packages/tooling/eslint-plugin/src/rules/max-file-lines.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;AAGH,+CAAyB;AACzB,mDAA6B;AAC7B,wCAAqC;AAMrC,MAAM,gBAAgB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkJxB,CAAC;AAEF,uDAAuD;AACvD,IAAI,cAAc,GAAG,KAAK,CAAC;AAE3B,SAAS,gBAAgB,CAAC,OAAyB;IAC/C,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC;IAC3D,IAAI,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IAEjC,gDAAgD;IAChD,OAAO,GAAG,KAAK,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QAC/B,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;QAC/C,IAAI,EAAE,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC;YACzB,IAAI,CAAC;gBACD,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;gBAC1D,IAAI,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC,IAAI,KAAK,cAAc,EAAE,CAAC;oBAChD,OAAO,GAAG,CAAC;gBACf,CAAC;YACL,CAAC;YAAC,OAAO,GAAY,EAAE,CAAC;gBACpB,6BAA6B;gBAC7B,KAA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SACpD;QACD,QAAQ,EAAE;YACN,OAAO,EACH,mHAAmH;SAC1H;QACD,OAAO,EAAE,SAAS;QAClB,MAAM,EAAE;YACJ;gBACI,IAAI,EAAE,QAAQ;gBACd,UAAU,EAAE;oBACR,GAAG,EAAE;wBACD,IAAI,EAAE,SAAS;wBACf,OAAO,EAAE,CAAC;qBACb;iBACJ;gBACD,oBAAoB,EAAE,KAAK;aAC9B;SACJ;KACJ;IAED,MAAM,CAAC,OAAyB;QAC5B,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,CAAiC,CAAC;QACnE,MAAM,QAAQ,GAAG,OAAO,EAAE,GAAG,IAAI,GAAG,CAAC;QAErC,OAAO;YACH,0FAA0F;YAC1F,OAAO,CAAC,IAAS;gBACb,aAAa,CAAC,OAAO,CAAC,CAAC;gBAEvB,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,IAAI,OAAO,CAAC,aAAa,EAAE,CAAC;gBACjE,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;gBAC/B,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC;gBAE/B,IAAI,SAAS,GAAG,QAAQ,EAAE,CAAC;oBACvB,OAAO,CAAC,MAAM,CAAC;wBACX,IAAI;wBACJ,SAAS,EAAE,SAAS;wBACpB,IAAI,EAAE;4BACF,MAAM,EAAE,MAAM,CAAC,SAAS,CAAC;4BACzB,GAAG,EAAE,MAAM,CAAC,QAAQ,CAAC;yBACxB;qBACJ,CAAC,CAAC;gBACP,CAAC;YACL,CAAC;SACJ,CAAC;IACN,CAAC;CACJ,CAAC;AAEF,iBAAS,IAAI,CAAC","sourcesContent":["/**\n * ESLint rule to enforce maximum file length\n *\n * Enforces a configurable maximum line count for files.\n * Default: 700 lines\n *\n * Configuration:\n * '@webpieces/max-file-lines': ['error', { max: 700 }]\n */\n\nimport type { Rule } from 'eslint';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { toError } from '../toError';\n\ninterface FileLinesOptions {\n max: number;\n}\n\nconst FILE_DOC_CONTENT = `# AI Agent Instructions: File Too Long\n\n**READ THIS FILE to fix files that are too long**\n\n## Core Principle\nFiles should contain a SINGLE COHESIVE UNIT.\n- One class per file (Java convention)\n- If class is too large, extract child responsibilities\n- Use dependency injection to compose functionality\n\n## Command: Reduce File Size\n\n### Step 1: Check for Multiple Classes\nIf the file contains multiple classes, **SEPARATE each class into its own file**.\n\n\\`\\`\\`typescript\n// BAD: UserController.ts (multiple classes)\nexport class UserController { /* ... */ }\nexport class UserValidator { /* ... */ }\nexport class UserNotifier { /* ... */ }\n\n// GOOD: Three separate files\n// UserController.ts\nexport class UserController { /* ... */ }\n\n// UserValidator.ts\nexport class UserValidator { /* ... */ }\n\n// UserNotifier.ts\nexport class UserNotifier { /* ... */ }\n\\`\\`\\`\n\n### Step 2: Extract Child Responsibilities (if single class is too large)\n\n#### Pattern: Create New Service Class with Dependency Injection\n\n\\`\\`\\`typescript\n// BAD: UserController.ts (800 lines, single class)\n@provideSingleton()\n@Controller()\nexport class UserController {\n // 200 lines: CRUD operations\n // 300 lines: validation logic\n // 200 lines: notification logic\n // 100 lines: analytics logic\n}\n\n// GOOD: Extract validation service\n// 1. Create UserValidationService.ts\n@provideSingleton()\nexport class UserValidationService {\n validateUserData(data: UserData): ValidationResult {\n // 300 lines of validation logic moved here\n }\n\n validateEmail(email: string): boolean { /* ... */ }\n validatePassword(password: string): boolean { /* ... */ }\n}\n\n// 2. Inject into UserController.ts\n@provideSingleton()\n@Controller()\nexport class UserController {\n constructor(\n @inject(TYPES.UserValidationService)\n private validator: UserValidationService\n ) {}\n\n async createUser(data: UserData): Promise<User> {\n const validation = this.validator.validateUserData(data);\n if (!validation.isValid) {\n throw new ValidationError(validation.errors);\n }\n // ... rest of logic\n }\n}\n\\`\\`\\`\n\n## AI Agent Action Steps\n\n1. **ANALYZE** the file structure:\n - Count classes (if >1, separate immediately)\n - Identify logical responsibilities within single class\n\n2. **IDENTIFY** \"child code\" to extract:\n - Validation logic -> ValidationService\n - Notification logic -> NotificationService\n - Data transformation -> TransformerService\n - External API calls -> ApiService\n - Business rules -> RulesEngine\n\n3. **CREATE** new service file(s):\n - Start with temporary name: \\`XXXX.ts\\` or \\`ChildService.ts\\`\n - Add \\`@provideSingleton()\\` decorator\n - Move child methods to new class\n\n4. **UPDATE** dependency injection:\n - Add to \\`TYPES\\` constants (if using symbol-based DI)\n - Inject new service into original class constructor\n - Replace direct method calls with \\`this.serviceName.method()\\`\n\n5. **RENAME** extracted file:\n - Read the extracted code to understand its purpose\n - Rename \\`XXXX.ts\\` to logical name (e.g., \\`UserValidationService.ts\\`)\n\n6. **VERIFY** file sizes:\n - Original file should now be <700 lines\n - Each extracted file should be <700 lines\n - If still too large, extract more services\n\n## Examples of Child Responsibilities to Extract\n\n| If File Contains | Extract To | Pattern |\n|-----------------|------------|---------|\n| Validation logic (200+ lines) | \\`XValidator.ts\\` or \\`XValidationService.ts\\` | Singleton service |\n| Notification logic (150+ lines) | \\`XNotifier.ts\\` or \\`XNotificationService.ts\\` | Singleton service |\n| Data transformation (200+ lines) | \\`XTransformer.ts\\` | Singleton service |\n| External API calls (200+ lines) | \\`XApiClient.ts\\` | Singleton service |\n| Complex business rules (300+ lines) | \\`XRulesEngine.ts\\` | Singleton service |\n| Database queries (200+ lines) | \\`XRepository.ts\\` | Singleton service |\n\n## WebPieces Dependency Injection Pattern\n\n\\`\\`\\`typescript\n// 1. Define service with @provideSingleton\nimport { provideSingleton } from '@webpieces/http-routing';\n\n@provideSingleton()\nexport class MyService {\n doSomething(): void { /* ... */ }\n}\n\n// 2. Inject into consumer\nimport { inject } from 'inversify';\nimport { TYPES } from './types';\n\n@provideSingleton()\n@Controller()\nexport class MyController {\n constructor(\n @inject(TYPES.MyService) private service: MyService\n ) {}\n}\n\\`\\`\\`\n\nRemember: 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.\n`;\n\n// Module-level flag to prevent redundant file creation\nlet fileDocCreated = false;\n\nfunction getWorkspaceRoot(context: Rule.RuleContext): string {\n const filename = context.filename || context.getFilename();\n let dir = path.dirname(filename);\n\n // Walk up directory tree to find workspace root\n while (dir !== path.dirname(dir)) {\n const pkgPath = path.join(dir, 'package.json');\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));\n if (pkg.workspaces || pkg.name === 'webpieces-ts') {\n return dir;\n }\n } catch (err: unknown) {\n //const error = toError(err);\n void err; // Continue searching if JSON parse fails\n }\n }\n dir = path.dirname(dir);\n }\n return process.cwd(); // Fallback\n}\n\nfunction ensureDocFile(docPath: string, content: string): boolean {\n try {\n fs.mkdirSync(path.dirname(docPath), { recursive: true });\n fs.writeFileSync(docPath, content, 'utf-8');\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n console.warn(`[webpieces] Could not create doc file: ${docPath}`, error);\n return false;\n }\n}\n\nfunction ensureFileDoc(context: Rule.RuleContext): void {\n if (fileDocCreated) return; // Performance: only create once per lint run\n\n const workspaceRoot = getWorkspaceRoot(context);\n const docPath = path.join(workspaceRoot, 'tmp', 'webpieces', 'webpieces.filesize.md');\n\n if (ensureDocFile(docPath, FILE_DOC_CONTENT)) {\n fileDocCreated = true;\n }\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: 'suggestion',\n docs: {\n description: 'Enforce maximum file length',\n category: 'Best Practices',\n recommended: false,\n url: 'https://github.com/deanhiller/webpieces-ts',\n },\n messages: {\n tooLong:\n 'AI Agent: READ tmp/webpieces/webpieces.filesize.md for fix instructions. File has {{actual}} lines (max: {{max}})',\n },\n fixable: undefined,\n schema: [\n {\n type: 'object',\n properties: {\n max: {\n type: 'integer',\n minimum: 1,\n },\n },\n additionalProperties: false,\n },\n ],\n },\n\n create(context: Rule.RuleContext): Rule.RuleListener {\n const options = context.options[0] as FileLinesOptions | undefined;\n const maxLines = options?.max ?? 700;\n\n return {\n // webpieces-disable no-any-unknown -- ESTree AST nodes require any for dynamic properties\n Program(node: any): void {\n ensureFileDoc(context);\n\n const sourceCode = context.sourceCode || context.getSourceCode();\n const lines = sourceCode.lines;\n const lineCount = lines.length;\n\n if (lineCount > maxLines) {\n context.report({\n node,\n messageId: 'tooLong',\n data: {\n actual: String(lineCount),\n max: String(maxLines),\n },\n });\n }\n },\n };\n },\n};\n\nexport = rule;\n"]}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * ESLint rule to enforce maximum method length
3
+ *
4
+ * Enforces a configurable maximum line count for methods, functions, and arrow functions.
5
+ * Default: 70 lines
6
+ *
7
+ * Configuration:
8
+ * '@webpieces/max-method-lines': ['error', { max: 70 }]
9
+ */
10
+ import type { Rule } from 'eslint';
11
+ declare const rule: Rule.RuleModule;
12
+ export = rule;
@@ -0,0 +1,243 @@
1
+ "use strict";
2
+ /**
3
+ * ESLint rule to enforce maximum method length
4
+ *
5
+ * Enforces a configurable maximum line count for methods, functions, and arrow functions.
6
+ * Default: 70 lines
7
+ *
8
+ * Configuration:
9
+ * '@webpieces/max-method-lines': ['error', { max: 70 }]
10
+ */
11
+ const tslib_1 = require("tslib");
12
+ const fs = tslib_1.__importStar(require("fs"));
13
+ const path = tslib_1.__importStar(require("path"));
14
+ const toError_1 = require("../toError");
15
+ const METHOD_DOC_CONTENT = `# AI Agent Instructions: Method Too Long
16
+
17
+ **READ THIS FILE to fix methods that are too long**
18
+
19
+ ## Core Principle
20
+ Every method should read like a TABLE OF CONTENTS of a book.
21
+ - Each method call is a "chapter"
22
+ - When you dive into a method, you find another table of contents
23
+ - Keeping methods under 70 lines is achievable with proper extraction
24
+
25
+ ## Command: Extract Code into Named Methods
26
+
27
+ ### Pattern 1: Extract Loop Bodies
28
+ \`\`\`typescript
29
+ // BAD: 50 lines embedded in loop
30
+ for (const order of orders) {
31
+ // 20 lines of validation logic
32
+ // 15 lines of processing logic
33
+ // 10 lines of notification logic
34
+ }
35
+
36
+ // GOOD: Extracted to named methods
37
+ for (const order of orders) {
38
+ validateOrder(order);
39
+ processOrderItems(order);
40
+ sendNotifications(order);
41
+ }
42
+ \`\`\`
43
+
44
+ ### Pattern 2: Try-Catch Wrapper for Exception Handling
45
+ \`\`\`typescript
46
+ // GOOD: Separates success path from error handling
47
+ async function handleRequest(req: Request): Promise<Response> {
48
+ try {
49
+ return await executeRequest(req);
50
+ } catch (err: unknown) {
51
+ const error = toError(err);
52
+ return createErrorResponse(error);
53
+ }
54
+ }
55
+ \`\`\`
56
+
57
+ ### Pattern 3: Sequential Method Calls (Table of Contents)
58
+ \`\`\`typescript
59
+ // GOOD: Self-documenting steps
60
+ function processOrder(order: Order): void {
61
+ validateOrderData(order);
62
+ calculateTotals(order);
63
+ applyDiscounts(order);
64
+ processPayment(order);
65
+ updateInventory(order);
66
+ sendConfirmation(order);
67
+ }
68
+ \`\`\`
69
+
70
+ ### Pattern 4: Separate Data Object Creation
71
+ \`\`\`typescript
72
+ // BAD: 15 lines of inline object creation
73
+ doSomething({ field1: ..., field2: ..., field3: ..., /* 15 more fields */ });
74
+
75
+ // GOOD: Extract to factory method
76
+ const request = createRequestObject(data);
77
+ doSomething(request);
78
+ \`\`\`
79
+
80
+ ### Pattern 5: Extract Inline Logic to Named Functions
81
+ \`\`\`typescript
82
+ // BAD: Complex inline logic
83
+ if (user.role === 'admin' && user.permissions.includes('write') && !user.suspended) {
84
+ // 30 lines of admin logic
85
+ }
86
+
87
+ // GOOD: Extract to named methods
88
+ if (isAdminWithWriteAccess(user)) {
89
+ performAdminOperation(user);
90
+ }
91
+ \`\`\`
92
+
93
+ ## AI Agent Action Steps
94
+
95
+ 1. **IDENTIFY** the long method in the error message
96
+ 2. **READ** the method to understand its logical sections
97
+ 3. **EXTRACT** logical units into separate methods with descriptive names
98
+ 4. **REPLACE** inline code with method calls
99
+ 5. **VERIFY** each extracted method is <70 lines
100
+ 6. **TEST** that functionality remains unchanged
101
+
102
+ ## Examples of "Logical Units" to Extract
103
+ - Validation logic -> \`validateX()\`
104
+ - Data transformation -> \`transformXToY()\`
105
+ - API calls -> \`fetchXFromApi()\`
106
+ - Object creation -> \`createX()\`
107
+ - Loop bodies -> \`processItem()\`
108
+ - Error handling -> \`handleXError()\`
109
+
110
+ Remember: Methods should read like a table of contents. Each line should be a "chapter title" (method call) that describes what happens, not how it happens.
111
+ `;
112
+ // Module-level flag to prevent redundant file creation
113
+ let methodDocCreated = false;
114
+ function getWorkspaceRoot(context) {
115
+ const filename = context.filename || context.getFilename();
116
+ let dir = path.dirname(filename);
117
+ while (dir !== path.dirname(dir)) {
118
+ const pkgPath = path.join(dir, 'package.json');
119
+ if (fs.existsSync(pkgPath)) {
120
+ try {
121
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
122
+ if (pkg.workspaces || pkg.name === 'webpieces-ts') {
123
+ return dir;
124
+ }
125
+ }
126
+ catch (err) {
127
+ //const error = toError(err);
128
+ void err;
129
+ }
130
+ }
131
+ dir = path.dirname(dir);
132
+ }
133
+ return process.cwd();
134
+ }
135
+ function ensureDocFile(docPath, content) {
136
+ try {
137
+ fs.mkdirSync(path.dirname(docPath), { recursive: true });
138
+ fs.writeFileSync(docPath, content, 'utf-8');
139
+ return true;
140
+ }
141
+ catch (err) {
142
+ const error = (0, toError_1.toError)(err);
143
+ console.warn(`[webpieces] Could not create doc file: ${docPath}`, error);
144
+ return false;
145
+ }
146
+ }
147
+ function ensureMethodDoc(context) {
148
+ const workspaceRoot = getWorkspaceRoot(context);
149
+ const docPath = path.join(workspaceRoot, 'tmp', 'webpieces', 'webpieces.methods.md');
150
+ // Check if file exists AND flag is true - if both, skip
151
+ if (methodDocCreated && fs.existsSync(docPath))
152
+ return;
153
+ if (ensureDocFile(docPath, METHOD_DOC_CONTENT)) {
154
+ methodDocCreated = true;
155
+ }
156
+ }
157
+ function getFunctionName(funcNode) {
158
+ if (funcNode.type === 'FunctionDeclaration' && funcNode.id?.name) {
159
+ return funcNode.id.name;
160
+ }
161
+ if (funcNode.type === 'FunctionExpression' && funcNode.id?.name) {
162
+ return funcNode.id.name;
163
+ }
164
+ return 'anonymous';
165
+ }
166
+ // webpieces-disable no-any-unknown -- ESTree AST nodes require any for dynamic properties
167
+ function reportTooLong(ctx, node, name, lineCount) {
168
+ ctx.context.report({
169
+ node,
170
+ messageId: 'tooLong',
171
+ data: {
172
+ name,
173
+ actual: String(lineCount),
174
+ max: String(ctx.maxLines),
175
+ },
176
+ });
177
+ }
178
+ // webpieces-disable no-any-unknown -- ESTree AST nodes require any for dynamic properties
179
+ function checkFunctionNode(ctx, node) {
180
+ ensureMethodDoc(ctx.context);
181
+ const funcNode = node;
182
+ // Skip function expressions inside method definitions
183
+ if (funcNode.type === 'FunctionExpression' && funcNode['parent']?.type === 'MethodDefinition') {
184
+ return;
185
+ }
186
+ if (!funcNode.loc || !funcNode.body)
187
+ return;
188
+ const name = getFunctionName(funcNode);
189
+ const lineCount = funcNode.loc.end.line - funcNode.loc.start.line + 1;
190
+ if (lineCount > ctx.maxLines) {
191
+ reportTooLong(ctx, funcNode, name, lineCount);
192
+ }
193
+ }
194
+ // webpieces-disable no-any-unknown -- ESTree AST nodes require any for dynamic properties
195
+ function checkMethodNode(ctx, node) {
196
+ ensureMethodDoc(ctx.context);
197
+ if (!node.loc || !node.value)
198
+ return;
199
+ const name = node.key?.name || 'anonymous';
200
+ const lineCount = node.loc.end.line - node.loc.start.line + 1;
201
+ if (lineCount > ctx.maxLines) {
202
+ reportTooLong(ctx, node, name, lineCount);
203
+ }
204
+ }
205
+ const rule = {
206
+ meta: {
207
+ type: 'suggestion',
208
+ docs: {
209
+ description: 'Enforce maximum method length',
210
+ category: 'Best Practices',
211
+ recommended: false,
212
+ url: 'https://github.com/deanhiller/webpieces-ts',
213
+ },
214
+ messages: {
215
+ tooLong: 'AI Agent: READ tmp/webpieces/webpieces.methods.md for fix instructions. Method "{{name}}" has {{actual}} lines (max: {{max}})',
216
+ },
217
+ fixable: undefined,
218
+ schema: [
219
+ {
220
+ type: 'object',
221
+ properties: {
222
+ max: {
223
+ type: 'integer',
224
+ minimum: 1,
225
+ },
226
+ },
227
+ additionalProperties: false,
228
+ },
229
+ ],
230
+ },
231
+ create(context) {
232
+ const options = context.options[0];
233
+ const ctx = { context, maxLines: options?.max ?? 70 };
234
+ return {
235
+ FunctionDeclaration: (node) => checkFunctionNode(ctx, node),
236
+ FunctionExpression: (node) => checkFunctionNode(ctx, node),
237
+ ArrowFunctionExpression: (node) => checkFunctionNode(ctx, node),
238
+ MethodDefinition: (node) => checkMethodNode(ctx, node),
239
+ };
240
+ },
241
+ };
242
+ module.exports = rule;
243
+ //# sourceMappingURL=max-method-lines.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"max-method-lines.js","sourceRoot":"","sources":["../../../../../../packages/tooling/eslint-plugin/src/rules/max-method-lines.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;AAGH,+CAAyB;AACzB,mDAA6B;AAC7B,wCAAqC;AAkCrC,MAAM,kBAAkB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgG1B,CAAC;AAEF,uDAAuD;AACvD,IAAI,gBAAgB,GAAG,KAAK,CAAC;AAE7B,SAAS,gBAAgB,CAAC,OAAyB;IAC/C,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC;IAC3D,IAAI,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IAEjC,OAAO,GAAG,KAAK,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QAC/B,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;QAC/C,IAAI,EAAE,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC;YACzB,IAAI,CAAC;gBACD,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK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ACb;iBACJ;gBACD,oBAAoB,EAAE,KAAK;aAC9B;SACJ;KACJ;IAED,MAAM,CAAC,OAAyB;QAC5B,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,CAAmC,CAAC;QACrE,MAAM,GAAG,GAAmB,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,IAAI,EAAE,EAAE,CAAC;QAEtE,OAAO;YACH,mBAAmB,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,iBAAiB,CAAC,GAAG,EAAE,IAAI,CAAC;YAC3D,kBAAkB,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,iBAAiB,CAAC,GAAG,EAAE,IAAI,CAAC;YAC1D,uBAAuB,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,iBAAiB,CAAC,GAAG,EAAE,IAAI,CAAC;YAC/D,gBAAgB,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,eAAe,CAAC,GAAG,EAAE,IAAI,CAAC;SACzD,CAAC;IACN,CAAC;CACJ,CAAC;AAEF,iBAAS,IAAI,CAAC","sourcesContent":["/**\n * ESLint rule to enforce maximum method length\n *\n * Enforces a configurable maximum line count for methods, functions, and arrow functions.\n * Default: 70 lines\n *\n * Configuration:\n * '@webpieces/max-method-lines': ['error', { max: 70 }]\n */\n\nimport type { Rule } from 'eslint';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { toError } from '../toError';\n\ninterface MethodLinesOptions {\n max: number;\n}\n\n// webpieces-disable no-any-unknown -- ESTree AST nodes require any for dynamic properties\ninterface FunctionNode {\n type:\n | 'FunctionDeclaration'\n | 'FunctionExpression'\n | 'ArrowFunctionExpression'\n | 'MethodDefinition';\n // webpieces-disable no-any-unknown -- ESTree AST dynamic body\n body?: any;\n loc?: {\n start: { line: number };\n end: { line: number };\n };\n key?: {\n name?: string;\n };\n id?: {\n name?: string;\n };\n // webpieces-disable no-any-unknown -- ESTree AST nodes require any for dynamic properties\n [key: string]: any;\n}\n\ninterface CheckerContext {\n context: Rule.RuleContext;\n maxLines: number;\n}\n\nconst METHOD_DOC_CONTENT = `# AI Agent Instructions: Method Too Long\n\n**READ THIS FILE to fix methods that are too long**\n\n## Core Principle\nEvery method should read like a TABLE OF CONTENTS of a book.\n- Each method call is a \"chapter\"\n- When you dive into a method, you find another table of contents\n- Keeping methods under 70 lines is achievable with proper extraction\n\n## Command: Extract Code into Named Methods\n\n### Pattern 1: Extract Loop Bodies\n\\`\\`\\`typescript\n// BAD: 50 lines embedded in loop\nfor (const order of orders) {\n // 20 lines of validation logic\n // 15 lines of processing logic\n // 10 lines of notification logic\n}\n\n// GOOD: Extracted to named methods\nfor (const order of orders) {\n validateOrder(order);\n processOrderItems(order);\n sendNotifications(order);\n}\n\\`\\`\\`\n\n### Pattern 2: Try-Catch Wrapper for Exception Handling\n\\`\\`\\`typescript\n// GOOD: Separates success path from error handling\nasync function handleRequest(req: Request): Promise<Response> {\n try {\n return await executeRequest(req);\n } catch (err: unknown) {\n const error = toError(err);\n return createErrorResponse(error);\n }\n}\n\\`\\`\\`\n\n### Pattern 3: Sequential Method Calls (Table of Contents)\n\\`\\`\\`typescript\n// GOOD: Self-documenting steps\nfunction processOrder(order: Order): void {\n validateOrderData(order);\n calculateTotals(order);\n applyDiscounts(order);\n processPayment(order);\n updateInventory(order);\n sendConfirmation(order);\n}\n\\`\\`\\`\n\n### Pattern 4: Separate Data Object Creation\n\\`\\`\\`typescript\n// BAD: 15 lines of inline object creation\ndoSomething({ field1: ..., field2: ..., field3: ..., /* 15 more fields */ });\n\n// GOOD: Extract to factory method\nconst request = createRequestObject(data);\ndoSomething(request);\n\\`\\`\\`\n\n### Pattern 5: Extract Inline Logic to Named Functions\n\\`\\`\\`typescript\n// BAD: Complex inline logic\nif (user.role === 'admin' && user.permissions.includes('write') && !user.suspended) {\n // 30 lines of admin logic\n}\n\n// GOOD: Extract to named methods\nif (isAdminWithWriteAccess(user)) {\n performAdminOperation(user);\n}\n\\`\\`\\`\n\n## AI Agent Action Steps\n\n1. **IDENTIFY** the long method in the error message\n2. **READ** the method to understand its logical sections\n3. **EXTRACT** logical units into separate methods with descriptive names\n4. **REPLACE** inline code with method calls\n5. **VERIFY** each extracted method is <70 lines\n6. **TEST** that functionality remains unchanged\n\n## Examples of \"Logical Units\" to Extract\n- Validation logic -> \\`validateX()\\`\n- Data transformation -> \\`transformXToY()\\`\n- API calls -> \\`fetchXFromApi()\\`\n- Object creation -> \\`createX()\\`\n- Loop bodies -> \\`processItem()\\`\n- Error handling -> \\`handleXError()\\`\n\nRemember: Methods should read like a table of contents. Each line should be a \"chapter title\" (method call) that describes what happens, not how it happens.\n`;\n\n// Module-level flag to prevent redundant file creation\nlet methodDocCreated = false;\n\nfunction getWorkspaceRoot(context: Rule.RuleContext): string {\n const filename = context.filename || context.getFilename();\n let dir = path.dirname(filename);\n\n while (dir !== path.dirname(dir)) {\n const pkgPath = path.join(dir, 'package.json');\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));\n if (pkg.workspaces || pkg.name === 'webpieces-ts') {\n return dir;\n }\n } catch (err: unknown) {\n //const error = toError(err);\n void err;\n }\n }\n dir = path.dirname(dir);\n }\n return process.cwd();\n}\n\nfunction ensureDocFile(docPath: string, content: string): boolean {\n try {\n fs.mkdirSync(path.dirname(docPath), { recursive: true });\n fs.writeFileSync(docPath, content, 'utf-8');\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n console.warn(`[webpieces] Could not create doc file: ${docPath}`, error);\n return false;\n }\n}\n\nfunction ensureMethodDoc(context: Rule.RuleContext): void {\n const workspaceRoot = getWorkspaceRoot(context);\n const docPath = path.join(workspaceRoot, 'tmp', 'webpieces', 'webpieces.methods.md');\n\n // Check if file exists AND flag is true - if both, skip\n if (methodDocCreated && fs.existsSync(docPath)) return;\n\n if (ensureDocFile(docPath, METHOD_DOC_CONTENT)) {\n methodDocCreated = true;\n }\n}\n\nfunction getFunctionName(funcNode: FunctionNode): string {\n if (funcNode.type === 'FunctionDeclaration' && funcNode.id?.name) {\n return funcNode.id.name;\n }\n if (funcNode.type === 'FunctionExpression' && funcNode.id?.name) {\n return funcNode.id.name;\n }\n return 'anonymous';\n}\n\n// webpieces-disable no-any-unknown -- ESTree AST nodes require any for dynamic properties\nfunction reportTooLong(ctx: CheckerContext, node: any, name: string, lineCount: number): void {\n ctx.context.report({\n node,\n messageId: 'tooLong',\n data: {\n name,\n actual: String(lineCount),\n max: String(ctx.maxLines),\n },\n });\n}\n\n// webpieces-disable no-any-unknown -- ESTree AST nodes require any for dynamic properties\nfunction checkFunctionNode(ctx: CheckerContext, node: any): void {\n ensureMethodDoc(ctx.context);\n const funcNode = node as FunctionNode;\n\n // Skip function expressions inside method definitions\n if (funcNode.type === 'FunctionExpression' && funcNode['parent']?.type === 'MethodDefinition') {\n return;\n }\n\n if (!funcNode.loc || !funcNode.body) return;\n\n const name = getFunctionName(funcNode);\n const lineCount = funcNode.loc.end.line - funcNode.loc.start.line + 1;\n\n if (lineCount > ctx.maxLines) {\n reportTooLong(ctx, funcNode, name, lineCount);\n }\n}\n\n// webpieces-disable no-any-unknown -- ESTree AST nodes require any for dynamic properties\nfunction checkMethodNode(ctx: CheckerContext, node: any): void {\n ensureMethodDoc(ctx.context);\n\n if (!node.loc || !node.value) return;\n\n const name = node.key?.name || 'anonymous';\n const lineCount = node.loc.end.line - node.loc.start.line + 1;\n\n if (lineCount > ctx.maxLines) {\n reportTooLong(ctx, node, name, lineCount);\n }\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: 'suggestion',\n docs: {\n description: 'Enforce maximum method length',\n category: 'Best Practices',\n recommended: false,\n url: 'https://github.com/deanhiller/webpieces-ts',\n },\n messages: {\n tooLong:\n 'AI Agent: READ tmp/webpieces/webpieces.methods.md for fix instructions. Method \"{{name}}\" has {{actual}} lines (max: {{max}})',\n },\n fixable: undefined,\n schema: [\n {\n type: 'object',\n properties: {\n max: {\n type: 'integer',\n minimum: 1,\n },\n },\n additionalProperties: false,\n },\n ],\n },\n\n create(context: Rule.RuleContext): Rule.RuleListener {\n const options = context.options[0] as MethodLinesOptions | undefined;\n const ctx: CheckerContext = { context, maxLines: options?.max ?? 70 };\n\n return {\n FunctionDeclaration: (node) => checkFunctionNode(ctx, node),\n FunctionExpression: (node) => checkFunctionNode(ctx, node),\n ArrowFunctionExpression: (node) => checkFunctionNode(ctx, node),\n MethodDefinition: (node) => checkMethodNode(ctx, node),\n };\n },\n};\n\nexport = rule;\n"]}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * ESLint rule to discourage try-catch blocks outside test files
3
+ *
4
+ * Works alongside catch-error-pattern rule:
5
+ * - catch-error-pattern: Enforces HOW to handle exceptions (with toError())
6
+ * - no-unmanaged-exceptions: Enforces WHERE try-catch is allowed (tests only by default)
7
+ *
8
+ * Philosophy: Exceptions should bubble to global error handlers where they are logged
9
+ * with traceId and stored for debugging via /debugLocal and /debugCloud endpoints.
10
+ * Local try-catch blocks break this architecture and create blind spots in production.
11
+ *
12
+ * Auto-allowed in:
13
+ * - Test files (.test.ts, .spec.ts, __tests__/)
14
+ *
15
+ * Requires eslint-disable comment in:
16
+ * - Retry loops with exponential backoff
17
+ * - Batch processing where partial failure is expected
18
+ * - Resource cleanup (with approval)
19
+ */
20
+ import type { Rule } from 'eslint';
21
+ declare const rule: Rule.RuleModule;
22
+ export = rule;