@webpieces/dev-config 0.2.79 → 0.2.81
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.
- package/architecture/executors/validate-code/executor.d.ts +7 -0
- package/architecture/executors/validate-code/executor.js +13 -2
- package/architecture/executors/validate-code/executor.js.map +1 -1
- package/architecture/executors/validate-code/executor.ts +23 -2
- package/architecture/executors/validate-code/schema.json +21 -0
- package/architecture/executors/validate-dtos/executor.d.ts +40 -0
- package/architecture/executors/validate-dtos/executor.js +486 -0
- package/architecture/executors/validate-dtos/executor.js.map +1 -0
- package/architecture/executors/validate-dtos/executor.ts +606 -0
- package/architecture/executors/validate-dtos/schema.json +24 -0
- package/executors.json +5 -0
- package/package.json +1 -1
|
@@ -0,0 +1,606 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validate DTOs Executor
|
|
3
|
+
*
|
|
4
|
+
* Validates that every non-deprecated field in a XxxDto class/interface exists
|
|
5
|
+
* in the corresponding XxxDbo Prisma model. This catches AI agents inventing
|
|
6
|
+
* field names that don't match the database schema.
|
|
7
|
+
*
|
|
8
|
+
* ============================================================================
|
|
9
|
+
* MODES
|
|
10
|
+
* ============================================================================
|
|
11
|
+
* - OFF: Skip validation entirely
|
|
12
|
+
* - MODIFIED_CLASS: Only validate Dto classes that have changed lines in the diff
|
|
13
|
+
* - MODIFIED_FILES: Validate ALL Dto classes in files that were modified
|
|
14
|
+
*
|
|
15
|
+
* ============================================================================
|
|
16
|
+
* SKIP CONDITIONS
|
|
17
|
+
* ============================================================================
|
|
18
|
+
* - If schema.prisma itself is modified, validation is skipped (schema in flux)
|
|
19
|
+
* - Dto classes ending with "JoinDto" are skipped (they compose other Dtos)
|
|
20
|
+
* - Fields marked @deprecated in a comment are exempt
|
|
21
|
+
*
|
|
22
|
+
* ============================================================================
|
|
23
|
+
* MATCHING
|
|
24
|
+
* ============================================================================
|
|
25
|
+
* - UserDto matches UserDbo by case-insensitive prefix ("user")
|
|
26
|
+
* - Dbo field names are converted from snake_case to camelCase for comparison
|
|
27
|
+
* - Dto fields must be a subset of Dbo fields
|
|
28
|
+
* - Extra Dbo fields are allowed (e.g., password)
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import type { ExecutorContext } from '@nx/devkit';
|
|
32
|
+
import { execSync } from 'child_process';
|
|
33
|
+
import * as fs from 'fs';
|
|
34
|
+
import * as path from 'path';
|
|
35
|
+
import * as ts from 'typescript';
|
|
36
|
+
|
|
37
|
+
export type ValidateDtosMode = 'OFF' | 'MODIFIED_CLASS' | 'MODIFIED_FILES';
|
|
38
|
+
|
|
39
|
+
export interface ValidateDtosOptions {
|
|
40
|
+
mode?: ValidateDtosMode;
|
|
41
|
+
prismaSchemaPath?: string;
|
|
42
|
+
dtoSourcePaths?: string[];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface ExecutorResult {
|
|
46
|
+
success: boolean;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
interface DtoFieldInfo {
|
|
50
|
+
name: string;
|
|
51
|
+
line: number;
|
|
52
|
+
deprecated: boolean;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
interface DtoInfo {
|
|
56
|
+
name: string;
|
|
57
|
+
file: string;
|
|
58
|
+
startLine: number;
|
|
59
|
+
endLine: number;
|
|
60
|
+
fields: DtoFieldInfo[];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface DtoViolation {
|
|
64
|
+
file: string;
|
|
65
|
+
line: number;
|
|
66
|
+
dtoName: string;
|
|
67
|
+
fieldName: string;
|
|
68
|
+
dboName: string;
|
|
69
|
+
availableFields: string[];
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
interface DboEntry {
|
|
73
|
+
name: string;
|
|
74
|
+
fields: Set<string>;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Auto-detect the base branch by finding the merge-base with origin/main.
|
|
79
|
+
*/
|
|
80
|
+
function detectBase(workspaceRoot: string): string | null {
|
|
81
|
+
try {
|
|
82
|
+
const mergeBase = execSync('git merge-base HEAD origin/main', {
|
|
83
|
+
cwd: workspaceRoot,
|
|
84
|
+
encoding: 'utf-8',
|
|
85
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
86
|
+
}).trim();
|
|
87
|
+
|
|
88
|
+
if (mergeBase) {
|
|
89
|
+
return mergeBase;
|
|
90
|
+
}
|
|
91
|
+
} catch {
|
|
92
|
+
try {
|
|
93
|
+
const mergeBase = execSync('git merge-base HEAD main', {
|
|
94
|
+
cwd: workspaceRoot,
|
|
95
|
+
encoding: 'utf-8',
|
|
96
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
97
|
+
}).trim();
|
|
98
|
+
|
|
99
|
+
if (mergeBase) {
|
|
100
|
+
return mergeBase;
|
|
101
|
+
}
|
|
102
|
+
} catch {
|
|
103
|
+
// Ignore
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Get changed files between base and head (or working tree if head not specified).
|
|
111
|
+
*/
|
|
112
|
+
// webpieces-disable max-lines-new-methods -- Git command handling with untracked files requires multiple code paths
|
|
113
|
+
function getChangedFiles(workspaceRoot: string, base: string, head?: string): string[] {
|
|
114
|
+
try {
|
|
115
|
+
const diffTarget = head ? `${base} ${head}` : base;
|
|
116
|
+
const output = execSync(`git diff --name-only ${diffTarget}`, {
|
|
117
|
+
cwd: workspaceRoot,
|
|
118
|
+
encoding: 'utf-8',
|
|
119
|
+
});
|
|
120
|
+
const changedFiles = output
|
|
121
|
+
.trim()
|
|
122
|
+
.split('\n')
|
|
123
|
+
.filter((f) => f.length > 0);
|
|
124
|
+
|
|
125
|
+
if (!head) {
|
|
126
|
+
try {
|
|
127
|
+
const untrackedOutput = execSync('git ls-files --others --exclude-standard', {
|
|
128
|
+
cwd: workspaceRoot,
|
|
129
|
+
encoding: 'utf-8',
|
|
130
|
+
});
|
|
131
|
+
const untrackedFiles = untrackedOutput
|
|
132
|
+
.trim()
|
|
133
|
+
.split('\n')
|
|
134
|
+
.filter((f) => f.length > 0);
|
|
135
|
+
const allFiles = new Set([...changedFiles, ...untrackedFiles]);
|
|
136
|
+
return Array.from(allFiles);
|
|
137
|
+
} catch {
|
|
138
|
+
return changedFiles;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return changedFiles;
|
|
143
|
+
} catch {
|
|
144
|
+
return [];
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Get the diff content for a specific file.
|
|
150
|
+
*/
|
|
151
|
+
function getFileDiff(workspaceRoot: string, file: string, base: string, head?: string): string {
|
|
152
|
+
try {
|
|
153
|
+
const diffTarget = head ? `${base} ${head}` : base;
|
|
154
|
+
const diff = execSync(`git diff ${diffTarget} -- "${file}"`, {
|
|
155
|
+
cwd: workspaceRoot,
|
|
156
|
+
encoding: 'utf-8',
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
if (!diff && !head) {
|
|
160
|
+
const fullPath = path.join(workspaceRoot, file);
|
|
161
|
+
if (fs.existsSync(fullPath)) {
|
|
162
|
+
const isUntracked = execSync(`git ls-files --others --exclude-standard "${file}"`, {
|
|
163
|
+
cwd: workspaceRoot,
|
|
164
|
+
encoding: 'utf-8',
|
|
165
|
+
}).trim();
|
|
166
|
+
|
|
167
|
+
if (isUntracked) {
|
|
168
|
+
const content = fs.readFileSync(fullPath, 'utf-8');
|
|
169
|
+
const lines = content.split('\n');
|
|
170
|
+
return lines.map((line) => `+${line}`).join('\n');
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return diff;
|
|
176
|
+
} catch {
|
|
177
|
+
return '';
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Parse diff to extract changed line numbers (additions only - lines starting with +).
|
|
183
|
+
*/
|
|
184
|
+
function getChangedLineNumbers(diffContent: string): Set<number> {
|
|
185
|
+
const changedLines = new Set<number>();
|
|
186
|
+
const lines = diffContent.split('\n');
|
|
187
|
+
let currentLine = 0;
|
|
188
|
+
|
|
189
|
+
for (const line of lines) {
|
|
190
|
+
const hunkMatch = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
|
|
191
|
+
if (hunkMatch) {
|
|
192
|
+
currentLine = parseInt(hunkMatch[1], 10);
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (line.startsWith('+') && !line.startsWith('+++')) {
|
|
197
|
+
changedLines.add(currentLine);
|
|
198
|
+
currentLine++;
|
|
199
|
+
} else if (line.startsWith('-') && !line.startsWith('---')) {
|
|
200
|
+
// Deletions don't increment line number
|
|
201
|
+
} else {
|
|
202
|
+
currentLine++;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return changedLines;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Convert a snake_case string to camelCase.
|
|
211
|
+
* e.g., "version_number" -> "versionNumber", "id" -> "id"
|
|
212
|
+
*/
|
|
213
|
+
function snakeToCamel(s: string): string {
|
|
214
|
+
return s.replace(/_([a-z])/g, (_, letter: string) => letter.toUpperCase());
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Parse schema.prisma to build a map of Dbo model name -> set of field names (camelCase).
|
|
219
|
+
* Only models whose name ends with "Dbo" are included.
|
|
220
|
+
* Field names are converted from snake_case to camelCase since Dto fields use camelCase.
|
|
221
|
+
*/
|
|
222
|
+
function parsePrismaSchema(schemaPath: string): Map<string, Set<string>> {
|
|
223
|
+
const models = new Map<string, Set<string>>();
|
|
224
|
+
|
|
225
|
+
if (!fs.existsSync(schemaPath)) {
|
|
226
|
+
return models;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const content = fs.readFileSync(schemaPath, 'utf-8');
|
|
230
|
+
const lines = content.split('\n');
|
|
231
|
+
|
|
232
|
+
let currentModel: string | null = null;
|
|
233
|
+
let currentFields: Set<string> | null = null;
|
|
234
|
+
|
|
235
|
+
for (const line of lines) {
|
|
236
|
+
const trimmed = line.trim();
|
|
237
|
+
|
|
238
|
+
// Match model declaration: model XxxDbo {
|
|
239
|
+
const modelMatch = trimmed.match(/^model\s+(\w+Dbo)\s*\{/);
|
|
240
|
+
if (modelMatch) {
|
|
241
|
+
currentModel = modelMatch[1];
|
|
242
|
+
currentFields = new Set<string>();
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// End of model block
|
|
247
|
+
if (currentModel && trimmed === '}') {
|
|
248
|
+
models.set(currentModel, currentFields!);
|
|
249
|
+
currentModel = null;
|
|
250
|
+
currentFields = null;
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// Inside a model block - extract field names
|
|
255
|
+
if (currentModel && currentFields) {
|
|
256
|
+
// Skip empty lines, comments, and model-level attributes (@@)
|
|
257
|
+
if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('@@')) {
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Field name is the first word on the line, converted to camelCase
|
|
262
|
+
const fieldMatch = trimmed.match(/^(\w+)\s/);
|
|
263
|
+
if (fieldMatch) {
|
|
264
|
+
currentFields.add(snakeToCamel(fieldMatch[1]));
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
return models;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Check if a field has @deprecated in a comment above it (within 3 lines).
|
|
274
|
+
*/
|
|
275
|
+
function isFieldDeprecated(fileLines: string[], fieldLine: number): boolean {
|
|
276
|
+
const start = Math.max(0, fieldLine - 4);
|
|
277
|
+
for (let i = start; i <= fieldLine - 1; i++) {
|
|
278
|
+
const line = fileLines[i]?.trim() ?? '';
|
|
279
|
+
if (line.includes('@deprecated')) return true;
|
|
280
|
+
}
|
|
281
|
+
return false;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Parse a TypeScript file to find Dto class/interface declarations and their fields.
|
|
286
|
+
* Skips classes ending with "JoinDto" since they compose other Dtos.
|
|
287
|
+
*/
|
|
288
|
+
// webpieces-disable max-lines-new-methods -- AST traversal for both class and interface Dto detection with field extraction
|
|
289
|
+
function findDtosInFile(filePath: string, workspaceRoot: string): DtoInfo[] {
|
|
290
|
+
const fullPath = path.join(workspaceRoot, filePath);
|
|
291
|
+
if (!fs.existsSync(fullPath)) return [];
|
|
292
|
+
|
|
293
|
+
const content = fs.readFileSync(fullPath, 'utf-8');
|
|
294
|
+
const fileLines = content.split('\n');
|
|
295
|
+
const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
|
|
296
|
+
|
|
297
|
+
const dtos: DtoInfo[] = [];
|
|
298
|
+
|
|
299
|
+
function visit(node: ts.Node): void {
|
|
300
|
+
const isClass = ts.isClassDeclaration(node);
|
|
301
|
+
const isInterface = ts.isInterfaceDeclaration(node);
|
|
302
|
+
|
|
303
|
+
if ((isClass || isInterface) && node.name) {
|
|
304
|
+
const name = node.name.text;
|
|
305
|
+
|
|
306
|
+
// Must end with Dto but NOT with JoinDto
|
|
307
|
+
if (name.endsWith('Dto') && !name.endsWith('JoinDto')) {
|
|
308
|
+
const fields: DtoFieldInfo[] = [];
|
|
309
|
+
const nodeStart = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));
|
|
310
|
+
const nodeEnd = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
|
|
311
|
+
|
|
312
|
+
for (const member of node.members) {
|
|
313
|
+
if (ts.isPropertyDeclaration(member) || ts.isPropertySignature(member)) {
|
|
314
|
+
if (member.name && ts.isIdentifier(member.name)) {
|
|
315
|
+
const fieldName = member.name.text;
|
|
316
|
+
const startPos = member.getStart(sourceFile);
|
|
317
|
+
const pos = sourceFile.getLineAndCharacterOfPosition(startPos);
|
|
318
|
+
const line = pos.line + 1;
|
|
319
|
+
const deprecated = isFieldDeprecated(fileLines, line);
|
|
320
|
+
|
|
321
|
+
fields.push({ name: fieldName, line, deprecated });
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
dtos.push({
|
|
327
|
+
name,
|
|
328
|
+
file: filePath,
|
|
329
|
+
startLine: nodeStart.line + 1,
|
|
330
|
+
endLine: nodeEnd.line + 1,
|
|
331
|
+
fields,
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
ts.forEachChild(node, visit);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
visit(sourceFile);
|
|
340
|
+
return dtos;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Extract the prefix from a Dto/Dbo name by removing the suffix.
|
|
345
|
+
* e.g., "UserDto" -> "user", "UserDbo" -> "user"
|
|
346
|
+
*/
|
|
347
|
+
function extractPrefix(name: string, suffix: string): string {
|
|
348
|
+
return name.slice(0, -suffix.length).toLowerCase();
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Find violations: Dto fields that don't exist in the corresponding Dbo.
|
|
353
|
+
*/
|
|
354
|
+
function findViolations(
|
|
355
|
+
dtos: DtoInfo[],
|
|
356
|
+
dboModels: Map<string, Set<string>>
|
|
357
|
+
): DtoViolation[] {
|
|
358
|
+
const violations: DtoViolation[] = [];
|
|
359
|
+
|
|
360
|
+
// Build a lowercase prefix -> Dbo info map
|
|
361
|
+
const dboByPrefix = new Map<string, DboEntry>();
|
|
362
|
+
for (const [dboName, fields] of dboModels) {
|
|
363
|
+
const prefix = extractPrefix(dboName, 'Dbo');
|
|
364
|
+
dboByPrefix.set(prefix, { name: dboName, fields });
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
for (const dto of dtos) {
|
|
368
|
+
const prefix = extractPrefix(dto.name, 'Dto');
|
|
369
|
+
const dbo = dboByPrefix.get(prefix);
|
|
370
|
+
|
|
371
|
+
if (!dbo) {
|
|
372
|
+
// No matching Dbo found - skip (might be a Dto without a DB table)
|
|
373
|
+
continue;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
for (const field of dto.fields) {
|
|
377
|
+
if (field.deprecated) continue;
|
|
378
|
+
|
|
379
|
+
if (!dbo.fields.has(field.name)) {
|
|
380
|
+
violations.push({
|
|
381
|
+
file: dto.file,
|
|
382
|
+
line: field.line,
|
|
383
|
+
dtoName: dto.name,
|
|
384
|
+
fieldName: field.name,
|
|
385
|
+
dboName: dbo.name,
|
|
386
|
+
availableFields: Array.from(dbo.fields).sort(),
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
return violations;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Report violations to console.
|
|
397
|
+
*/
|
|
398
|
+
function reportViolations(violations: DtoViolation[]): void {
|
|
399
|
+
console.error('');
|
|
400
|
+
console.error('❌ DTO fields don\'t match Prisma Dbo models!');
|
|
401
|
+
console.error('');
|
|
402
|
+
console.error('📚 Every non-deprecated field in a Dto must exist in the corresponding Dbo.');
|
|
403
|
+
console.error(' This prevents AI from inventing field names that don\'t match the database schema.');
|
|
404
|
+
console.error(' Dbo can have extra fields (e.g., password) - Dto cannot.');
|
|
405
|
+
console.error('');
|
|
406
|
+
|
|
407
|
+
for (const v of violations) {
|
|
408
|
+
console.error(` ❌ ${v.file}:${v.line}`);
|
|
409
|
+
console.error(` ${v.dtoName}.${v.fieldName} does not exist in ${v.dboName}`);
|
|
410
|
+
console.error(` Available Dbo fields: ${v.availableFields.join(', ')}`);
|
|
411
|
+
}
|
|
412
|
+
console.error('');
|
|
413
|
+
|
|
414
|
+
console.error(' Dto fields must be a subset of Dbo fields (matching camelCase field names).');
|
|
415
|
+
console.error(' Fields marked @deprecated in the Dto are exempt from this check.');
|
|
416
|
+
console.error('');
|
|
417
|
+
console.error(' When needing fields from multiple tables (e.g., a join), use a XxxJoinDto that');
|
|
418
|
+
console.error(' contains YYDto and ZZDto fields from the other tables instead of flattening.');
|
|
419
|
+
console.error('');
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Filter changed files to only TypeScript Dto source files within configured paths.
|
|
424
|
+
*/
|
|
425
|
+
function filterDtoFiles(changedFiles: string[], dtoSourcePaths: string[]): string[] {
|
|
426
|
+
return changedFiles.filter((f) => {
|
|
427
|
+
if (!f.endsWith('.ts') && !f.endsWith('.tsx')) return false;
|
|
428
|
+
if (f.includes('.spec.ts') || f.includes('.test.ts')) return false;
|
|
429
|
+
return dtoSourcePaths.some((srcPath) => f.startsWith(srcPath));
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Collect all Dto definitions from the given files.
|
|
435
|
+
*/
|
|
436
|
+
function collectDtos(dtoFiles: string[], workspaceRoot: string): DtoInfo[] {
|
|
437
|
+
const allDtos: DtoInfo[] = [];
|
|
438
|
+
for (const file of dtoFiles) {
|
|
439
|
+
const dtos = findDtosInFile(file, workspaceRoot);
|
|
440
|
+
allDtos.push(...dtos);
|
|
441
|
+
}
|
|
442
|
+
return allDtos;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Check if a Dto class overlaps with any changed lines in the diff.
|
|
447
|
+
*/
|
|
448
|
+
function isDtoTouched(dto: DtoInfo, changedLines: Set<number>): boolean {
|
|
449
|
+
for (let line = dto.startLine; line <= dto.endLine; line++) {
|
|
450
|
+
if (changedLines.has(line)) return true;
|
|
451
|
+
}
|
|
452
|
+
return false;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Filter Dtos to only those that have changed lines in the diff (MODIFIED_CLASS mode).
|
|
457
|
+
*/
|
|
458
|
+
function filterTouchedDtos(
|
|
459
|
+
dtos: DtoInfo[],
|
|
460
|
+
workspaceRoot: string,
|
|
461
|
+
base: string,
|
|
462
|
+
head?: string
|
|
463
|
+
): DtoInfo[] {
|
|
464
|
+
// Group dtos by file to avoid re-fetching diffs
|
|
465
|
+
const byFile = new Map<string, DtoInfo[]>();
|
|
466
|
+
for (const dto of dtos) {
|
|
467
|
+
const list = byFile.get(dto.file) ?? [];
|
|
468
|
+
list.push(dto);
|
|
469
|
+
byFile.set(dto.file, list);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
const touched: DtoInfo[] = [];
|
|
473
|
+
for (const [file, fileDtos] of byFile) {
|
|
474
|
+
const diff = getFileDiff(workspaceRoot, file, base, head);
|
|
475
|
+
const changedLines = getChangedLineNumbers(diff);
|
|
476
|
+
for (const dto of fileDtos) {
|
|
477
|
+
if (isDtoTouched(dto, changedLines)) {
|
|
478
|
+
touched.push(dto);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
return touched;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Resolve git base ref from env vars or auto-detection.
|
|
487
|
+
*/
|
|
488
|
+
function resolveBase(workspaceRoot: string): string | undefined {
|
|
489
|
+
const envBase = process.env['NX_BASE'];
|
|
490
|
+
if (envBase) return envBase;
|
|
491
|
+
return detectBase(workspaceRoot) ?? undefined;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* Run the core validation after early-exit checks have passed.
|
|
496
|
+
*/
|
|
497
|
+
// webpieces-disable max-lines-new-methods -- Core validation orchestration with multiple early-exit checks
|
|
498
|
+
function validateDtoFiles(
|
|
499
|
+
workspaceRoot: string,
|
|
500
|
+
prismaSchemaPath: string,
|
|
501
|
+
changedFiles: string[],
|
|
502
|
+
dtoSourcePaths: string[],
|
|
503
|
+
mode: ValidateDtosMode,
|
|
504
|
+
base: string,
|
|
505
|
+
head?: string
|
|
506
|
+
): ExecutorResult {
|
|
507
|
+
if (changedFiles.some((f) => f.endsWith(prismaSchemaPath))) {
|
|
508
|
+
console.log('⏭️ Skipping validate-dtos (schema.prisma is modified - schema in flux)');
|
|
509
|
+
console.log('');
|
|
510
|
+
return { success: true };
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
const dtoFiles = filterDtoFiles(changedFiles, dtoSourcePaths);
|
|
514
|
+
|
|
515
|
+
if (dtoFiles.length === 0) {
|
|
516
|
+
console.log('✅ No Dto files changed');
|
|
517
|
+
return { success: true };
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
console.log(`📂 Checking ${dtoFiles.length} changed file(s) for Dto definitions...`);
|
|
521
|
+
|
|
522
|
+
const fullSchemaPath = path.join(workspaceRoot, prismaSchemaPath);
|
|
523
|
+
const dboModels = parsePrismaSchema(fullSchemaPath);
|
|
524
|
+
|
|
525
|
+
if (dboModels.size === 0) {
|
|
526
|
+
console.log('⏭️ No Dbo models found in schema.prisma');
|
|
527
|
+
console.log('');
|
|
528
|
+
return { success: true };
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
console.log(` Found ${dboModels.size} Dbo model(s) in schema.prisma`);
|
|
532
|
+
|
|
533
|
+
let allDtos = collectDtos(dtoFiles, workspaceRoot);
|
|
534
|
+
|
|
535
|
+
if (allDtos.length === 0) {
|
|
536
|
+
console.log('✅ No Dto definitions found in changed files');
|
|
537
|
+
return { success: true };
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// In MODIFIED_CLASS mode, narrow to only Dtos with changed lines
|
|
541
|
+
if (mode === 'MODIFIED_CLASS') {
|
|
542
|
+
allDtos = filterTouchedDtos(allDtos, workspaceRoot, base, head);
|
|
543
|
+
if (allDtos.length === 0) {
|
|
544
|
+
console.log('✅ No Dto classes were modified');
|
|
545
|
+
return { success: true };
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
console.log(` Validating ${allDtos.length} Dto definition(s)`);
|
|
550
|
+
|
|
551
|
+
const violations = findViolations(allDtos, dboModels);
|
|
552
|
+
|
|
553
|
+
if (violations.length === 0) {
|
|
554
|
+
console.log('✅ All Dto fields match their Dbo models');
|
|
555
|
+
return { success: true };
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
reportViolations(violations);
|
|
559
|
+
return { success: false };
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
export default async function runExecutor(
|
|
563
|
+
options: ValidateDtosOptions,
|
|
564
|
+
context: ExecutorContext
|
|
565
|
+
): Promise<ExecutorResult> {
|
|
566
|
+
const workspaceRoot = context.root;
|
|
567
|
+
const mode: ValidateDtosMode = options.mode ?? 'OFF';
|
|
568
|
+
|
|
569
|
+
if (mode === 'OFF') {
|
|
570
|
+
console.log('\n⏭️ Skipping validate-dtos (mode: OFF)');
|
|
571
|
+
console.log('');
|
|
572
|
+
return { success: true };
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
const prismaSchemaPath = options.prismaSchemaPath;
|
|
576
|
+
const dtoSourcePaths = options.dtoSourcePaths ?? [];
|
|
577
|
+
|
|
578
|
+
if (!prismaSchemaPath || dtoSourcePaths.length === 0) {
|
|
579
|
+
const reason = !prismaSchemaPath ? 'no prismaSchemaPath configured' : 'no dtoSourcePaths configured';
|
|
580
|
+
console.log(`\n⏭️ Skipping validate-dtos (${reason})`);
|
|
581
|
+
console.log('');
|
|
582
|
+
return { success: true };
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
console.log('\n📏 Validating DTOs match Prisma Dbo models\n');
|
|
586
|
+
console.log(` Mode: ${mode}`);
|
|
587
|
+
console.log(` Schema: ${prismaSchemaPath}`);
|
|
588
|
+
console.log(` Dto paths: ${dtoSourcePaths.join(', ')}`);
|
|
589
|
+
|
|
590
|
+
const base = resolveBase(workspaceRoot);
|
|
591
|
+
const head = process.env['NX_HEAD'];
|
|
592
|
+
|
|
593
|
+
if (!base) {
|
|
594
|
+
console.log('\n⏭️ Skipping validate-dtos (could not detect base branch)');
|
|
595
|
+
console.log('');
|
|
596
|
+
return { success: true };
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
console.log(` Base: ${base}`);
|
|
600
|
+
console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);
|
|
601
|
+
console.log('');
|
|
602
|
+
|
|
603
|
+
const changedFiles = getChangedFiles(workspaceRoot, base, head);
|
|
604
|
+
|
|
605
|
+
return validateDtoFiles(workspaceRoot, prismaSchemaPath, changedFiles, dtoSourcePaths, mode, base, head);
|
|
606
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "http://json-schema.org/schema",
|
|
3
|
+
"title": "Validate DTOs Executor",
|
|
4
|
+
"description": "Validate DTO fields match Prisma Dbo model fields. Ensures AI agents don't invent field names.",
|
|
5
|
+
"type": "object",
|
|
6
|
+
"properties": {
|
|
7
|
+
"mode": {
|
|
8
|
+
"type": "string",
|
|
9
|
+
"enum": ["OFF", "MODIFIED_CLASS", "MODIFIED_FILES"],
|
|
10
|
+
"description": "OFF: skip validation. MODIFIED_CLASS: only validate Dto classes with changed lines. MODIFIED_FILES: validate all Dtos in modified files.",
|
|
11
|
+
"default": "OFF"
|
|
12
|
+
},
|
|
13
|
+
"prismaSchemaPath": {
|
|
14
|
+
"type": "string",
|
|
15
|
+
"description": "Relative path from workspace root to schema.prisma"
|
|
16
|
+
},
|
|
17
|
+
"dtoSourcePaths": {
|
|
18
|
+
"type": "array",
|
|
19
|
+
"items": { "type": "string" },
|
|
20
|
+
"description": "Array of directories (relative to workspace root) containing Dto files"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"required": []
|
|
24
|
+
}
|
package/executors.json
CHANGED
|
@@ -79,6 +79,11 @@
|
|
|
79
79
|
"implementation": "./architecture/executors/validate-no-any-unknown/executor",
|
|
80
80
|
"schema": "./architecture/executors/validate-no-any-unknown/schema.json",
|
|
81
81
|
"description": "Validate no any/unknown keywords are used - use specific types instead"
|
|
82
|
+
},
|
|
83
|
+
"validate-dtos": {
|
|
84
|
+
"implementation": "./architecture/executors/validate-dtos/executor",
|
|
85
|
+
"schema": "./architecture/executors/validate-dtos/schema.json",
|
|
86
|
+
"description": "Validate DTO fields match Prisma Dbo model fields"
|
|
82
87
|
}
|
|
83
88
|
}
|
|
84
89
|
}
|