@webpieces/code-rules 0.0.1

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,588 @@
1
+ /**
2
+ * Validate No Destructure Executor
3
+ *
4
+ * Validates that destructuring patterns are not used in TypeScript code.
5
+ * Uses LINE-BASED detection (not method-based) for git diff filtering.
6
+ *
7
+ * ============================================================================
8
+ * VIOLATIONS (BAD) - These patterns are flagged:
9
+ * ============================================================================
10
+ *
11
+ * - const { x, y } = obj — object destructuring in variable declarations
12
+ * - const [a, b] = fn() — array destructuring (except Promise.all)
13
+ * - for (const { email } of items) — object destructuring in for-of loops
14
+ * - for (const [a, b] of items) — array destructuring in for-of (except Object.entries)
15
+ * - const { page = 0 } = opts — destructuring with defaults
16
+ * - const { done: streamDone } = obj — destructuring with renaming
17
+ * - function foo({ x, y }: Type) — function parameter destructuring
18
+ *
19
+ * ============================================================================
20
+ * ALLOWED (skip — NOT violations)
21
+ * ============================================================================
22
+ *
23
+ * - const [a, b] = await Promise.all([...]) — Promise.all array destructuring
24
+ * - for (const [key, value] of Object.entries(obj)) — Object.entries in for-of
25
+ * - const { extracted, ...rest } = obj — rest operator separation
26
+ * - Lines with // webpieces-disable no-destructure -- [reason] (only when disableAllowed: true)
27
+ *
28
+ * ============================================================================
29
+ * MODES (LINE-BASED)
30
+ * ============================================================================
31
+ * - OFF: Skip validation entirely
32
+ * - MODIFIED_CODE: Flag destructuring on changed lines (lines in diff hunks)
33
+ * - MODIFIED_FILES: Flag ALL destructuring in files that were modified
34
+ *
35
+ * ============================================================================
36
+ * ESCAPE HATCH
37
+ * ============================================================================
38
+ * Add comment above the violation:
39
+ * // webpieces-disable no-destructure -- [your justification]
40
+ * const { x, y } = obj;
41
+ */
42
+
43
+ import { execSync } from 'child_process';
44
+ import * as fs from 'fs';
45
+ import * as path from 'path';
46
+ import * as ts from 'typescript';
47
+
48
+ export type NoDestructureMode = 'OFF' | 'MODIFIED_CODE' | 'MODIFIED_FILES';
49
+
50
+ export interface ValidateNoDestructureOptions {
51
+ mode?: NoDestructureMode;
52
+ disableAllowed?: boolean;
53
+ ignoreModifiedUntilEpoch?: number;
54
+ }
55
+
56
+ export interface ExecutorResult {
57
+ success: boolean;
58
+ }
59
+
60
+ interface DestructureViolation {
61
+ file: string;
62
+ line: number;
63
+ column: number;
64
+ context: string;
65
+ }
66
+
67
+ /**
68
+ * Get changed TypeScript files between base and head (or working tree if head not specified).
69
+ */
70
+ // webpieces-disable max-lines-new-methods -- Git command handling with untracked files requires multiple code paths
71
+ function getChangedTypeScriptFiles(workspaceRoot: string, base: string, head?: string): string[] {
72
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
73
+ try {
74
+ const diffTarget = head ? `${base} ${head}` : base;
75
+ const output = execSync(`git diff --name-only ${diffTarget} -- '*.ts' '*.tsx'`, {
76
+ cwd: workspaceRoot,
77
+ encoding: 'utf-8',
78
+ });
79
+ const changedFiles = output
80
+ .trim()
81
+ .split('\n')
82
+ .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
83
+
84
+ if (!head) {
85
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
86
+ try {
87
+ const untrackedOutput = execSync(`git ls-files --others --exclude-standard '*.ts' '*.tsx'`, {
88
+ cwd: workspaceRoot,
89
+ encoding: 'utf-8',
90
+ });
91
+ const untrackedFiles = untrackedOutput
92
+ .trim()
93
+ .split('\n')
94
+ .filter((f) => f && !f.includes('.spec.ts') && !f.includes('.test.ts'));
95
+ const allFiles = new Set([...changedFiles, ...untrackedFiles]);
96
+ return Array.from(allFiles);
97
+ } catch (err: unknown) {
98
+ //const error = toError(err);
99
+ return changedFiles;
100
+ }
101
+ }
102
+
103
+ return changedFiles;
104
+ } catch (err: unknown) {
105
+ //const error = toError(err);
106
+ return [];
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Get the diff content for a specific file.
112
+ */
113
+ function getFileDiff(workspaceRoot: string, file: string, base: string, head?: string): string {
114
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
115
+ try {
116
+ const diffTarget = head ? `${base} ${head}` : base;
117
+ const diff = execSync(`git diff ${diffTarget} -- "${file}"`, {
118
+ cwd: workspaceRoot,
119
+ encoding: 'utf-8',
120
+ });
121
+
122
+ if (!diff && !head) {
123
+ const fullPath = path.join(workspaceRoot, file);
124
+ if (fs.existsSync(fullPath)) {
125
+ const isUntracked = execSync(`git ls-files --others --exclude-standard "${file}"`, {
126
+ cwd: workspaceRoot,
127
+ encoding: 'utf-8',
128
+ }).trim();
129
+
130
+ if (isUntracked) {
131
+ const content = fs.readFileSync(fullPath, 'utf-8');
132
+ const lines = content.split('\n');
133
+ return lines.map((line) => `+${line}`).join('\n');
134
+ }
135
+ }
136
+ }
137
+
138
+ return diff;
139
+ } catch (err: unknown) {
140
+ //const error = toError(err);
141
+ return '';
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Parse diff to extract changed line numbers (additions only - lines starting with +).
147
+ */
148
+ function getChangedLineNumbers(diffContent: string): Set<number> {
149
+ const changedLines = new Set<number>();
150
+ const lines = diffContent.split('\n');
151
+ let currentLine = 0;
152
+
153
+ for (const line of lines) {
154
+ const hunkMatch = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
155
+ if (hunkMatch) {
156
+ currentLine = parseInt(hunkMatch[1], 10);
157
+ continue;
158
+ }
159
+
160
+ if (line.startsWith('+') && !line.startsWith('+++')) {
161
+ changedLines.add(currentLine);
162
+ currentLine++;
163
+ } else if (line.startsWith('-') && !line.startsWith('---')) {
164
+ // Deletions don't increment line number
165
+ } else {
166
+ currentLine++;
167
+ }
168
+ }
169
+
170
+ return changedLines;
171
+ }
172
+
173
+ /**
174
+ * Check if a line contains a webpieces-disable comment for no-destructure.
175
+ */
176
+ function hasDisableComment(lines: string[], lineNumber: number): boolean {
177
+ const startCheck = Math.max(0, lineNumber - 5);
178
+ for (let i = lineNumber - 2; i >= startCheck; i--) {
179
+ const line = lines[i]?.trim() ?? '';
180
+ if (line.startsWith('function ') || line.startsWith('class ') || line.endsWith('}')) {
181
+ break;
182
+ }
183
+ if (line.includes('webpieces-disable') && line.includes('no-destructure')) {
184
+ return true;
185
+ }
186
+ }
187
+ return false;
188
+ }
189
+
190
+ /**
191
+ * Check if an ArrayBindingPattern's initializer is `await Promise.all(...)`.
192
+ */
193
+ function isPromiseAllDestructure(node: ts.ArrayBindingPattern): boolean {
194
+ const parent = node.parent;
195
+ if (!ts.isVariableDeclaration(parent)) return false;
196
+ const initializer = parent.initializer;
197
+ if (!initializer) return false;
198
+
199
+ // Handle: const [a, b] = await Promise.all([...])
200
+ if (ts.isAwaitExpression(initializer)) {
201
+ const awaitedExpr = initializer.expression;
202
+ if (ts.isCallExpression(awaitedExpr)) {
203
+ const callExpr = awaitedExpr.expression;
204
+ // Promise.all(...)
205
+ if (ts.isPropertyAccessExpression(callExpr) && callExpr.name.text === 'all') {
206
+ const obj = callExpr.expression;
207
+ if (ts.isIdentifier(obj) && obj.text === 'Promise') {
208
+ return true;
209
+ }
210
+ }
211
+ }
212
+ }
213
+
214
+ return false;
215
+ }
216
+
217
+ /**
218
+ * Check if an ArrayBindingPattern in a for-of loop iterates over Object.entries(...).
219
+ */
220
+ function isObjectEntriesForOf(node: ts.ArrayBindingPattern): boolean {
221
+ // Walk up: ArrayBindingPattern -> VariableDeclaration -> VariableDeclarationList -> ForOfStatement
222
+ const varDecl = node.parent;
223
+ if (!ts.isVariableDeclaration(varDecl)) return false;
224
+
225
+ const varDeclList = varDecl.parent;
226
+ if (!ts.isVariableDeclarationList(varDeclList)) return false;
227
+
228
+ const forOfStmt = varDeclList.parent;
229
+ if (!ts.isForOfStatement(forOfStmt)) return false;
230
+
231
+ // Check iterable expression ends with .entries()
232
+ const iterable = forOfStmt.expression;
233
+ if (ts.isCallExpression(iterable)) {
234
+ const callExpr = iterable.expression;
235
+ if (ts.isPropertyAccessExpression(callExpr) && callExpr.name.text === 'entries') {
236
+ return true;
237
+ }
238
+ }
239
+
240
+ return false;
241
+ }
242
+
243
+ /**
244
+ * Check if an ObjectBindingPattern contains a rest element (...rest).
245
+ */
246
+ function hasRestElement(node: ts.ObjectBindingPattern): boolean {
247
+ for (const element of node.elements) {
248
+ if (element.dotDotDotToken) {
249
+ return true;
250
+ }
251
+ }
252
+ return false;
253
+ }
254
+
255
+ interface DestructureInfo {
256
+ line: number;
257
+ column: number;
258
+ context: string;
259
+ hasDisableComment: boolean;
260
+ }
261
+
262
+ /**
263
+ * Find all destructuring patterns in a file using AST.
264
+ */
265
+ // webpieces-disable max-lines-new-methods -- AST traversal with multiple destructuring pattern checks and exception detection
266
+ function findDestructuringInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean): DestructureInfo[] {
267
+ const fullPath = path.join(workspaceRoot, filePath);
268
+ if (!fs.existsSync(fullPath)) return [];
269
+
270
+ const content = fs.readFileSync(fullPath, 'utf-8');
271
+ const fileLines = content.split('\n');
272
+ const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
273
+
274
+ const violations: DestructureInfo[] = [];
275
+
276
+ // webpieces-disable max-lines-new-methods -- AST visitor needs to handle object/array binding patterns in declarations, for-of, and parameters
277
+ function visit(node: ts.Node): void {
278
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
279
+ try {
280
+ // Check ObjectBindingPattern
281
+ if (ts.isObjectBindingPattern(node)) {
282
+ // Exception: rest operator separation
283
+ if (hasRestElement(node)) {
284
+ ts.forEachChild(node, visit);
285
+ return;
286
+ }
287
+
288
+ const context = getDestructureContext(node);
289
+ recordViolation(node, context, fileLines, sourceFile, violations, disableAllowed);
290
+ }
291
+
292
+ // Check ArrayBindingPattern
293
+ if (ts.isArrayBindingPattern(node)) {
294
+ // Exception: Promise.all destructure
295
+ if (isPromiseAllDestructure(node)) {
296
+ ts.forEachChild(node, visit);
297
+ return;
298
+ }
299
+
300
+ // Exception: Object.entries in for-of
301
+ if (isObjectEntriesForOf(node)) {
302
+ ts.forEachChild(node, visit);
303
+ return;
304
+ }
305
+
306
+ const context = getDestructureContext(node);
307
+ recordViolation(node, context, fileLines, sourceFile, violations, disableAllowed);
308
+ }
309
+ } catch (err: unknown) {
310
+ //const error = toError(err);
311
+ // Skip nodes that cause errors during analysis
312
+ }
313
+
314
+ ts.forEachChild(node, visit);
315
+ }
316
+
317
+ visit(sourceFile);
318
+ return violations;
319
+ }
320
+
321
+ function recordViolation(
322
+ node: ts.Node,
323
+ context: string,
324
+ fileLines: string[],
325
+ sourceFile: ts.SourceFile,
326
+ violations: DestructureInfo[],
327
+ disableAllowed: boolean,
328
+ ): void {
329
+ const startPos = node.getStart(sourceFile);
330
+ if (startPos >= 0) {
331
+ const pos = sourceFile.getLineAndCharacterOfPosition(startPos);
332
+ const line = pos.line + 1;
333
+ const column = pos.character + 1;
334
+ const disabled = hasDisableComment(fileLines, line);
335
+
336
+ if (!disableAllowed && disabled) {
337
+ // When disableAllowed is false, ignore disable comments — still a violation
338
+ violations.push({ line, column, context, hasDisableComment: false });
339
+ } else {
340
+ violations.push({ line, column, context, hasDisableComment: disabled });
341
+ }
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Get a description of where the destructuring pattern appears.
347
+ */
348
+ function getDestructureContext(node: ts.Node): string {
349
+ const parent = node.parent;
350
+ if (ts.isParameter(parent)) {
351
+ return 'function parameter destructuring';
352
+ }
353
+ if (ts.isVariableDeclaration(parent)) {
354
+ const grandparent = parent.parent;
355
+ if (grandparent && ts.isVariableDeclarationList(grandparent)) {
356
+ const forOfParent = grandparent.parent;
357
+ if (forOfParent && ts.isForOfStatement(forOfParent)) {
358
+ return ts.isObjectBindingPattern(node)
359
+ ? 'object destructuring in for-of loop'
360
+ : 'array destructuring in for-of loop';
361
+ }
362
+ }
363
+ return ts.isObjectBindingPattern(node)
364
+ ? 'object destructuring in variable declaration'
365
+ : 'array destructuring in variable declaration';
366
+ }
367
+ return ts.isObjectBindingPattern(node)
368
+ ? 'object destructuring'
369
+ : 'array destructuring';
370
+ }
371
+
372
+ /**
373
+ * MODIFIED_CODE mode: Flag violations on changed lines in diff hunks.
374
+ */
375
+ // webpieces-disable max-lines-new-methods -- File iteration with diff parsing and line filtering
376
+ function findViolationsForModifiedCode(
377
+ workspaceRoot: string,
378
+ changedFiles: string[],
379
+ base: string,
380
+ head: string | undefined,
381
+ disableAllowed: boolean
382
+ ): DestructureViolation[] {
383
+ const violations: DestructureViolation[] = [];
384
+
385
+ for (const file of changedFiles) {
386
+ const diff = getFileDiff(workspaceRoot, file, base, head);
387
+ const changedLines = getChangedLineNumbers(diff);
388
+
389
+ if (changedLines.size === 0) continue;
390
+
391
+ const allViolations = findDestructuringInFile(file, workspaceRoot, disableAllowed);
392
+
393
+ for (const v of allViolations) {
394
+ if (disableAllowed && v.hasDisableComment) continue;
395
+ // LINE-BASED: Only include if the violation is on a changed line
396
+ if (!changedLines.has(v.line)) continue;
397
+
398
+ violations.push({
399
+ file,
400
+ line: v.line,
401
+ column: v.column,
402
+ context: v.context,
403
+ });
404
+ }
405
+ }
406
+
407
+ return violations;
408
+ }
409
+
410
+ /**
411
+ * MODIFIED_FILES mode: Flag ALL violations in files that were modified.
412
+ */
413
+ function findViolationsForModifiedFiles(workspaceRoot: string, changedFiles: string[], disableAllowed: boolean): DestructureViolation[] {
414
+ const violations: DestructureViolation[] = [];
415
+
416
+ for (const file of changedFiles) {
417
+ const allViolations = findDestructuringInFile(file, workspaceRoot, disableAllowed);
418
+
419
+ for (const v of allViolations) {
420
+ if (disableAllowed && v.hasDisableComment) continue;
421
+
422
+ violations.push({
423
+ file,
424
+ line: v.line,
425
+ column: v.column,
426
+ context: v.context,
427
+ });
428
+ }
429
+ }
430
+
431
+ return violations;
432
+ }
433
+
434
+ /**
435
+ * Auto-detect the base branch by finding the merge-base with origin/main.
436
+ */
437
+ function detectBase(workspaceRoot: string): string | null {
438
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
439
+ try {
440
+ const mergeBase = execSync('git merge-base HEAD origin/main', {
441
+ cwd: workspaceRoot,
442
+ encoding: 'utf-8',
443
+ stdio: ['pipe', 'pipe', 'pipe'],
444
+ }).trim();
445
+
446
+ if (mergeBase) {
447
+ return mergeBase;
448
+ }
449
+ } catch (err: unknown) {
450
+ //const error = toError(err);
451
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
452
+ try {
453
+ const mergeBase = execSync('git merge-base HEAD main', {
454
+ cwd: workspaceRoot,
455
+ encoding: 'utf-8',
456
+ stdio: ['pipe', 'pipe', 'pipe'],
457
+ }).trim();
458
+
459
+ if (mergeBase) {
460
+ return mergeBase;
461
+ }
462
+ } catch (err2: unknown) {
463
+ //const error2 = toError(err2);
464
+ // Ignore
465
+ }
466
+ }
467
+ return null;
468
+ }
469
+
470
+ /**
471
+ * Report violations to console.
472
+ */
473
+ // webpieces-disable max-lines-new-methods -- Console output with examples and escape hatch information
474
+ function reportViolations(violations: DestructureViolation[], mode: NoDestructureMode, disableAllowed: boolean): void {
475
+ console.error('');
476
+ console.error('\u274c Destructuring patterns found! Use explicit property access instead.');
477
+ console.error('');
478
+ console.error('\ud83d\udcda Avoiding destructuring improves code traceability:');
479
+ console.error('');
480
+ console.error(' BAD: const { name, age } = user;');
481
+ console.error(' GOOD: const name = user.name;');
482
+ console.error(' const age = user.age;');
483
+ console.error('');
484
+ console.error(' BAD: function process({ x, y }: Point) { }');
485
+ console.error(' GOOD: function process(point: Point) { point.x; point.y; }');
486
+ console.error('');
487
+
488
+ for (const v of violations) {
489
+ console.error(` \u274c ${v.file}:${v.line}:${v.column}`);
490
+ console.error(` ${v.context}`);
491
+ }
492
+ console.error('');
493
+
494
+ console.error(' Allowed exceptions:');
495
+ console.error(' - const [a, b] = await Promise.all([...])');
496
+ console.error(' - for (const [key, value] of Object.entries(obj))');
497
+ console.error(' - const { extracted, ...rest } = obj (rest operator separation)');
498
+ console.error('');
499
+
500
+ if (disableAllowed) {
501
+ console.error(' Escape hatch (use sparingly):');
502
+ console.error(' // webpieces-disable no-destructure -- [your reason]');
503
+ } else {
504
+ console.error(' Escape hatch: DISABLED (disableAllowed: false)');
505
+ console.error(' Disable comments are ignored. Fix the destructuring directly.');
506
+ }
507
+ console.error('');
508
+ console.error(` Current mode: ${mode}`);
509
+ console.error('');
510
+ }
511
+
512
+ /**
513
+ * Resolve mode considering ignoreModifiedUntilEpoch override.
514
+ * When active, downgrades to OFF. When expired, logs a warning.
515
+ */
516
+ function resolveNoDestructureMode(normalMode: NoDestructureMode, epoch: number | undefined): NoDestructureMode {
517
+ if (epoch === undefined || normalMode === 'OFF') {
518
+ return normalMode;
519
+ }
520
+ const nowSeconds = Date.now() / 1000;
521
+ if (nowSeconds < epoch) {
522
+ const expiresDate = new Date(epoch * 1000).toISOString().split('T')[0];
523
+ console.log(`\n\u23ed\ufe0f Skipping no-destructure validation (ignoreModifiedUntilEpoch active, expires: ${expiresDate})`);
524
+ console.log('');
525
+ return 'OFF';
526
+ }
527
+ return normalMode;
528
+ }
529
+
530
+ export default async function runValidator(
531
+ options: ValidateNoDestructureOptions,
532
+ workspaceRoot: string
533
+ ): Promise<ExecutorResult> {
534
+ const mode: NoDestructureMode = resolveNoDestructureMode(options.mode ?? 'OFF', options.ignoreModifiedUntilEpoch);
535
+ const disableAllowed = options.disableAllowed ?? true;
536
+
537
+ if (mode === 'OFF') {
538
+ console.log('\n\u23ed\ufe0f Skipping no-destructure validation (mode: OFF)');
539
+ console.log('');
540
+ return { success: true };
541
+ }
542
+
543
+ console.log('\n\ud83d\udccf Validating No Destructuring\n');
544
+ console.log(` Mode: ${mode}`);
545
+
546
+ let base = process.env['NX_BASE'];
547
+ const head = process.env['NX_HEAD'];
548
+
549
+ if (!base) {
550
+ base = detectBase(workspaceRoot) ?? undefined;
551
+
552
+ if (!base) {
553
+ console.log('\n\u23ed\ufe0f Skipping no-destructure validation (could not detect base branch)');
554
+ console.log('');
555
+ return { success: true };
556
+ }
557
+ }
558
+
559
+ console.log(` Base: ${base}`);
560
+ console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);
561
+ console.log('');
562
+
563
+ const changedFiles = getChangedTypeScriptFiles(workspaceRoot, base, head);
564
+
565
+ if (changedFiles.length === 0) {
566
+ console.log('\u2705 No TypeScript files changed');
567
+ return { success: true };
568
+ }
569
+
570
+ console.log(`\ud83d\udcc2 Checking ${changedFiles.length} changed file(s)...`);
571
+
572
+ let violations: DestructureViolation[] = [];
573
+
574
+ if (mode === 'MODIFIED_CODE') {
575
+ violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);
576
+ } else if (mode === 'MODIFIED_FILES') {
577
+ violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);
578
+ }
579
+
580
+ if (violations.length === 0) {
581
+ console.log('\u2705 No destructuring patterns found');
582
+ return { success: true };
583
+ }
584
+
585
+ reportViolations(violations, mode, disableAllowed);
586
+
587
+ return { success: false };
588
+ }