@webpieces/dev-config 0.2.83 → 0.2.85

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