@webpieces/code-rules 0.4.391 → 0.4.392

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 (51) hide show
  1. package/package.json +2 -2
  2. package/src/cli.js +2 -3
  3. package/src/cli.js.map +1 -1
  4. package/src/code-rules-app.js +1 -3
  5. package/src/code-rules-app.js.map +1 -1
  6. package/src/code-rules-engine.js +1 -3
  7. package/src/code-rules-engine.js.map +1 -1
  8. package/src/rule-reporter.js +1 -3
  9. package/src/rule-reporter.js.map +1 -1
  10. package/src/validate-catch-error-pattern.js +1 -3
  11. package/src/validate-catch-error-pattern.js.map +1 -1
  12. package/src/validate-code.js +2 -3
  13. package/src/validate-code.js.map +1 -1
  14. package/src/validate-dtos.js +1 -3
  15. package/src/validate-dtos.js.map +1 -1
  16. package/src/validate-framework-tag.js +1 -3
  17. package/src/validate-framework-tag.js.map +1 -1
  18. package/src/validate-inject-annotation-not-needed-for-concrete-class.js +1 -3
  19. package/src/validate-inject-annotation-not-needed-for-concrete-class.js.map +1 -1
  20. package/src/validate-match-rules.js +1 -3
  21. package/src/validate-match-rules.js.map +1 -1
  22. package/src/validate-modified-files.js +1 -3
  23. package/src/validate-modified-files.js.map +1 -1
  24. package/src/validate-modified-methods.js +1 -3
  25. package/src/validate-modified-methods.js.map +1 -1
  26. package/src/validate-no-any-unknown.js +1 -3
  27. package/src/validate-no-any-unknown.js.map +1 -1
  28. package/src/validate-no-destructure.js +1 -3
  29. package/src/validate-no-destructure.js.map +1 -1
  30. package/src/validate-no-direct-api-resolver.js +1 -3
  31. package/src/validate-no-direct-api-resolver.js.map +1 -1
  32. package/src/validate-no-function-outside-class.js +2 -4
  33. package/src/validate-no-function-outside-class.js.map +1 -1
  34. package/src/validate-no-implicit-any.js +1 -3
  35. package/src/validate-no-implicit-any.js.map +1 -1
  36. package/src/validate-no-inline-types.js +1 -3
  37. package/src/validate-no-inline-types.js.map +1 -1
  38. package/src/validate-no-process-exit-outside-main.js +1 -3
  39. package/src/validate-no-process-exit-outside-main.js.map +1 -1
  40. package/src/validate-no-symbol-di-tokens.js +2 -4
  41. package/src/validate-no-symbol-di-tokens.js.map +1 -1
  42. package/src/validate-no-unmanaged-exceptions.js +1 -3
  43. package/src/validate-no-unmanaged-exceptions.js.map +1 -1
  44. package/src/validate-prisma-converters.js +1 -3
  45. package/src/validate-prisma-converters.js.map +1 -1
  46. package/src/validate-return-types.js +1 -3
  47. package/src/validate-return-types.js.map +1 -1
  48. package/src/validate-role-tag.js +1 -3
  49. package/src/validate-role-tag.js.map +1 -1
  50. package/src/wp-ci.js +2 -3
  51. package/src/wp-ci.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"validate-dtos.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-dtos.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAA4J;AAC5J,qDAAiE;AACjE,0DAA2D;AAC3D,yCAAuC;AACvC,iDAAgD;AA8BhD;;;GAGG;AACH,SAAS,YAAY,CAAC,CAAS;IAC3B,OAAO,CAAC,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC,EAAE,MAAc,EAAE,EAAE,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC;AAC/E,CAAC;AAED;;;;GAIG;AACH,SAAS,iBAAiB,CAAC,UAAkB;IACzC,MAAM,MAAM,GAAG,IAAI,GAAG,EAAuB,CAAC;IAE9C,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;QAC7B,OAAO,MAAM,CAAC;IAClB,CAAC;IAED,MAAM,OAAO,GAAG,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IACrD,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAElC,IAAI,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,kEAA2B;sCAA3B,2BAA2B;IAFvC,IAAA,+BAAgB,GAAE;IAClB,IAAA,sBAAU,GAAE;6CAEW,uCAAwB;GADnC,2BAA2B,CAQvC","sourcesContent":["/**\n * Validate DTOs Executor\n *\n * Validates that every non-deprecated field in a XxxDto class/interface exists\n * in the corresponding XxxDbo Prisma model. This catches AI agents inventing\n * field names that don't match the database schema.\n *\n * ============================================================================\n * MODES\n * ============================================================================\n * - OFF: Skip validation entirely\n * - MODIFIED_CLASS: Only validate Dto classes that have changed lines in the diff\n * - NEW_AND_MODIFIED_FILES: Validate ALL Dto classes in files that were modified\n *\n * ============================================================================\n * SKIP CONDITIONS\n * ============================================================================\n * - If schema.prisma itself is modified, validation is skipped (schema in flux)\n * - Dto classes ending with \"JoinDto\" are skipped (they compose other Dtos)\n * - Fields marked @deprecated in a comment are exempt\n *\n * ============================================================================\n * MATCHING\n * ============================================================================\n * - UserDto matches UserDbo by case-insensitive prefix (\"user\")\n * - Dbo field names are converted from snake_case to camelCase for comparison\n * - Dto fields must be a subset of Dbo fields\n * - Extra Dbo fields are allowed (e.g., password)\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport { PrismaValidateDtosConfig, PrismaValidateDtosMode, detectBase, getChangedFiles, getFileDiff, getChangedLineNumbers } from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { provideSingleton } from '@webpieces/rules-config';\nimport { injectable } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\n\ninterface DtoFieldInfo {\n name: string;\n line: number;\n deprecated: boolean;\n}\n\ninterface DtoInfo {\n name: string;\n file: string;\n startLine: number;\n endLine: number;\n fields: DtoFieldInfo[];\n}\n\ninterface DtoViolation {\n file: string;\n line: number;\n dtoName: string;\n fieldName: string;\n dboName: string;\n availableFields: string[];\n}\n\ninterface DboEntry {\n name: string;\n fields: Set<string>;\n}\n\n/**\n * Convert a snake_case string to camelCase.\n * e.g., \"version_number\" -> \"versionNumber\", \"id\" -> \"id\"\n */\nfunction snakeToCamel(s: string): string {\n return s.replace(/_([a-z])/g, (_, letter: string) => letter.toUpperCase());\n}\n\n/**\n * Parse schema.prisma to build a map of Dbo model name -> set of field names (camelCase).\n * Only models whose name ends with \"Dbo\" are included.\n * Field names are converted from snake_case to camelCase since Dto fields use camelCase.\n */\nfunction parsePrismaSchema(schemaPath: string): Map<string, Set<string>> {\n const models = new Map<string, Set<string>>();\n\n if (!fs.existsSync(schemaPath)) {\n return models;\n }\n\n const content = fs.readFileSync(schemaPath, 'utf-8');\n const lines = content.split('\\n');\n\n let currentModel: string | null = null;\n let currentFields: Set<string> | null = null;\n\n for (const line of lines) {\n const trimmed = line.trim();\n\n // Match model declaration: model XxxDbo {\n const modelMatch = trimmed.match(/^model\\s+(\\w+Dbo)\\s*\\{/);\n if (modelMatch) {\n currentModel = modelMatch[1];\n currentFields = new Set<string>();\n continue;\n }\n\n // End of model block\n if (currentModel && trimmed === '}') {\n models.set(currentModel, currentFields!);\n currentModel = null;\n currentFields = null;\n continue;\n }\n\n // Inside a model block - extract field names\n if (currentModel && currentFields) {\n // Skip empty lines, comments, and model-level attributes (@@)\n if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('@@')) {\n continue;\n }\n\n // Field name is the first word on the line, converted to camelCase\n const fieldMatch = trimmed.match(/^(\\w+)\\s/);\n if (fieldMatch) {\n currentFields.add(snakeToCamel(fieldMatch[1]));\n }\n }\n }\n\n return models;\n}\n\n/**\n * Check if a field has @deprecated in a comment above it (within 3 lines).\n */\nfunction isFieldDeprecated(fileLines: string[], fieldLine: number): boolean {\n const start = Math.max(0, fieldLine - 4);\n for (let i = start; i <= fieldLine - 1; i++) {\n const line = fileLines[i]?.trim() ?? '';\n if (line.includes('@deprecated')) return true;\n }\n return false;\n}\n\n/**\n * Parse a TypeScript file to find Dto class/interface declarations and their fields.\n * Skips classes ending with \"JoinDto\" since they compose other Dtos.\n */\n// webpieces-disable max-lines-new-methods -- AST traversal for both class and interface Dto detection with field extraction\nfunction findDtosInFile(filePath: string, workspaceRoot: string): DtoInfo[] {\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const fileLines = content.split('\\n');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n\n const dtos: DtoInfo[] = [];\n\n function visit(node: ts.Node): void {\n const isClass = ts.isClassDeclaration(node);\n const isInterface = ts.isInterfaceDeclaration(node);\n\n if ((isClass || isInterface) && node.name) {\n const name = node.name.text;\n\n // Must end with Dto but NOT with JoinDto\n if (name.endsWith('Dto') && !name.endsWith('JoinDto')) {\n const fields: DtoFieldInfo[] = [];\n const nodeStart = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));\n const nodeEnd = sourceFile.getLineAndCharacterOfPosition(node.getEnd());\n\n for (const member of node.members) {\n if (ts.isPropertyDeclaration(member) || ts.isPropertySignature(member)) {\n if (member.name && ts.isIdentifier(member.name)) {\n const fieldName = member.name.text;\n const startPos = member.getStart(sourceFile);\n const pos = sourceFile.getLineAndCharacterOfPosition(startPos);\n const line = pos.line + 1;\n const deprecated = isFieldDeprecated(fileLines, line);\n\n fields.push({ name: fieldName, line, deprecated });\n }\n }\n }\n\n dtos.push({\n name,\n file: filePath,\n startLine: nodeStart.line + 1,\n endLine: nodeEnd.line + 1,\n fields,\n });\n }\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return dtos;\n}\n\n/**\n * Extract the prefix from a Dto/Dbo name by removing the suffix.\n * e.g., \"UserDto\" -> \"user\", \"UserDbo\" -> \"user\"\n */\nfunction extractPrefix(name: string, suffix: string): string {\n return name.slice(0, -suffix.length).toLowerCase();\n}\n\n/**\n * Find violations: Dto fields that don't exist in the corresponding Dbo.\n */\nfunction findViolations(\n dtos: DtoInfo[],\n dboModels: Map<string, Set<string>>\n): DtoViolation[] {\n const violations: DtoViolation[] = [];\n\n // Build a lowercase prefix -> Dbo info map\n const dboByPrefix = new Map<string, DboEntry>();\n dboModels.forEach((fields, dboName) => {\n const prefix = extractPrefix(dboName, 'Dbo');\n dboByPrefix.set(prefix, { name: dboName, fields });\n });\n\n for (const dto of dtos) {\n const prefix = extractPrefix(dto.name, 'Dto');\n const dbo = dboByPrefix.get(prefix);\n\n if (!dbo) {\n // No matching Dbo found - skip (might be a Dto without a DB table)\n continue;\n }\n\n for (const field of dto.fields) {\n if (field.deprecated) continue;\n\n if (!dbo.fields.has(field.name)) {\n violations.push({\n file: dto.file,\n line: field.line,\n dtoName: dto.name,\n fieldName: field.name,\n dboName: dbo.name,\n availableFields: Array.from(dbo.fields).sort(),\n });\n }\n }\n }\n\n return violations;\n}\n\n/**\n * Compute similarity between two strings using longest common subsequence ratio.\n * Returns a value between 0 and 1, where 1 is an exact match.\n */\nfunction similarity(a: string, b: string): number {\n const al = a.toLowerCase();\n const bl = b.toLowerCase();\n if (al === bl) return 1;\n\n const m = al.length;\n const n = bl.length;\n const prev = new Array<number>(n + 1).fill(0);\n const curr = new Array<number>(n + 1).fill(0);\n\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n if (al[i - 1] === bl[j - 1]) {\n curr[j] = prev[j - 1] + 1;\n } else {\n curr[j] = Math.max(prev[j], curr[j - 1]);\n }\n }\n for (let j = 0; j <= n; j++) {\n prev[j] = curr[j];\n curr[j] = 0;\n }\n }\n\n const lcsLen = prev[n];\n return (2 * lcsLen) / (m + n);\n}\n\n/**\n * Find the closest matching Dbo field for a given Dto field name.\n * Returns the best match or null if nothing scores above the threshold.\n */\nfunction suggestClosestField(fieldName: string, availableFields: string[]): string | null {\n let bestMatch: string | null = null;\n let bestScore = 0.4; // minimum threshold\n\n for (const candidate of availableFields) {\n const score = similarity(fieldName, candidate);\n if (score > bestScore) {\n bestScore = score;\n bestMatch = candidate;\n }\n }\n\n return bestMatch;\n}\n\n/**\n * Report violations to console with prominent AI warning and rename suggestions.\n */\nfunction reportViolations(violations: DtoViolation[]): void {\n console.error('');\n console.error('❌❌❌ DTO FIELD MISMATCH - AI AGENT: READ THIS CAREFULLY ❌❌❌');\n console.error('');\n console.error('🛑 DO NOT attempt find/replace or manual renaming. Instead:');\n console.error(' 1. IDE rename is 10x faster than AI renaming PLUS 100% correct vs. AI\\'s 80%');\n console.error(' 2. Based on errors below, suggest renames to the user');\n console.error(' 3. Ask the human to use IDE rename-refactoring (F2 / right-click → Rename Symbol)');\n console.error('');\n console.error('📚 Every non-deprecated field in a Dto must exist in the corresponding Dbo.');\n console.error(' Dbo can have extra fields (e.g., password) — Dto fields cannot be invented.');\n console.error('');\n console.error(' When needing fields from multiple tables (e.g., a join), use a XxxJoinDto that');\n console.error(' contains YYDto and ZZDto fields from the other tables instead of flattening.');\n console.error(' Fields marked @deprecated in the Dto are exempt from this check.');\n console.error('');\n\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}`);\n console.error(` ${v.dtoName}.${v.fieldName} does not exist in ${v.dboName}`);\n\n const suggestion = suggestClosestField(v.fieldName, v.availableFields);\n if (suggestion) {\n console.error(` 💡 Suggested rename: ${v.fieldName} → ${suggestion} (Use IDE rename on ${v.dtoName}.${v.fieldName})`);\n } else {\n const preview = v.availableFields.slice(0, 8).join(', ');\n const ellipsis = v.availableFields.length > 8 ? ', ...' : '';\n console.error(` 💡 No close match found. Available: ${preview}${ellipsis}`);\n }\n }\n console.error('');\n\n console.error('❌❌❌ AI AGENT: Suggest to the human which are the most likely renames needed and list them ❌❌❌');\n console.error('');\n}\n\n/**\n * Filter changed files to only TypeScript Dto source files within configured paths.\n */\nfunction filterDtoFiles(changedFiles: string[], dtoSourcePaths: string[]): string[] {\n return changedFiles.filter((f) => {\n if (!f.endsWith('.ts') && !f.endsWith('.tsx')) return false;\n if (f.includes('.spec.ts') || f.includes('.test.ts')) return false;\n return dtoSourcePaths.some((srcPath) => f.startsWith(srcPath));\n });\n}\n\n/**\n * Collect all Dto definitions from the given files.\n */\nfunction collectDtos(dtoFiles: string[], workspaceRoot: string): DtoInfo[] {\n const allDtos: DtoInfo[] = [];\n for (const file of dtoFiles) {\n const dtos = findDtosInFile(file, workspaceRoot);\n allDtos.push(...dtos);\n }\n return allDtos;\n}\n\n/**\n * Check if a Dto class overlaps with any changed lines in the diff.\n */\nfunction isDtoTouched(dto: DtoInfo, changedLines: Set<number>): boolean {\n for (let line = dto.startLine; line <= dto.endLine; line++) {\n if (changedLines.has(line)) return true;\n }\n return false;\n}\n\n/**\n * Filter Dtos to only those that have changed lines in the diff (MODIFIED_CLASS mode).\n */\nfunction filterTouchedDtos(\n dtos: DtoInfo[],\n workspaceRoot: string,\n base: string,\n head?: string\n): DtoInfo[] {\n // Group dtos by file to avoid re-fetching diffs\n const byFile = new Map<string, DtoInfo[]>();\n for (const dto of dtos) {\n const list = byFile.get(dto.file) ?? [];\n list.push(dto);\n byFile.set(dto.file, list);\n }\n\n const touched: DtoInfo[] = [];\n byFile.forEach((fileDtos, file) => {\n const diff = getFileDiff(workspaceRoot, file, base, head);\n const changedLines = getChangedLineNumbers(diff);\n for (const dto of fileDtos) {\n if (isDtoTouched(dto, changedLines)) {\n touched.push(dto);\n }\n }\n });\n return touched;\n}\n\n/**\n * Resolve git base ref from env vars or auto-detection.\n */\nfunction resolveBase(workspaceRoot: string): string | undefined {\n const envBase = process.env['NX_BASE'];\n if (envBase) return envBase;\n return detectBase(workspaceRoot) ?? undefined;\n}\n\n/**\n * Run the core validation after early-exit checks have passed.\n */\n// webpieces-disable max-lines-new-methods -- Core validation orchestration with multiple early-exit checks\nfunction validateDtoFiles(\n workspaceRoot: string,\n prismaSchemaPath: string,\n changedFiles: string[],\n dtoSourcePaths: string[],\n mode: PrismaValidateDtosMode,\n base: string,\n head?: string\n): ExecutorResult {\n if (changedFiles.some((f) => f.endsWith(prismaSchemaPath))) {\n console.log('⏭️ Skipping validate-dtos (schema.prisma is modified - schema in flux)');\n console.log('');\n return { success: true };\n }\n\n const dtoFiles = filterDtoFiles(changedFiles, dtoSourcePaths);\n\n if (dtoFiles.length === 0) {\n console.log('✅ No Dto files changed');\n return { success: true };\n }\n\n console.log(`📂 Checking ${dtoFiles.length} changed file(s) for Dto definitions...`);\n\n const fullSchemaPath = path.join(workspaceRoot, prismaSchemaPath);\n const dboModels = parsePrismaSchema(fullSchemaPath);\n\n if (dboModels.size === 0) {\n console.log('⏭️ No Dbo models found in schema.prisma');\n console.log('');\n return { success: true };\n }\n\n console.log(` Found ${dboModels.size} Dbo model(s) in schema.prisma`);\n\n let allDtos = collectDtos(dtoFiles, workspaceRoot);\n\n if (allDtos.length === 0) {\n console.log('✅ No Dto definitions found in changed files');\n return { success: true };\n }\n\n // In MODIFIED_CLASS mode, narrow to only Dtos with changed lines\n if (mode === 'MODIFIED_CLASS') {\n allDtos = filterTouchedDtos(allDtos, workspaceRoot, base, head);\n if (allDtos.length === 0) {\n console.log('✅ No Dto classes were modified');\n return { success: true };\n }\n }\n\n console.log(` Validating ${allDtos.length} Dto definition(s)`);\n\n const violations = findViolations(allDtos, dboModels);\n\n if (violations.length === 0) {\n console.log('✅ All Dto fields match their Dbo models');\n return { success: true };\n }\n\n reportViolations(violations);\n return { success: false };\n}\n\n/**\n * Resolve mode considering ignoreModifiedUntilEpoch override.\n * When active, downgrades to OFF. When expired, logs a warning.\n */\nfunction resolveMode(normalMode: PrismaValidateDtosMode, epoch: number | undefined, branchPattern: string | undefined): PrismaValidateDtosMode {\n if (normalMode === 'OFF') {\n return normalMode;\n }\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping validate-dtos (${skip.reason})`);\n console.log('');\n return 'OFF';\n }\n return normalMode;\n}\n\nasync function runValidatorImpl(\n options: PrismaValidateDtosConfig,\n workspaceRoot: string\n): Promise<ExecutorResult> {\n const mode = resolveMode(options.mode ?? 'OFF', options.ignoreModifiedUntilEpoch, options.ignoreRuleWhileOnBranch);\n\n if (mode === 'OFF') {\n console.log('\\n⏭️ Skipping validate-dtos (mode: OFF)');\n console.log('');\n return { success: true };\n }\n\n const prismaSchemaPath = options.prismaSchemaPath;\n const dtoSourcePaths = options.dtoSourcePaths ?? [];\n\n if (!prismaSchemaPath || dtoSourcePaths.length === 0) {\n const reason = !prismaSchemaPath ? 'no prismaSchemaPath configured' : 'no dtoSourcePaths configured';\n console.log(`\\n⏭️ Skipping validate-dtos (${reason})`);\n console.log('');\n return { success: true };\n }\n\n console.log('\\n📏 Validating DTOs match Prisma Dbo models\\n');\n console.log(` Mode: ${mode}`);\n console.log(` Schema: ${prismaSchemaPath}`);\n console.log(` Dto paths: ${dtoSourcePaths.join(', ')}`);\n\n const base = resolveBase(workspaceRoot);\n const head = process.env['NX_HEAD'];\n\n if (!base) {\n console.log('\\n⏭️ Skipping validate-dtos (could not detect base branch)');\n console.log('');\n return { success: true };\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);\n console.log('');\n\n const changedFiles = getChangedFiles(workspaceRoot, base, head, { tsOnly: false });\n\n return validateDtoFiles(workspaceRoot, prismaSchemaPath, changedFiles, dtoSourcePaths, mode, base, head);\n}\n\n@provideSingleton()\n@injectable()\nexport class PrismaValidateDtosValidator extends CodeValidator<PrismaValidateDtosConfig> {\n constructor(config: PrismaValidateDtosConfig) {\n super(config, 'prisma-validate-dtos');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.config, workspaceRoot);\n }\n}\n"]}
1
+ {"version":3,"file":"validate-dtos.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-dtos.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAA4J;AAC5J,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AA8BhD;;;GAGG;AACH,SAAS,YAAY,CAAC,CAAS;IAC3B,OAAO,CAAC,C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E,IAAI,EAAE,IAAI,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;IAEnF,OAAO,gBAAgB,CAAC,aAAa,EAAE,gBAAgB,EAAE,YAAY,EAAE,cAAc,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAC7G,CAAC;AAGM,IAAM,2BAA2B,GAAjC,MAAM,2BAA4B,SAAQ,8BAAuC;IACpF,YAAY,MAAgC;QACxC,KAAK,CAAC,MAAM,EAAE,sBAAsB,CAAC,CAAC;IAC1C,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,OAAO,gBAAgB,CAAC,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxD,CAAC;CACJ,CAAA;AARY,kEAA2B;sCAA3B,2BAA2B;IADvC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,uCAAwB;GADnC,2BAA2B,CAQvC","sourcesContent":["/**\n * Validate DTOs Executor\n *\n * Validates that every non-deprecated field in a XxxDto class/interface exists\n * in the corresponding XxxDbo Prisma model. This catches AI agents inventing\n * field names that don't match the database schema.\n *\n * ============================================================================\n * MODES\n * ============================================================================\n * - OFF: Skip validation entirely\n * - MODIFIED_CLASS: Only validate Dto classes that have changed lines in the diff\n * - NEW_AND_MODIFIED_FILES: Validate ALL Dto classes in files that were modified\n *\n * ============================================================================\n * SKIP CONDITIONS\n * ============================================================================\n * - If schema.prisma itself is modified, validation is skipped (schema in flux)\n * - Dto classes ending with \"JoinDto\" are skipped (they compose other Dtos)\n * - Fields marked @deprecated in a comment are exempt\n *\n * ============================================================================\n * MATCHING\n * ============================================================================\n * - UserDto matches UserDbo by case-insensitive prefix (\"user\")\n * - Dbo field names are converted from snake_case to camelCase for comparison\n * - Dto fields must be a subset of Dbo fields\n * - Extra Dbo fields are allowed (e.g., password)\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport { PrismaValidateDtosConfig, PrismaValidateDtosMode, detectBase, getChangedFiles, getFileDiff, getChangedLineNumbers } from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\n\ninterface DtoFieldInfo {\n name: string;\n line: number;\n deprecated: boolean;\n}\n\ninterface DtoInfo {\n name: string;\n file: string;\n startLine: number;\n endLine: number;\n fields: DtoFieldInfo[];\n}\n\ninterface DtoViolation {\n file: string;\n line: number;\n dtoName: string;\n fieldName: string;\n dboName: string;\n availableFields: string[];\n}\n\ninterface DboEntry {\n name: string;\n fields: Set<string>;\n}\n\n/**\n * Convert a snake_case string to camelCase.\n * e.g., \"version_number\" -> \"versionNumber\", \"id\" -> \"id\"\n */\nfunction snakeToCamel(s: string): string {\n return s.replace(/_([a-z])/g, (_, letter: string) => letter.toUpperCase());\n}\n\n/**\n * Parse schema.prisma to build a map of Dbo model name -> set of field names (camelCase).\n * Only models whose name ends with \"Dbo\" are included.\n * Field names are converted from snake_case to camelCase since Dto fields use camelCase.\n */\nfunction parsePrismaSchema(schemaPath: string): Map<string, Set<string>> {\n const models = new Map<string, Set<string>>();\n\n if (!fs.existsSync(schemaPath)) {\n return models;\n }\n\n const content = fs.readFileSync(schemaPath, 'utf-8');\n const lines = content.split('\\n');\n\n let currentModel: string | null = null;\n let currentFields: Set<string> | null = null;\n\n for (const line of lines) {\n const trimmed = line.trim();\n\n // Match model declaration: model XxxDbo {\n const modelMatch = trimmed.match(/^model\\s+(\\w+Dbo)\\s*\\{/);\n if (modelMatch) {\n currentModel = modelMatch[1];\n currentFields = new Set<string>();\n continue;\n }\n\n // End of model block\n if (currentModel && trimmed === '}') {\n models.set(currentModel, currentFields!);\n currentModel = null;\n currentFields = null;\n continue;\n }\n\n // Inside a model block - extract field names\n if (currentModel && currentFields) {\n // Skip empty lines, comments, and model-level attributes (@@)\n if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('@@')) {\n continue;\n }\n\n // Field name is the first word on the line, converted to camelCase\n const fieldMatch = trimmed.match(/^(\\w+)\\s/);\n if (fieldMatch) {\n currentFields.add(snakeToCamel(fieldMatch[1]));\n }\n }\n }\n\n return models;\n}\n\n/**\n * Check if a field has @deprecated in a comment above it (within 3 lines).\n */\nfunction isFieldDeprecated(fileLines: string[], fieldLine: number): boolean {\n const start = Math.max(0, fieldLine - 4);\n for (let i = start; i <= fieldLine - 1; i++) {\n const line = fileLines[i]?.trim() ?? '';\n if (line.includes('@deprecated')) return true;\n }\n return false;\n}\n\n/**\n * Parse a TypeScript file to find Dto class/interface declarations and their fields.\n * Skips classes ending with \"JoinDto\" since they compose other Dtos.\n */\n// webpieces-disable max-lines-new-methods -- AST traversal for both class and interface Dto detection with field extraction\nfunction findDtosInFile(filePath: string, workspaceRoot: string): DtoInfo[] {\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const fileLines = content.split('\\n');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n\n const dtos: DtoInfo[] = [];\n\n function visit(node: ts.Node): void {\n const isClass = ts.isClassDeclaration(node);\n const isInterface = ts.isInterfaceDeclaration(node);\n\n if ((isClass || isInterface) && node.name) {\n const name = node.name.text;\n\n // Must end with Dto but NOT with JoinDto\n if (name.endsWith('Dto') && !name.endsWith('JoinDto')) {\n const fields: DtoFieldInfo[] = [];\n const nodeStart = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));\n const nodeEnd = sourceFile.getLineAndCharacterOfPosition(node.getEnd());\n\n for (const member of node.members) {\n if (ts.isPropertyDeclaration(member) || ts.isPropertySignature(member)) {\n if (member.name && ts.isIdentifier(member.name)) {\n const fieldName = member.name.text;\n const startPos = member.getStart(sourceFile);\n const pos = sourceFile.getLineAndCharacterOfPosition(startPos);\n const line = pos.line + 1;\n const deprecated = isFieldDeprecated(fileLines, line);\n\n fields.push({ name: fieldName, line, deprecated });\n }\n }\n }\n\n dtos.push({\n name,\n file: filePath,\n startLine: nodeStart.line + 1,\n endLine: nodeEnd.line + 1,\n fields,\n });\n }\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return dtos;\n}\n\n/**\n * Extract the prefix from a Dto/Dbo name by removing the suffix.\n * e.g., \"UserDto\" -> \"user\", \"UserDbo\" -> \"user\"\n */\nfunction extractPrefix(name: string, suffix: string): string {\n return name.slice(0, -suffix.length).toLowerCase();\n}\n\n/**\n * Find violations: Dto fields that don't exist in the corresponding Dbo.\n */\nfunction findViolations(\n dtos: DtoInfo[],\n dboModels: Map<string, Set<string>>\n): DtoViolation[] {\n const violations: DtoViolation[] = [];\n\n // Build a lowercase prefix -> Dbo info map\n const dboByPrefix = new Map<string, DboEntry>();\n dboModels.forEach((fields, dboName) => {\n const prefix = extractPrefix(dboName, 'Dbo');\n dboByPrefix.set(prefix, { name: dboName, fields });\n });\n\n for (const dto of dtos) {\n const prefix = extractPrefix(dto.name, 'Dto');\n const dbo = dboByPrefix.get(prefix);\n\n if (!dbo) {\n // No matching Dbo found - skip (might be a Dto without a DB table)\n continue;\n }\n\n for (const field of dto.fields) {\n if (field.deprecated) continue;\n\n if (!dbo.fields.has(field.name)) {\n violations.push({\n file: dto.file,\n line: field.line,\n dtoName: dto.name,\n fieldName: field.name,\n dboName: dbo.name,\n availableFields: Array.from(dbo.fields).sort(),\n });\n }\n }\n }\n\n return violations;\n}\n\n/**\n * Compute similarity between two strings using longest common subsequence ratio.\n * Returns a value between 0 and 1, where 1 is an exact match.\n */\nfunction similarity(a: string, b: string): number {\n const al = a.toLowerCase();\n const bl = b.toLowerCase();\n if (al === bl) return 1;\n\n const m = al.length;\n const n = bl.length;\n const prev = new Array<number>(n + 1).fill(0);\n const curr = new Array<number>(n + 1).fill(0);\n\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n if (al[i - 1] === bl[j - 1]) {\n curr[j] = prev[j - 1] + 1;\n } else {\n curr[j] = Math.max(prev[j], curr[j - 1]);\n }\n }\n for (let j = 0; j <= n; j++) {\n prev[j] = curr[j];\n curr[j] = 0;\n }\n }\n\n const lcsLen = prev[n];\n return (2 * lcsLen) / (m + n);\n}\n\n/**\n * Find the closest matching Dbo field for a given Dto field name.\n * Returns the best match or null if nothing scores above the threshold.\n */\nfunction suggestClosestField(fieldName: string, availableFields: string[]): string | null {\n let bestMatch: string | null = null;\n let bestScore = 0.4; // minimum threshold\n\n for (const candidate of availableFields) {\n const score = similarity(fieldName, candidate);\n if (score > bestScore) {\n bestScore = score;\n bestMatch = candidate;\n }\n }\n\n return bestMatch;\n}\n\n/**\n * Report violations to console with prominent AI warning and rename suggestions.\n */\nfunction reportViolations(violations: DtoViolation[]): void {\n console.error('');\n console.error('❌❌❌ DTO FIELD MISMATCH - AI AGENT: READ THIS CAREFULLY ❌❌❌');\n console.error('');\n console.error('🛑 DO NOT attempt find/replace or manual renaming. Instead:');\n console.error(' 1. IDE rename is 10x faster than AI renaming PLUS 100% correct vs. AI\\'s 80%');\n console.error(' 2. Based on errors below, suggest renames to the user');\n console.error(' 3. Ask the human to use IDE rename-refactoring (F2 / right-click → Rename Symbol)');\n console.error('');\n console.error('📚 Every non-deprecated field in a Dto must exist in the corresponding Dbo.');\n console.error(' Dbo can have extra fields (e.g., password) — Dto fields cannot be invented.');\n console.error('');\n console.error(' When needing fields from multiple tables (e.g., a join), use a XxxJoinDto that');\n console.error(' contains YYDto and ZZDto fields from the other tables instead of flattening.');\n console.error(' Fields marked @deprecated in the Dto are exempt from this check.');\n console.error('');\n\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}`);\n console.error(` ${v.dtoName}.${v.fieldName} does not exist in ${v.dboName}`);\n\n const suggestion = suggestClosestField(v.fieldName, v.availableFields);\n if (suggestion) {\n console.error(` 💡 Suggested rename: ${v.fieldName} → ${suggestion} (Use IDE rename on ${v.dtoName}.${v.fieldName})`);\n } else {\n const preview = v.availableFields.slice(0, 8).join(', ');\n const ellipsis = v.availableFields.length > 8 ? ', ...' : '';\n console.error(` 💡 No close match found. Available: ${preview}${ellipsis}`);\n }\n }\n console.error('');\n\n console.error('❌❌❌ AI AGENT: Suggest to the human which are the most likely renames needed and list them ❌❌❌');\n console.error('');\n}\n\n/**\n * Filter changed files to only TypeScript Dto source files within configured paths.\n */\nfunction filterDtoFiles(changedFiles: string[], dtoSourcePaths: string[]): string[] {\n return changedFiles.filter((f) => {\n if (!f.endsWith('.ts') && !f.endsWith('.tsx')) return false;\n if (f.includes('.spec.ts') || f.includes('.test.ts')) return false;\n return dtoSourcePaths.some((srcPath) => f.startsWith(srcPath));\n });\n}\n\n/**\n * Collect all Dto definitions from the given files.\n */\nfunction collectDtos(dtoFiles: string[], workspaceRoot: string): DtoInfo[] {\n const allDtos: DtoInfo[] = [];\n for (const file of dtoFiles) {\n const dtos = findDtosInFile(file, workspaceRoot);\n allDtos.push(...dtos);\n }\n return allDtos;\n}\n\n/**\n * Check if a Dto class overlaps with any changed lines in the diff.\n */\nfunction isDtoTouched(dto: DtoInfo, changedLines: Set<number>): boolean {\n for (let line = dto.startLine; line <= dto.endLine; line++) {\n if (changedLines.has(line)) return true;\n }\n return false;\n}\n\n/**\n * Filter Dtos to only those that have changed lines in the diff (MODIFIED_CLASS mode).\n */\nfunction filterTouchedDtos(\n dtos: DtoInfo[],\n workspaceRoot: string,\n base: string,\n head?: string\n): DtoInfo[] {\n // Group dtos by file to avoid re-fetching diffs\n const byFile = new Map<string, DtoInfo[]>();\n for (const dto of dtos) {\n const list = byFile.get(dto.file) ?? [];\n list.push(dto);\n byFile.set(dto.file, list);\n }\n\n const touched: DtoInfo[] = [];\n byFile.forEach((fileDtos, file) => {\n const diff = getFileDiff(workspaceRoot, file, base, head);\n const changedLines = getChangedLineNumbers(diff);\n for (const dto of fileDtos) {\n if (isDtoTouched(dto, changedLines)) {\n touched.push(dto);\n }\n }\n });\n return touched;\n}\n\n/**\n * Resolve git base ref from env vars or auto-detection.\n */\nfunction resolveBase(workspaceRoot: string): string | undefined {\n const envBase = process.env['NX_BASE'];\n if (envBase) return envBase;\n return detectBase(workspaceRoot) ?? undefined;\n}\n\n/**\n * Run the core validation after early-exit checks have passed.\n */\n// webpieces-disable max-lines-new-methods -- Core validation orchestration with multiple early-exit checks\nfunction validateDtoFiles(\n workspaceRoot: string,\n prismaSchemaPath: string,\n changedFiles: string[],\n dtoSourcePaths: string[],\n mode: PrismaValidateDtosMode,\n base: string,\n head?: string\n): ExecutorResult {\n if (changedFiles.some((f) => f.endsWith(prismaSchemaPath))) {\n console.log('⏭️ Skipping validate-dtos (schema.prisma is modified - schema in flux)');\n console.log('');\n return { success: true };\n }\n\n const dtoFiles = filterDtoFiles(changedFiles, dtoSourcePaths);\n\n if (dtoFiles.length === 0) {\n console.log('✅ No Dto files changed');\n return { success: true };\n }\n\n console.log(`📂 Checking ${dtoFiles.length} changed file(s) for Dto definitions...`);\n\n const fullSchemaPath = path.join(workspaceRoot, prismaSchemaPath);\n const dboModels = parsePrismaSchema(fullSchemaPath);\n\n if (dboModels.size === 0) {\n console.log('⏭️ No Dbo models found in schema.prisma');\n console.log('');\n return { success: true };\n }\n\n console.log(` Found ${dboModels.size} Dbo model(s) in schema.prisma`);\n\n let allDtos = collectDtos(dtoFiles, workspaceRoot);\n\n if (allDtos.length === 0) {\n console.log('✅ No Dto definitions found in changed files');\n return { success: true };\n }\n\n // In MODIFIED_CLASS mode, narrow to only Dtos with changed lines\n if (mode === 'MODIFIED_CLASS') {\n allDtos = filterTouchedDtos(allDtos, workspaceRoot, base, head);\n if (allDtos.length === 0) {\n console.log('✅ No Dto classes were modified');\n return { success: true };\n }\n }\n\n console.log(` Validating ${allDtos.length} Dto definition(s)`);\n\n const violations = findViolations(allDtos, dboModels);\n\n if (violations.length === 0) {\n console.log('✅ All Dto fields match their Dbo models');\n return { success: true };\n }\n\n reportViolations(violations);\n return { success: false };\n}\n\n/**\n * Resolve mode considering ignoreModifiedUntilEpoch override.\n * When active, downgrades to OFF. When expired, logs a warning.\n */\nfunction resolveMode(normalMode: PrismaValidateDtosMode, epoch: number | undefined, branchPattern: string | undefined): PrismaValidateDtosMode {\n if (normalMode === 'OFF') {\n return normalMode;\n }\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping validate-dtos (${skip.reason})`);\n console.log('');\n return 'OFF';\n }\n return normalMode;\n}\n\nasync function runValidatorImpl(\n options: PrismaValidateDtosConfig,\n workspaceRoot: string\n): Promise<ExecutorResult> {\n const mode = resolveMode(options.mode ?? 'OFF', options.ignoreModifiedUntilEpoch, options.ignoreRuleWhileOnBranch);\n\n if (mode === 'OFF') {\n console.log('\\n⏭️ Skipping validate-dtos (mode: OFF)');\n console.log('');\n return { success: true };\n }\n\n const prismaSchemaPath = options.prismaSchemaPath;\n const dtoSourcePaths = options.dtoSourcePaths ?? [];\n\n if (!prismaSchemaPath || dtoSourcePaths.length === 0) {\n const reason = !prismaSchemaPath ? 'no prismaSchemaPath configured' : 'no dtoSourcePaths configured';\n console.log(`\\n⏭️ Skipping validate-dtos (${reason})`);\n console.log('');\n return { success: true };\n }\n\n console.log('\\n📏 Validating DTOs match Prisma Dbo models\\n');\n console.log(` Mode: ${mode}`);\n console.log(` Schema: ${prismaSchemaPath}`);\n console.log(` Dto paths: ${dtoSourcePaths.join(', ')}`);\n\n const base = resolveBase(workspaceRoot);\n const head = process.env['NX_HEAD'];\n\n if (!base) {\n console.log('\\n⏭️ Skipping validate-dtos (could not detect base branch)');\n console.log('');\n return { success: true };\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);\n console.log('');\n\n const changedFiles = getChangedFiles(workspaceRoot, base, head, { tsOnly: false });\n\n return validateDtoFiles(workspaceRoot, prismaSchemaPath, changedFiles, dtoSourcePaths, mode, base, head);\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class PrismaValidateDtosValidator extends CodeValidator<PrismaValidateDtosConfig> {\n constructor(config: PrismaValidateDtosConfig) {\n super(config, 'prisma-validate-dtos');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.config, workspaceRoot);\n }\n}\n"]}
@@ -38,7 +38,6 @@ exports.findUntaggedProjects = findUntaggedProjects;
38
38
  const tslib_1 = require("tslib");
39
39
  const rules_config_1 = require("@webpieces/rules-config");
40
40
  const code_validator_1 = require("./code-validator");
41
- const rules_config_2 = require("@webpieces/rules-config");
42
41
  const inversify_1 = require("inversify");
43
42
  const tag_rule_1 = require("./tag-rule");
44
43
  const FRAMEWORK_TAG_PREFIX = 'framework:';
@@ -104,8 +103,7 @@ let FrameworkTagValidator = class FrameworkTagValidator extends code_validator_1
104
103
  };
105
104
  exports.FrameworkTagValidator = FrameworkTagValidator;
106
105
  exports.FrameworkTagValidator = FrameworkTagValidator = tslib_1.__decorate([
107
- (0, rules_config_2.provideSingleton)(),
108
- (0, inversify_1.injectable)(),
106
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
109
107
  tslib_1.__metadata("design:paramtypes", [rules_config_1.FrameworkTagConfig])
110
108
  ], FrameworkTagValidator);
111
109
  //# sourceMappingURL=validate-framework-tag.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate-framework-tag.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-framework-tag.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;;;AAwBH,oDAEC;;AAxBD,0DAA0E;AAC1E,qDAAiE;AACjE,0DAA2D;AAC3D,yCAAuC;AACvC,yCAMoB;AAEpB,MAAM,oBAAoB,GAAG,YAAY,CAAC;AAC1C,MAAM,mBAAmB,GAAG,CAAC,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,CAAC,CAAC;AAE/E,kFAAkF;AAClF,MAAM,iBAAiB,GAAG,KAAK,CAAC;AAEhC;;;GAGG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AAsB,SAAQ,8BAAiC;IACxE,YAAY,MAA0B;QAClC,KAAK,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IACnC,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,OAAO,IAAA,0BAAe,EAAC,IAAI,CAAC,MAAM,EAAE,aAAa,EAAE,kBAAkB,CAAC,CAAC;IAC3E,CAAC;CACJ,CAAA;AARY,sDAAqB;gCAArB,qBAAqB;IAFjC,IAAA,+BAAgB,GAAE;IAClB,IAAA,sBAAU,GAAE;6CAEW,iCAAkB;GAD7B,qBAAqB,CAQjC","sourcesContent":["/**\n * Validate Framework Tag Executor\n *\n * Every project that a changed source file belongs to must carry at least one\n * `framework:<value>` nx tag in its project.json. Those tags are the project's\n * \"libType\" — the SET of runtime environments it is validated to run in, drawn\n * from the atomic values:\n *\n * framework:browser | framework:react | framework:angular\n * framework:node | framework:express\n *\n * A project lists EVERY environment it promises to run in (e.g.\n * `framework:browser` + `framework:node`). This env set is the source of truth\n * for the `framework` field written into architecture/dependencies.json and for\n * the `library-types-match-client` rule, which uses the compatibility lattice\n * (react/angular→browser, express→node) to keep an express project from\n * depending on a browser-only library (and vice-versa).\n *\n * The legacy single-value `framework:all` \"usable by any side\" bucket is\n * REMOVED — it is a hard error, and the author must declare the actual env set.\n *\n * The project-walking + diff-scoping + mode logic is shared with the `role-tag`\n * rule in `tag-rule.ts`; this file supplies only the framework-specific prefix,\n * known values, and violation messages. Unlike role-tag, framework-tag ALSO\n * validates tag VALUES (allowing multiple) via {@link TagRuleSpec.validateValues}.\n *\n * ============================================================================\n * MODES (PROJECT-LEVEL)\n * ============================================================================\n * - OFF: Skip validation entirely.\n * - MODIFIED_PROJECTS: Require >=1 valid framework tag on every project that\n * owns ANY changed file (not just .ts, and not line-scoped).\n */\n\nimport { ProjectMode, FrameworkTagConfig } from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { provideSingleton } from '@webpieces/rules-config';\nimport { injectable } from 'inversify';\nimport {\n InvalidTagProject,\n MissingTagProject,\n TagRuleSpec,\n findProjectsMissingTag,\n runTagValidator,\n} from './tag-rule';\n\nconst FRAMEWORK_TAG_PREFIX = 'framework:';\nconst DEFAULT_KNOWN_TYPES = ['browser', 'react', 'angular', 'node', 'express'];\n\n/** The removed legacy libType, kept only to emit a targeted migration message. */\nconst REMOVED_ALL_VALUE = 'all';\n\n/**\n * Back-compat export used by tests: the framework-tag flavor of the shared\n * missing-tag scan.\n */\nexport function findUntaggedProjects(workspaceRoot: string, changedFiles: string[]): MissingTagProject[] {\n return findProjectsMissingTag(workspaceRoot, changedFiles, FRAMEWORK_TAG_PREFIX);\n}\n\nfunction reportViolations(untagged: MissingTagProject[], knownTypes: string[], mode: ProjectMode): void {\n const suggestion = knownTypes.map((t: string) => `${FRAMEWORK_TAG_PREFIX}${t}`).join(' | ');\n console.error('');\n console.error('❌ Every modified project must declare the env set it runs in (>=1 framework tag)!');\n console.error('');\n console.error(` Add ONE OR MORE of these to the project's project.json \"tags\" array: ${suggestion}`);\n console.error(' (react/angular specialize browser; express specializes node. A project that runs in');\n console.error(' both the browser and node declares BOTH, e.g. framework:browser + framework:node.)');\n console.error(' This libType drives architecture/dependencies.json and the library-types-match-client rule.');\n console.error('');\n\n for (const project of untagged) {\n console.error(` ❌ ${project.name} — ${project.projectJsonPath}`);\n console.error(` add e.g. \"tags\": [\"${FRAMEWORK_TAG_PREFIX}browser\", \"${FRAMEWORK_TAG_PREFIX}node\"]`);\n }\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n}\n\nfunction reportInvalidValues(invalid: InvalidTagProject[], knownTypes: string[], mode: ProjectMode): void {\n const known = knownTypes.map((t: string) => `${FRAMEWORK_TAG_PREFIX}${t}`).join(' | ');\n console.error('');\n console.error('❌ Some modified projects carry an unknown framework tag value!');\n console.error('');\n console.error(` Allowed values: ${known}`);\n console.error('');\n\n for (const project of invalid) {\n console.error(` ❌ ${project.name} — ${project.projectJsonPath}`);\n for (const bad of project.badValues) {\n if (bad === REMOVED_ALL_VALUE) {\n console.error(\n ` framework:all is removed — declare the actual env set, ` +\n `e.g. framework:browser + framework:node`\n );\n } else {\n console.error(` unknown value \"${FRAMEWORK_TAG_PREFIX}${bad}\" — use one of: ${known}`);\n }\n }\n }\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n}\n\nconst FRAMEWORK_TAG_SPEC = new TagRuleSpec(\n FRAMEWORK_TAG_PREFIX,\n 'framework-tag',\n 'Framework Tag',\n DEFAULT_KNOWN_TYPES,\n reportViolations,\n true,\n reportInvalidValues\n);\n\n@provideSingleton()\n@injectable()\nexport class FrameworkTagValidator extends CodeValidator<FrameworkTagConfig> {\n constructor(config: FrameworkTagConfig) {\n super(config, 'framework-tag');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runTagValidator(this.config, workspaceRoot, FRAMEWORK_TAG_SPEC);\n }\n}\n"]}
1
+ {"version":3,"file":"validate-framework-tag.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-framework-tag.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;;;AAuBH,oDAEC;;AAvBD,0DAA0E;AAC1E,qDAAiE;AACjE,yCAA2D;AAC3D,yCAMoB;AAEpB,MAAM,oBAAoB,GAAG,YAAY,CAAC;AAC1C,MAAM,mBAAmB,GAAG,CAAC,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,CAAC,CAAC;AAE/E,kFAAkF;AAClF,MAAM,iBAAiB,GAAG,KAAK,CAAC;AAEhC;;;GAGG;AACH,SAAgB,oBAAoB,CAAC,aAAqB,EAAE,YAAsB;IAC9E,OAAO,IAAA,iCAAsB,EAAC,aAAa,EAAE,YAAY,EAAE,oBAAoB,CAAC,CAAC;AACrF,CAAC;AAED,SAAS,gBAAgB,CAAC,QAA6B,EAAE,UAAoB,EAAE,IAAiB;IAC5F,MAAM,UAAU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AAC,CAAC;IAC3E,CAAC;CACJ,CAAA;AARY,sDAAqB;gCAArB,qBAAqB;IADjC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,iCAAkB;GAD7B,qBAAqB,CAQjC","sourcesContent":["/**\n * Validate Framework Tag Executor\n *\n * Every project that a changed source file belongs to must carry at least one\n * `framework:<value>` nx tag in its project.json. Those tags are the project's\n * \"libType\" — the SET of runtime environments it is validated to run in, drawn\n * from the atomic values:\n *\n * framework:browser | framework:react | framework:angular\n * framework:node | framework:express\n *\n * A project lists EVERY environment it promises to run in (e.g.\n * `framework:browser` + `framework:node`). This env set is the source of truth\n * for the `framework` field written into architecture/dependencies.json and for\n * the `library-types-match-client` rule, which uses the compatibility lattice\n * (react/angular→browser, express→node) to keep an express project from\n * depending on a browser-only library (and vice-versa).\n *\n * The legacy single-value `framework:all` \"usable by any side\" bucket is\n * REMOVED — it is a hard error, and the author must declare the actual env set.\n *\n * The project-walking + diff-scoping + mode logic is shared with the `role-tag`\n * rule in `tag-rule.ts`; this file supplies only the framework-specific prefix,\n * known values, and violation messages. Unlike role-tag, framework-tag ALSO\n * validates tag VALUES (allowing multiple) via {@link TagRuleSpec.validateValues}.\n *\n * ============================================================================\n * MODES (PROJECT-LEVEL)\n * ============================================================================\n * - OFF: Skip validation entirely.\n * - MODIFIED_PROJECTS: Require >=1 valid framework tag on every project that\n * owns ANY changed file (not just .ts, and not line-scoped).\n */\n\nimport { ProjectMode, FrameworkTagConfig } from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport {\n InvalidTagProject,\n MissingTagProject,\n TagRuleSpec,\n findProjectsMissingTag,\n runTagValidator,\n} from './tag-rule';\n\nconst FRAMEWORK_TAG_PREFIX = 'framework:';\nconst DEFAULT_KNOWN_TYPES = ['browser', 'react', 'angular', 'node', 'express'];\n\n/** The removed legacy libType, kept only to emit a targeted migration message. */\nconst REMOVED_ALL_VALUE = 'all';\n\n/**\n * Back-compat export used by tests: the framework-tag flavor of the shared\n * missing-tag scan.\n */\nexport function findUntaggedProjects(workspaceRoot: string, changedFiles: string[]): MissingTagProject[] {\n return findProjectsMissingTag(workspaceRoot, changedFiles, FRAMEWORK_TAG_PREFIX);\n}\n\nfunction reportViolations(untagged: MissingTagProject[], knownTypes: string[], mode: ProjectMode): void {\n const suggestion = knownTypes.map((t: string) => `${FRAMEWORK_TAG_PREFIX}${t}`).join(' | ');\n console.error('');\n console.error('❌ Every modified project must declare the env set it runs in (>=1 framework tag)!');\n console.error('');\n console.error(` Add ONE OR MORE of these to the project's project.json \"tags\" array: ${suggestion}`);\n console.error(' (react/angular specialize browser; express specializes node. A project that runs in');\n console.error(' both the browser and node declares BOTH, e.g. framework:browser + framework:node.)');\n console.error(' This libType drives architecture/dependencies.json and the library-types-match-client rule.');\n console.error('');\n\n for (const project of untagged) {\n console.error(` ❌ ${project.name} — ${project.projectJsonPath}`);\n console.error(` add e.g. \"tags\": [\"${FRAMEWORK_TAG_PREFIX}browser\", \"${FRAMEWORK_TAG_PREFIX}node\"]`);\n }\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n}\n\nfunction reportInvalidValues(invalid: InvalidTagProject[], knownTypes: string[], mode: ProjectMode): void {\n const known = knownTypes.map((t: string) => `${FRAMEWORK_TAG_PREFIX}${t}`).join(' | ');\n console.error('');\n console.error('❌ Some modified projects carry an unknown framework tag value!');\n console.error('');\n console.error(` Allowed values: ${known}`);\n console.error('');\n\n for (const project of invalid) {\n console.error(` ❌ ${project.name} — ${project.projectJsonPath}`);\n for (const bad of project.badValues) {\n if (bad === REMOVED_ALL_VALUE) {\n console.error(\n ` framework:all is removed — declare the actual env set, ` +\n `e.g. framework:browser + framework:node`\n );\n } else {\n console.error(` unknown value \"${FRAMEWORK_TAG_PREFIX}${bad}\" — use one of: ${known}`);\n }\n }\n }\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n}\n\nconst FRAMEWORK_TAG_SPEC = new TagRuleSpec(\n FRAMEWORK_TAG_PREFIX,\n 'framework-tag',\n 'Framework Tag',\n DEFAULT_KNOWN_TYPES,\n reportViolations,\n true,\n reportInvalidValues\n);\n\n@injectable(bindingScopeValues.Singleton)\nexport class FrameworkTagValidator extends CodeValidator<FrameworkTagConfig> {\n constructor(config: FrameworkTagConfig) {\n super(config, 'framework-tag');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runTagValidator(this.config, workspaceRoot, FRAMEWORK_TAG_SPEC);\n }\n}\n"]}
@@ -49,7 +49,6 @@ const path = tslib_1.__importStar(require("path"));
49
49
  const ts = tslib_1.__importStar(require("typescript"));
50
50
  const rules_config_1 = require("@webpieces/rules-config");
51
51
  const code_validator_1 = require("./code-validator");
52
- const rules_config_2 = require("@webpieces/rules-config");
53
52
  const inversify_1 = require("inversify");
54
53
  const resolve_mode_1 = require("./resolve-mode");
55
54
  const RULE_NAME = rules_config_1.RULE_NAMES.INJECT_ANNOTATION_NOT_NEEDED_FOR_CONCRETE_CLASS;
@@ -269,8 +268,7 @@ let InjectAnnotationNotNeededForConcreteClassValidator = class InjectAnnotationN
269
268
  };
270
269
  exports.InjectAnnotationNotNeededForConcreteClassValidator = InjectAnnotationNotNeededForConcreteClassValidator;
271
270
  exports.InjectAnnotationNotNeededForConcreteClassValidator = InjectAnnotationNotNeededForConcreteClassValidator = tslib_1.__decorate([
272
- (0, rules_config_2.provideSingleton)(),
273
- (0, inversify_1.injectable)(),
271
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
274
272
  tslib_1.__metadata("design:paramtypes", [rules_config_1.InjectAnnotationNotNeededForConcreteClassConfig])
275
273
  ], InjectAnnotationNotNeededForConcreteClassValidator);
276
274
  //# sourceMappingURL=validate-inject-annotation-not-needed-for-concrete-class.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate-inject-annotation-not-needed-for-concrete-class.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-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9D,IAAA,+BAAgB,GAAE;IAClB,IAAA,sBAAU,GAAE;6CAEW,8DAA+C;GAD1D,kDAAkD,CAQ9D","sourcesContent":["/**\n * Validate Inject Annotation Not Needed For Concrete Class\n *\n * Flags a REDUNDANT `@inject(X)` on a CONSTRUCTOR parameter whose token is textually identical to the\n * parameter's own declared type:\n *\n * BAD: constructor(@inject(RequestContextHeaders) private readonly h: RequestContextHeaders) {}\n * GOOD: constructor(private readonly h: RequestContextHeaders) {}\n *\n * WHY: in this inversify setup a constructor parameter is auto-resolved by its class TYPE via\n * reflect-metadata (`emitDecoratorMetadata` emits `design:paramtypes`). So `private readonly h: Foo`\n * already binds `Foo` — the `@inject(Foo)` adds nothing (see CLAUDE.md, and the sibling\n * no-symbol-di-tokens rule that pushes the same inject-by-type pattern). AI keeps carpet-bombing\n * `@inject`; this fails the build on the redundant form so it stops.\n *\n * Uses the TypeScript AST (not a regex) so \"token equals the parameter type\" is decided precisely.\n * That single rule is what makes every LEGITIMATE token pass untouched — a real token never equals the\n * type it resolves:\n * - `@inject(TASK_PROXY_CLIENT_PROVIDER) x: Provider<TaskProxyClient>` (Symbol token ≠ type)\n * - `@inject(WEBPIECES_CONFIG_TOKEN) c: WebpiecesConfig` (Symbol ≠ interface type)\n * - `@inject('some-string') x: Foo` (string token ≠ type)\n * - `@inject(Symbol.for('X')) x: Foo` (not a bare identifier)\n *\n * SCOPE: only CONSTRUCTOR parameters. Property injection (`@inject(Foo) private foo: Foo` on a class\n * field) genuinely REQUIRES `@inject` in inversify — there is no design:type auto-wiring for properties\n * — so it is left alone.\n *\n * ALLOWED (skip — NOT violations)\n * - Any `@inject(TOKEN)` whose token differs from the parameter's type (Symbols, string tokens,\n * provider tokens, interface tokens).\n * - Property/field injection, and any parameter without an `@inject` decorator.\n * - Test files (*.test.ts, *.spec.ts, __tests__/**).\n * - Files under a configured `allowedPaths` glob (shared isPathExcluded glob/prefix/segment semantics).\n * - Lines with `// webpieces-disable inject-annotation-not-needed-for-concrete-class -- <reason>`\n * (only when disableAllowed).\n *\n * MODES (AST + LINE-SCOPED)\n * - OFF: Skip.\n * - NEW_AND_MODIFIED_CODE: Flag only on changed lines (diff hunks).\n * - NEW_AND_MODIFIED_FILES: Flag every occurrence in any modified file.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport { hasDisable, RULE_NAMES, InjectAnnotationNotNeededForConcreteClassConfig, ModifiedCodeMode, detectBase, getChangedFiles, getFileDiff, getChangedLineNumbers, isPathExcluded } from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { provideSingleton } from '@webpieces/rules-config';\nimport { injectable } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\n\nconst RULE_NAME = RULE_NAMES.INJECT_ANNOTATION_NOT_NEEDED_FOR_CONCRETE_CLASS;\n\nconst SHARED_MESSAGE = `@inject(Foo) on a constructor parameter typed \\`: Foo\\` is noise — inversify resolves a constructor\nparameter by its class type via reflect-metadata, so \\`private readonly foo: Foo\\` already binds it\n(see CLAUDE.md). Pick one:\n Fix Option 1 (PREFERRED): delete the decorator — constructor(private readonly foo: Foo) {}\n Fix Option 2: if you actually need a DIFFERENT binding token (a Symbol for a generated\n http-client-node / cloud-tasks client, or an interface/config with multiple impls), inject that\n token so it DIFFERS from the type: @inject(FOO_TOKEN) foo: SomeInterface.\nProperty injection (@inject on a class field, not a constructor param) is NOT flagged — it genuinely\nneeds @inject. Only a constructor param whose token equals its own type is redundant.`;\n\ninterface InjectViolation {\n file: string;\n line: number;\n column: number;\n context: string;\n}\n\ninterface InjectViolationInfo {\n line: number;\n column: number;\n context: string;\n hasDisableComment: boolean;\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction isTestFile(filePath: string): boolean {\n return filePath.includes('.spec.ts') || filePath.includes('.test.ts') || filePath.includes('__tests__/');\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction isDeclarationFile(filePath: string): boolean {\n return filePath.endsWith('.d.ts');\n}\n\n// The violation line (or the line just above it) carries the disable comment.\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction hasDisableOnLine(fileLines: string[], lineNumber: number): boolean {\n const current = fileLines[lineNumber - 1] ?? '';\n const previous = lineNumber >= 2 ? (fileLines[lineNumber - 2] ?? '') : '';\n return hasDisable(current, RULE_NAME) || hasDisable(previous, RULE_NAME);\n}\n\n// The `@inject(X)` decorator's single argument, when it is a BARE identifier (a class/token name).\n// Returns null for Symbol.for(...), property-access (`Symbol.x`), string literals, or a non-inject\n// decorator — those can never equal the parameter type, so they are never redundant.\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction injectIdentifierArg(decorator: ts.Decorator): string | null {\n const expr = decorator.expression;\n if (!ts.isCallExpression(expr)) return null;\n if (!ts.isIdentifier(expr.expression) || expr.expression.text !== 'inject') return null;\n if (expr.arguments.length !== 1) return null;\n const arg = expr.arguments[0];\n return arg && ts.isIdentifier(arg) ? arg.text : null;\n}\n\n// The parameter's declared type when it is a simple `TypeReference` with an identifier name\n// (`Foo`, or `Foo<Bar>` → `Foo`). Qualified names (`ns.Foo`) and non-references return null.\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction paramTypeName(param: ts.ParameterDeclaration): string | null {\n const typeNode = param.type;\n if (!typeNode || !ts.isTypeReferenceNode(typeNode)) return null;\n return ts.isIdentifier(typeNode.typeName) ? typeNode.typeName.text : null;\n}\n\n// AST scan: a CONSTRUCTOR parameter is a violation when it carries `@inject(X)` and its declared type\n// is exactly `X`. Property injection and method params are ignored (only constructor params).\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nexport function findRedundantInjectInSource(content: string, filePath: string, disableAllowed: boolean): InjectViolationInfo[] {\n if (isDeclarationFile(filePath)) return [];\n const fileLines = content.split('\\n');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n const violations: InjectViolationInfo[] = [];\n\n function checkParameter(param: ts.ParameterDeclaration): void {\n const decorators = ts.canHaveDecorators(param) ? ts.getDecorators(param) : undefined;\n if (!decorators) return;\n const typeName = paramTypeName(param);\n if (!typeName) return;\n for (const decorator of decorators) {\n if (injectIdentifierArg(decorator) === typeName) {\n recordViolation(param, `@inject(${typeName}) is redundant — the parameter is typed \\`: ${typeName}\\` and resolves by type`, fileLines, sourceFile, violations, disableAllowed);\n return;\n }\n }\n }\n\n function visit(node: ts.Node): void {\n if (ts.isConstructorDeclaration(node)) {\n for (const param of node.parameters) checkParameter(param);\n }\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return violations;\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction recordViolation(\n node: ts.Node,\n context: string,\n fileLines: string[],\n sourceFile: ts.SourceFile,\n violations: InjectViolationInfo[],\n disableAllowed: boolean,\n): void {\n const startPos = node.getStart(sourceFile);\n if (startPos < 0) return;\n const pos = sourceFile.getLineAndCharacterOfPosition(startPos);\n const line = pos.line + 1;\n const column = pos.character + 1;\n const disabled = hasDisableOnLine(fileLines, line);\n // When disableAllowed is false, a disable comment does NOT clear the violation.\n const effectiveDisabled = disableAllowed ? disabled : false;\n violations.push({ line, column, context, hasDisableComment: effectiveDisabled });\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction findRedundantInjectInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean, allowedPaths: string[]): InjectViolationInfo[] {\n if (isTestFile(filePath)) return [];\n if (isPathExcluded(filePath, allowedPaths)) return [];\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n const content = fs.readFileSync(fullPath, 'utf-8');\n return findRedundantInjectInSource(content, filePath, disableAllowed);\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction findViolationsForModifiedCode(workspaceRoot: string, changedFiles: string[], base: string, head: string | undefined, disableAllowed: boolean, allowedPaths: string[]): InjectViolation[] {\n const violations: InjectViolation[] = [];\n for (const file of changedFiles) {\n const changedLines = getChangedLineNumbers(getFileDiff(workspaceRoot, file, base, head));\n if (changedLines.size === 0) continue;\n for (const v of findRedundantInjectInFile(file, workspaceRoot, disableAllowed, allowedPaths)) {\n if (disableAllowed && v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n violations.push({ file, line: v.line, column: v.column, context: v.context });\n }\n }\n return violations;\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction findViolationsForModifiedFiles(workspaceRoot: string, changedFiles: string[], disableAllowed: boolean, allowedPaths: string[]): InjectViolation[] {\n const violations: InjectViolation[] = [];\n for (const file of changedFiles) {\n for (const v of findRedundantInjectInFile(file, workspaceRoot, disableAllowed, allowedPaths)) {\n if (disableAllowed && v.hasDisableComment) continue;\n violations.push({ file, line: v.line, column: v.column, context: v.context });\n }\n }\n return violations;\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction reportViolations(violations: InjectViolation[], mode: ModifiedCodeMode, disableAllowed: boolean): void {\n console.error('');\n console.error('❌ Redundant @inject — the parameter\\'s type already resolves it.');\n console.error('');\n console.error(SHARED_MESSAGE);\n console.error('');\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}:${v.column}`);\n console.error(` ${v.context}`);\n }\n console.error('');\n console.error(disableAllowed\n ? ` Escape hatch (use sparingly): // webpieces-disable ${RULE_NAME} -- <reason>`\n : ' Escape hatch: DISABLED (disableAllowed: false)');\n console.error(` Whole-tree exemption: add a glob to ${RULE_NAME}.allowedPaths in webpieces.config.json`);\n console.error(`\\n Current mode: ${mode}\\n`);\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction resolveMode(normalMode: ModifiedCodeMode, epoch: number | undefined, branchPattern: string | undefined): ModifiedCodeMode {\n if (normalMode === 'OFF') return normalMode;\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping ${RULE_NAME} validation (${skip.reason})\\n`);\n return 'OFF';\n }\n return normalMode;\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nasync function runValidatorImpl(options: InjectAnnotationNotNeededForConcreteClassConfig, workspaceRoot: string): Promise<ExecutorResult> {\n const mode: ModifiedCodeMode = resolveMode(options.mode ?? 'OFF', options.ignoreModifiedUntilEpoch, options.ignoreRuleWhileOnBranch);\n const disableAllowed = options.disableAllowed ?? true;\n const allowedPaths = options.allowedPaths ?? [];\n\n if (mode === 'OFF') {\n console.log(`\\n⏭️ Skipping ${RULE_NAME} validation (mode: OFF)\\n`);\n return { success: true };\n }\n\n console.log(`\\n📏 Validating ${RULE_NAME}\\n`);\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n if (!base) {\n console.log(`\\n⏭️ Skipping ${RULE_NAME} validation (could not detect base branch)\\n`);\n return { success: true };\n }\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\\n`);\n\n const changedFiles = getChangedFiles(workspaceRoot, base, head);\n if (changedFiles.length === 0) {\n console.log('✅ No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);\n\n let violations: InjectViolation[] = [];\n if (mode === 'NEW_AND_MODIFIED_CODE') {\n violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed, allowedPaths);\n } else if (mode === 'NEW_AND_MODIFIED_FILES') {\n violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed, allowedPaths);\n }\n\n if (violations.length === 0) {\n console.log('✅ No redundant-@inject violations found');\n return { success: true };\n }\n\n reportViolations(violations, mode, disableAllowed);\n return { success: false };\n}\n\n@provideSingleton()\n@injectable()\nexport class InjectAnnotationNotNeededForConcreteClassValidator extends CodeValidator<InjectAnnotationNotNeededForConcreteClassConfig> {\n constructor(config: InjectAnnotationNotNeededForConcreteClassConfig) {\n super(config, RULE_NAME);\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.config, workspaceRoot);\n }\n}\n"]}
1
+ {"version":3,"file":"validate-inject-annotation-not-needed-for-concrete-class.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-inject-annotation-not-needed-for-concrete-class.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;;;AA+EH,kEA4BC;;AAzGD,+CAAyB;AACzB,mDAA6B;AAC7B,uDAAiC;AACjC,0DAAqN;AACrN,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AAEhD,MAAM,SAAS,GAAG,yBAAU,CAAC,+CAA+C,CAAC;AAE7E,MAAM,cAAc,GAAG;;;;;;;;sFAQ+D,CAAC;AAgBvF,6HAA6H;AAC7H,SAAS,UAAU,CAAC,QAAgB;IAChC,OAAO,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC,IAAI,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC,IAAI,QAAQ,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;AAC7G,CAAC;AAED,6HAA6H;AAC7H,SAAS,iBAAiB,CAAC,QAAgB;IACvC,OAAO,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AACtC,CAAC;AAED,8EAA8E;AAC9E,6HAA6H;AAC7H,SAAS,gBAAgB,CAAC,SAAmB,EAAE,UAAkB;IAC7D,MAAM,OAAO,GAAG,SAAS,CAAC,UAAU,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;IAChD,MAAM,QAAQ,GAAG,UAAU,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,UAAU,GAAG,CAAC,CA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,IAAM,kDAAkD,GAAxD,MAAM,kDAAmD,SAAQ,8BAA8D;IAClI,YAAY,MAAuD;QAC/D,KAAK,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;IAC7B,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,OAAO,gBAAgB,CAAC,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxD,CAAC;CACJ,CAAA;AARY,gHAAkD;6DAAlD,kDAAkD;IAD9D,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,8DAA+C;GAD1D,kDAAkD,CAQ9D","sourcesContent":["/**\n * Validate Inject Annotation Not Needed For Concrete Class\n *\n * Flags a REDUNDANT `@inject(X)` on a CONSTRUCTOR parameter whose token is textually identical to the\n * parameter's own declared type:\n *\n * BAD: constructor(@inject(RequestContextHeaders) private readonly h: RequestContextHeaders) {}\n * GOOD: constructor(private readonly h: RequestContextHeaders) {}\n *\n * WHY: in this inversify setup a constructor parameter is auto-resolved by its class TYPE via\n * reflect-metadata (`emitDecoratorMetadata` emits `design:paramtypes`). So `private readonly h: Foo`\n * already binds `Foo` — the `@inject(Foo)` adds nothing (see CLAUDE.md, and the sibling\n * no-symbol-di-tokens rule that pushes the same inject-by-type pattern). AI keeps carpet-bombing\n * `@inject`; this fails the build on the redundant form so it stops.\n *\n * Uses the TypeScript AST (not a regex) so \"token equals the parameter type\" is decided precisely.\n * That single rule is what makes every LEGITIMATE token pass untouched — a real token never equals the\n * type it resolves:\n * - `@inject(TASK_PROXY_CLIENT_PROVIDER) x: Provider<TaskProxyClient>` (Symbol token ≠ type)\n * - `@inject(WEBPIECES_CONFIG_TOKEN) c: WebpiecesConfig` (Symbol ≠ interface type)\n * - `@inject('some-string') x: Foo` (string token ≠ type)\n * - `@inject(Symbol.for('X')) x: Foo` (not a bare identifier)\n *\n * SCOPE: only CONSTRUCTOR parameters. Property injection (`@inject(Foo) private foo: Foo` on a class\n * field) genuinely REQUIRES `@inject` in inversify — there is no design:type auto-wiring for properties\n * — so it is left alone.\n *\n * ALLOWED (skip — NOT violations)\n * - Any `@inject(TOKEN)` whose token differs from the parameter's type (Symbols, string tokens,\n * provider tokens, interface tokens).\n * - Property/field injection, and any parameter without an `@inject` decorator.\n * - Test files (*.test.ts, *.spec.ts, __tests__/**).\n * - Files under a configured `allowedPaths` glob (shared isPathExcluded glob/prefix/segment semantics).\n * - Lines with `// webpieces-disable inject-annotation-not-needed-for-concrete-class -- <reason>`\n * (only when disableAllowed).\n *\n * MODES (AST + LINE-SCOPED)\n * - OFF: Skip.\n * - NEW_AND_MODIFIED_CODE: Flag only on changed lines (diff hunks).\n * - NEW_AND_MODIFIED_FILES: Flag every occurrence in any modified file.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport { hasDisable, RULE_NAMES, InjectAnnotationNotNeededForConcreteClassConfig, ModifiedCodeMode, detectBase, getChangedFiles, getFileDiff, getChangedLineNumbers, isPathExcluded } from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\n\nconst RULE_NAME = RULE_NAMES.INJECT_ANNOTATION_NOT_NEEDED_FOR_CONCRETE_CLASS;\n\nconst SHARED_MESSAGE = `@inject(Foo) on a constructor parameter typed \\`: Foo\\` is noise — inversify resolves a constructor\nparameter by its class type via reflect-metadata, so \\`private readonly foo: Foo\\` already binds it\n(see CLAUDE.md). Pick one:\n Fix Option 1 (PREFERRED): delete the decorator — constructor(private readonly foo: Foo) {}\n Fix Option 2: if you actually need a DIFFERENT binding token (a Symbol for a generated\n http-client-node / cloud-tasks client, or an interface/config with multiple impls), inject that\n token so it DIFFERS from the type: @inject(FOO_TOKEN) foo: SomeInterface.\nProperty injection (@inject on a class field, not a constructor param) is NOT flagged — it genuinely\nneeds @inject. Only a constructor param whose token equals its own type is redundant.`;\n\ninterface InjectViolation {\n file: string;\n line: number;\n column: number;\n context: string;\n}\n\ninterface InjectViolationInfo {\n line: number;\n column: number;\n context: string;\n hasDisableComment: boolean;\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction isTestFile(filePath: string): boolean {\n return filePath.includes('.spec.ts') || filePath.includes('.test.ts') || filePath.includes('__tests__/');\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction isDeclarationFile(filePath: string): boolean {\n return filePath.endsWith('.d.ts');\n}\n\n// The violation line (or the line just above it) carries the disable comment.\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction hasDisableOnLine(fileLines: string[], lineNumber: number): boolean {\n const current = fileLines[lineNumber - 1] ?? '';\n const previous = lineNumber >= 2 ? (fileLines[lineNumber - 2] ?? '') : '';\n return hasDisable(current, RULE_NAME) || hasDisable(previous, RULE_NAME);\n}\n\n// The `@inject(X)` decorator's single argument, when it is a BARE identifier (a class/token name).\n// Returns null for Symbol.for(...), property-access (`Symbol.x`), string literals, or a non-inject\n// decorator — those can never equal the parameter type, so they are never redundant.\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction injectIdentifierArg(decorator: ts.Decorator): string | null {\n const expr = decorator.expression;\n if (!ts.isCallExpression(expr)) return null;\n if (!ts.isIdentifier(expr.expression) || expr.expression.text !== 'inject') return null;\n if (expr.arguments.length !== 1) return null;\n const arg = expr.arguments[0];\n return arg && ts.isIdentifier(arg) ? arg.text : null;\n}\n\n// The parameter's declared type when it is a simple `TypeReference` with an identifier name\n// (`Foo`, or `Foo<Bar>` → `Foo`). Qualified names (`ns.Foo`) and non-references return null.\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction paramTypeName(param: ts.ParameterDeclaration): string | null {\n const typeNode = param.type;\n if (!typeNode || !ts.isTypeReferenceNode(typeNode)) return null;\n return ts.isIdentifier(typeNode.typeName) ? typeNode.typeName.text : null;\n}\n\n// AST scan: a CONSTRUCTOR parameter is a violation when it carries `@inject(X)` and its declared type\n// is exactly `X`. Property injection and method params are ignored (only constructor params).\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nexport function findRedundantInjectInSource(content: string, filePath: string, disableAllowed: boolean): InjectViolationInfo[] {\n if (isDeclarationFile(filePath)) return [];\n const fileLines = content.split('\\n');\n const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);\n const violations: InjectViolationInfo[] = [];\n\n function checkParameter(param: ts.ParameterDeclaration): void {\n const decorators = ts.canHaveDecorators(param) ? ts.getDecorators(param) : undefined;\n if (!decorators) return;\n const typeName = paramTypeName(param);\n if (!typeName) return;\n for (const decorator of decorators) {\n if (injectIdentifierArg(decorator) === typeName) {\n recordViolation(param, `@inject(${typeName}) is redundant — the parameter is typed \\`: ${typeName}\\` and resolves by type`, fileLines, sourceFile, violations, disableAllowed);\n return;\n }\n }\n }\n\n function visit(node: ts.Node): void {\n if (ts.isConstructorDeclaration(node)) {\n for (const param of node.parameters) checkParameter(param);\n }\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return violations;\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction recordViolation(\n node: ts.Node,\n context: string,\n fileLines: string[],\n sourceFile: ts.SourceFile,\n violations: InjectViolationInfo[],\n disableAllowed: boolean,\n): void {\n const startPos = node.getStart(sourceFile);\n if (startPos < 0) return;\n const pos = sourceFile.getLineAndCharacterOfPosition(startPos);\n const line = pos.line + 1;\n const column = pos.character + 1;\n const disabled = hasDisableOnLine(fileLines, line);\n // When disableAllowed is false, a disable comment does NOT clear the violation.\n const effectiveDisabled = disableAllowed ? disabled : false;\n violations.push({ line, column, context, hasDisableComment: effectiveDisabled });\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction findRedundantInjectInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean, allowedPaths: string[]): InjectViolationInfo[] {\n if (isTestFile(filePath)) return [];\n if (isPathExcluded(filePath, allowedPaths)) return [];\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n const content = fs.readFileSync(fullPath, 'utf-8');\n return findRedundantInjectInSource(content, filePath, disableAllowed);\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction findViolationsForModifiedCode(workspaceRoot: string, changedFiles: string[], base: string, head: string | undefined, disableAllowed: boolean, allowedPaths: string[]): InjectViolation[] {\n const violations: InjectViolation[] = [];\n for (const file of changedFiles) {\n const changedLines = getChangedLineNumbers(getFileDiff(workspaceRoot, file, base, head));\n if (changedLines.size === 0) continue;\n for (const v of findRedundantInjectInFile(file, workspaceRoot, disableAllowed, allowedPaths)) {\n if (disableAllowed && v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n violations.push({ file, line: v.line, column: v.column, context: v.context });\n }\n }\n return violations;\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction findViolationsForModifiedFiles(workspaceRoot: string, changedFiles: string[], disableAllowed: boolean, allowedPaths: string[]): InjectViolation[] {\n const violations: InjectViolation[] = [];\n for (const file of changedFiles) {\n for (const v of findRedundantInjectInFile(file, workspaceRoot, disableAllowed, allowedPaths)) {\n if (disableAllowed && v.hasDisableComment) continue;\n violations.push({ file, line: v.line, column: v.column, context: v.context });\n }\n }\n return violations;\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction reportViolations(violations: InjectViolation[], mode: ModifiedCodeMode, disableAllowed: boolean): void {\n console.error('');\n console.error('❌ Redundant @inject — the parameter\\'s type already resolves it.');\n console.error('');\n console.error(SHARED_MESSAGE);\n console.error('');\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}:${v.column}`);\n console.error(` ${v.context}`);\n }\n console.error('');\n console.error(disableAllowed\n ? ` Escape hatch (use sparingly): // webpieces-disable ${RULE_NAME} -- <reason>`\n : ' Escape hatch: DISABLED (disableAllowed: false)');\n console.error(` Whole-tree exemption: add a glob to ${RULE_NAME}.allowedPaths in webpieces.config.json`);\n console.error(`\\n Current mode: ${mode}\\n`);\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nfunction resolveMode(normalMode: ModifiedCodeMode, epoch: number | undefined, branchPattern: string | undefined): ModifiedCodeMode {\n if (normalMode === 'OFF') return normalMode;\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping ${RULE_NAME} validation (${skip.reason})\\n`);\n return 'OFF';\n }\n return normalMode;\n}\n\n// webpieces-disable no-function-outside-class -- the rule engine is inherently functional; validators can't be class members\nasync function runValidatorImpl(options: InjectAnnotationNotNeededForConcreteClassConfig, workspaceRoot: string): Promise<ExecutorResult> {\n const mode: ModifiedCodeMode = resolveMode(options.mode ?? 'OFF', options.ignoreModifiedUntilEpoch, options.ignoreRuleWhileOnBranch);\n const disableAllowed = options.disableAllowed ?? true;\n const allowedPaths = options.allowedPaths ?? [];\n\n if (mode === 'OFF') {\n console.log(`\\n⏭️ Skipping ${RULE_NAME} validation (mode: OFF)\\n`);\n return { success: true };\n }\n\n console.log(`\\n📏 Validating ${RULE_NAME}\\n`);\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n if (!base) {\n console.log(`\\n⏭️ Skipping ${RULE_NAME} validation (could not detect base branch)\\n`);\n return { success: true };\n }\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\\n`);\n\n const changedFiles = getChangedFiles(workspaceRoot, base, head);\n if (changedFiles.length === 0) {\n console.log('✅ No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);\n\n let violations: InjectViolation[] = [];\n if (mode === 'NEW_AND_MODIFIED_CODE') {\n violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed, allowedPaths);\n } else if (mode === 'NEW_AND_MODIFIED_FILES') {\n violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed, allowedPaths);\n }\n\n if (violations.length === 0) {\n console.log('✅ No redundant-@inject violations found');\n return { success: true };\n }\n\n reportViolations(violations, mode, disableAllowed);\n return { success: false };\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class InjectAnnotationNotNeededForConcreteClassValidator extends CodeValidator<InjectAnnotationNotNeededForConcreteClassConfig> {\n constructor(config: InjectAnnotationNotNeededForConcreteClassConfig) {\n super(config, RULE_NAME);\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.config, workspaceRoot);\n }\n}\n"]}
@@ -14,7 +14,6 @@ const tslib_1 = require("tslib");
14
14
  const fs = tslib_1.__importStar(require("fs"));
15
15
  const path = tslib_1.__importStar(require("path"));
16
16
  const rules_config_1 = require("@webpieces/rules-config");
17
- const rules_config_2 = require("@webpieces/rules-config");
18
17
  const inversify_1 = require("inversify");
19
18
  class MatchViolation {
20
19
  file;
@@ -152,7 +151,6 @@ let MatchRulesChecker = class MatchRulesChecker {
152
151
  };
153
152
  exports.MatchRulesChecker = MatchRulesChecker;
154
153
  exports.MatchRulesChecker = MatchRulesChecker = tslib_1.__decorate([
155
- (0, rules_config_2.provideSingleton)(),
156
- (0, inversify_1.injectable)()
154
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton)
157
155
  ], MatchRulesChecker);
158
156
  //# sourceMappingURL=validate-match-rules.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate-match-rules.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-match-rules.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAYiC;AACjC,0DAA2D;AAC3D,yCAAuC;A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AAI,CAAC,IAAI,EAAE,CAAC;YACZ,OAAO,CAAC,GAAG,CAAC,kBAAkB,MAAM,CAAC,IAAI,gBAAgB,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC;YAC3E,OAAO,KAAK,CAAC;QACjB,CAAC;QACD,OAAO,UAAU,CAAC;IACtB,CAAC;CACJ,CAAA;AApIY,8CAAiB;4BAAjB,iBAAiB;IAF7B,IAAA,+BAAgB,GAAE;IAClB,IAAA,sBAAU,GAAE;GACA,iBAAiB,CAoI7B","sourcesContent":["/**\n * Validate `match-rules` entries (client-authored content guards) at build time.\n *\n * A config-free, injected checker: the {@link CodeRulesEngine} injects ONE MatchRulesChecker and runs\n * it once per `match-rules` entry (config passed to the method), so there is no `new` of a DAG member.\n * `shouldRun` / mode / epoch apply per entry and the report shows the entry name. The regex matching +\n * allowedPath/test-file exemption is shared with the ai-hook engine via findMatchRuleViolations; this\n * adds diff-scoping (mode), the `// webpieces-disable <name>` filter, and the console report.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n hasDisable,\n MatchRuleConfig,\n MatchRuleViolation,\n findMatchRuleViolations,\n renderMatchRuleMessage,\n ModifiedCodeMode,\n detectBase,\n getChangedFiles,\n getFileDiff,\n getChangedLineNumbers,\n shouldSkipRule,\n} from '@webpieces/rules-config';\nimport { provideSingleton } from '@webpieces/rules-config';\nimport { injectable } from 'inversify';\nimport { ExecutorResult } from './code-validator';\n\nclass MatchViolation {\n readonly file: string;\n readonly line: number;\n readonly context: string;\n\n constructor(file: string, line: number, context: string) {\n this.file = file;\n this.line = line;\n this.context = context;\n }\n}\n\nexport class MatchViolationInfo {\n readonly line: number;\n readonly context: string;\n readonly hasDisableComment: boolean;\n\n constructor(line: number, context: string, hasDisableComment: boolean) {\n this.line = line;\n this.context = context;\n this.hasDisableComment = hasDisableComment;\n }\n}\n\n@provideSingleton()\n@injectable()\nexport class MatchRulesChecker {\n /** True unless this entry is `mode: \"OFF\"` or skipped by a branch/epoch escape hatch. */\n shouldRun(config: MatchRuleConfig): boolean {\n if ((config.mode ?? 'OFF') === 'OFF') return false;\n return !shouldSkipRule(config.ignoreModifiedUntilEpoch, config.ignoreRuleWhileOnBranch).skip;\n }\n\n /** Run one `match-rules` entry against the workspace (per-entry mode/diff-scoping/report). */\n async runForConfig(config: MatchRuleConfig, workspaceRoot: string): Promise<ExecutorResult> {\n const mode = this.resolveMode(config);\n if (mode === 'OFF') {\n console.log(`\\n⏭️ Skipping ${config.name} validation (mode: OFF)\\n`);\n return { success: true };\n }\n\n console.log(`\\n📏 Validating match-rule: ${config.name}\\n`);\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n if (!base) {\n console.log(`\\n⏭️ Skipping ${config.name} validation (could not detect base branch)\\n`);\n return { success: true };\n }\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\\n`);\n\n const changedFiles = getChangedFiles(workspaceRoot, base, head);\n if (changedFiles.length === 0) {\n console.log('✅ No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);\n const violations = mode === 'NEW_AND_MODIFIED_CODE'\n ? this.findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, config)\n : this.findViolationsForModifiedFiles(workspaceRoot, changedFiles, config);\n\n if (violations.length === 0) {\n console.log(`✅ No ${config.name} violations found`);\n return { success: true };\n }\n\n this.reportViolations(config, violations, mode);\n return { success: false };\n }\n\n findViolationsInFile(filePath: string, workspaceRoot: string, config: MatchRuleConfig): MatchViolationInfo[] {\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const lines = content.split('\\n');\n\n // Shared engine applies allowedPaths + test-file exemption and regex matching.\n const hits = findMatchRuleViolations(lines, filePath, config);\n const disableAllowed = config.disableAllowed ?? true;\n\n return hits.map((hit: MatchRuleViolation) => {\n const line = lines[hit.line - 1] ?? '';\n const prevLine = hit.line > 1 ? (lines[hit.line - 2] ?? '') : '';\n const disabled = hasDisable(line, config.name) || hasDisable(prevLine, config.name);\n return new MatchViolationInfo(hit.line, hit.context, disableAllowed && disabled);\n });\n }\n\n private findViolationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n config: MatchRuleConfig,\n ): MatchViolation[] {\n const violations: MatchViolation[] = [];\n for (const file of changedFiles) {\n const diff = getFileDiff(workspaceRoot, file, base, head);\n const changedLines = getChangedLineNumbers(diff);\n if (changedLines.size === 0) continue;\n\n for (const v of this.findViolationsInFile(file, workspaceRoot, config)) {\n if (v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n violations.push(new MatchViolation(file, v.line, v.context));\n }\n }\n return violations;\n }\n\n private findViolationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n config: MatchRuleConfig,\n ): MatchViolation[] {\n const violations: MatchViolation[] = [];\n for (const file of changedFiles) {\n for (const v of this.findViolationsInFile(file, workspaceRoot, config)) {\n if (v.hasDisableComment) continue;\n violations.push(new MatchViolation(file, v.line, v.context));\n }\n }\n return violations;\n }\n\n private reportViolations(config: MatchRuleConfig, violations: MatchViolation[], mode: ModifiedCodeMode): void {\n console.error('');\n console.error(`❌ [${config.name}] matched disallowed pattern(s)!`);\n console.error('');\n console.error(renderMatchRuleMessage(config));\n console.error('');\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}`);\n console.error(` ${v.context}`);\n }\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n }\n\n private resolveMode(config: MatchRuleConfig): ModifiedCodeMode {\n const normalMode: ModifiedCodeMode = config.mode ?? 'OFF';\n if (normalMode === 'OFF') return normalMode;\n const skip = shouldSkipRule(config.ignoreModifiedUntilEpoch, config.ignoreRuleWhileOnBranch);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping ${config.name} validation (${skip.reason})\\n`);\n return 'OFF';\n }\n return normalMode;\n }\n}\n"]}
1
+ {"version":3,"file":"validate-match-rules.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-match-rules.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAYiC;AACjC,yCAA2D;AAG3D,MAAM,cAAc;IACP,IAAI,CAAS;IACb,IAAI,CAAS;IACb,OAAO,CAAS;IAEzB,YAAY,IAAY,EAAE,IAAY,EAAE,OAAe;QACnD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IAC3B,CAAC;CACJ;AAED,MAAa,kBAAkB;IAClB,IAAI,CAAS;IACb,OAAO,CAAS;IAChB,iBAAiB,CAAU;IAEpC,YAAY,IAAY,EAAE,OAAe,EAAE,iBAA0B;QACjE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;IAC/C,CAAC;CACJ;AAVD,gDAUC;AAGM,IAAM,iBAAiB,GAAvB,MAAM,iBAAiB;IAC1B,yFAAyF;IACzF,SAAS,CAAC,MAAuB;QAC7B,IAAI,CAAC,MAAM,CAAC,IAAI,IAAI,KAAK,CAAC,KAAK,KAAK;YAAE,OAAO,KAAK,CAAC;QACnD,OAAO,CAAC,IAAA,6BAAc,EAAC,MAAM,CAAC,wBAAwB,EAAE,MAAM,CAAC,uBAAuB,CAAC,CAAC,IAAI,CAAC;IACjG,CAAC;IAED,8FAA8F;IAC9F,KAAK,CAAC,YAAY,CAAC,MAAuB,EAAE,aAAqB;QAC7D,MAAM,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QACtC,IAAI,IAAI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AAC,MAAuB;QACvC,MAAM,UAAU,GAAqB,MAAM,CAAC,IAAI,IAAI,KAAK,CAAC;QAC1D,IAAI,UAAU,KAAK,KAAK;YAAE,OAAO,UAAU,CAAC;QAC5C,MAAM,IAAI,GAAG,IAAA,6BAAc,EAAC,MAAM,CAAC,wBAAwB,EAAE,MAAM,CAAC,uBAAuB,CAAC,CAAC;QAC7F,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YACZ,OAAO,CAAC,GAAG,CAAC,kBAAkB,MAAM,CAAC,IAAI,gBAAgB,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC;YAC3E,OAAO,KAAK,CAAC;QACjB,CAAC;QACD,OAAO,UAAU,CAAC;IACtB,CAAC;CACJ,CAAA;AApIY,8CAAiB;4BAAjB,iBAAiB;IAD7B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;GAC5B,iBAAiB,CAoI7B","sourcesContent":["/**\n * Validate `match-rules` entries (client-authored content guards) at build time.\n *\n * A config-free, injected checker: the {@link CodeRulesEngine} injects ONE MatchRulesChecker and runs\n * it once per `match-rules` entry (config passed to the method), so there is no `new` of a DAG member.\n * `shouldRun` / mode / epoch apply per entry and the report shows the entry name. The regex matching +\n * allowedPath/test-file exemption is shared with the ai-hook engine via findMatchRuleViolations; this\n * adds diff-scoping (mode), the `// webpieces-disable <name>` filter, and the console report.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n hasDisable,\n MatchRuleConfig,\n MatchRuleViolation,\n findMatchRuleViolations,\n renderMatchRuleMessage,\n ModifiedCodeMode,\n detectBase,\n getChangedFiles,\n getFileDiff,\n getChangedLineNumbers,\n shouldSkipRule,\n} from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { ExecutorResult } from './code-validator';\n\nclass MatchViolation {\n readonly file: string;\n readonly line: number;\n readonly context: string;\n\n constructor(file: string, line: number, context: string) {\n this.file = file;\n this.line = line;\n this.context = context;\n }\n}\n\nexport class MatchViolationInfo {\n readonly line: number;\n readonly context: string;\n readonly hasDisableComment: boolean;\n\n constructor(line: number, context: string, hasDisableComment: boolean) {\n this.line = line;\n this.context = context;\n this.hasDisableComment = hasDisableComment;\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class MatchRulesChecker {\n /** True unless this entry is `mode: \"OFF\"` or skipped by a branch/epoch escape hatch. */\n shouldRun(config: MatchRuleConfig): boolean {\n if ((config.mode ?? 'OFF') === 'OFF') return false;\n return !shouldSkipRule(config.ignoreModifiedUntilEpoch, config.ignoreRuleWhileOnBranch).skip;\n }\n\n /** Run one `match-rules` entry against the workspace (per-entry mode/diff-scoping/report). */\n async runForConfig(config: MatchRuleConfig, workspaceRoot: string): Promise<ExecutorResult> {\n const mode = this.resolveMode(config);\n if (mode === 'OFF') {\n console.log(`\\n⏭️ Skipping ${config.name} validation (mode: OFF)\\n`);\n return { success: true };\n }\n\n console.log(`\\n📏 Validating match-rule: ${config.name}\\n`);\n console.log(` Mode: ${mode}`);\n\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n if (!base) {\n console.log(`\\n⏭️ Skipping ${config.name} validation (could not detect base branch)\\n`);\n return { success: true };\n }\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}\\n`);\n\n const changedFiles = getChangedFiles(workspaceRoot, base, head);\n if (changedFiles.length === 0) {\n console.log('✅ No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`📂 Checking ${changedFiles.length} changed file(s)...`);\n const violations = mode === 'NEW_AND_MODIFIED_CODE'\n ? this.findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, config)\n : this.findViolationsForModifiedFiles(workspaceRoot, changedFiles, config);\n\n if (violations.length === 0) {\n console.log(`✅ No ${config.name} violations found`);\n return { success: true };\n }\n\n this.reportViolations(config, violations, mode);\n return { success: false };\n }\n\n findViolationsInFile(filePath: string, workspaceRoot: string, config: MatchRuleConfig): MatchViolationInfo[] {\n const fullPath = path.join(workspaceRoot, filePath);\n if (!fs.existsSync(fullPath)) return [];\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const lines = content.split('\\n');\n\n // Shared engine applies allowedPaths + test-file exemption and regex matching.\n const hits = findMatchRuleViolations(lines, filePath, config);\n const disableAllowed = config.disableAllowed ?? true;\n\n return hits.map((hit: MatchRuleViolation) => {\n const line = lines[hit.line - 1] ?? '';\n const prevLine = hit.line > 1 ? (lines[hit.line - 2] ?? '') : '';\n const disabled = hasDisable(line, config.name) || hasDisable(prevLine, config.name);\n return new MatchViolationInfo(hit.line, hit.context, disableAllowed && disabled);\n });\n }\n\n private findViolationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n config: MatchRuleConfig,\n ): MatchViolation[] {\n const violations: MatchViolation[] = [];\n for (const file of changedFiles) {\n const diff = getFileDiff(workspaceRoot, file, base, head);\n const changedLines = getChangedLineNumbers(diff);\n if (changedLines.size === 0) continue;\n\n for (const v of this.findViolationsInFile(file, workspaceRoot, config)) {\n if (v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n violations.push(new MatchViolation(file, v.line, v.context));\n }\n }\n return violations;\n }\n\n private findViolationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n config: MatchRuleConfig,\n ): MatchViolation[] {\n const violations: MatchViolation[] = [];\n for (const file of changedFiles) {\n for (const v of this.findViolationsInFile(file, workspaceRoot, config)) {\n if (v.hasDisableComment) continue;\n violations.push(new MatchViolation(file, v.line, v.context));\n }\n }\n return violations;\n }\n\n private reportViolations(config: MatchRuleConfig, violations: MatchViolation[], mode: ModifiedCodeMode): void {\n console.error('');\n console.error(`❌ [${config.name}] matched disallowed pattern(s)!`);\n console.error('');\n console.error(renderMatchRuleMessage(config));\n console.error('');\n for (const v of violations) {\n console.error(` ❌ ${v.file}:${v.line}`);\n console.error(` ${v.context}`);\n }\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n }\n\n private resolveMode(config: MatchRuleConfig): ModifiedCodeMode {\n const normalMode: ModifiedCodeMode = config.mode ?? 'OFF';\n if (normalMode === 'OFF') return normalMode;\n const skip = shouldSkipRule(config.ignoreModifiedUntilEpoch, config.ignoreRuleWhileOnBranch);\n if (skip.skip) {\n console.log(`\\n⏭️ Skipping ${config.name} validation (${skip.reason})\\n`);\n return 'OFF';\n }\n return normalMode;\n }\n}\n"]}
@@ -20,7 +20,6 @@ const fs = tslib_1.__importStar(require("fs"));
20
20
  const path = tslib_1.__importStar(require("path"));
21
21
  const rules_config_1 = require("@webpieces/rules-config");
22
22
  const code_validator_1 = require("./code-validator");
23
- const rules_config_2 = require("@webpieces/rules-config");
24
23
  const inversify_1 = require("inversify");
25
24
  const resolve_mode_1 = require("./resolve-mode");
26
25
  const TMP_MD_FILE = 'webpieces.filesize.md';
@@ -269,8 +268,7 @@ let MaxFileLinesValidator = class MaxFileLinesValidator extends code_validator_1
269
268
  };
270
269
  exports.MaxFileLinesValidator = MaxFileLinesValidator;
271
270
  exports.MaxFileLinesValidator = MaxFileLinesValidator = tslib_1.__decorate([
272
- (0, rules_config_2.provideSingleton)(),
273
- (0, inversify_1.injectable)(),
271
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
274
272
  tslib_1.__metadata("design:paramtypes", [rules_config_1.MaxFileLinesConfig])
275
273
  ], MaxFileLinesValidator);
276
274
  //# sourceMappingURL=validate-modified-files.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate-modified-files.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-modified-files.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;GAaG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAgJ;AAChJ,qDAAiE;AACjE,0DAA2D;AAC3D,yCAAuC;AACvC,iDAAgD;AAShD,MAAM,WAAW,GAAG,uBAAuB,CAAC;AAG5C;;;GAGG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AK,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;IACpC,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,OAAO,gBAAgB,CAAC,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxD,CAAC;CACJ,CAAA;AARY,sDAAqB;gCAArB,qBAAqB;IAFjC,IAAA,+BAAgB,GAAE;IAClB,IAAA,sBAAU,GAAE;6CAEW,iCAAkB;GAD7B,qBAAqB,CAQjC","sourcesContent":["/**\n * Validate Modified Files Executor\n *\n * Validates that modified files don't exceed a maximum line count (default 900).\n * This encourages keeping files small and focused - when you touch a file,\n * you must bring it under the limit.\n *\n * Usage:\n * nx affected --target=validate-modified-files --base=origin/main\n *\n * Escape hatch: Add webpieces-disable max-lines-modified-files comment with date and justification\n * Format: // webpieces-disable max-lines-modified-files 2025/01/15 -- [reason]\n * The disable expires after 1 month from the date specified.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { writeTemplate, hasDisable, RULE_NAMES, MaxFileLinesConfig, FileLimitMode, detectBase, getChangedFiles } from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { provideSingleton } from '@webpieces/rules-config';\nimport { injectable } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\n\ninterface FileViolation {\n file: string;\n lines: number;\n expiredDisable?: boolean;\n expiredDate?: string;\n}\n\nconst TMP_MD_FILE = 'webpieces.filesize.md';\n\n\n/**\n * Write the instructions documentation to .webpieces/instruct-ai/.\n * Sourced from @webpieces/rules-config.\n */\nfunction writeTmpInstructions(workspaceRoot: string): string {\n return writeTemplate(workspaceRoot, TMP_MD_FILE);\n}\n\n/**\n * Parse a date string in yyyy/mm/dd format and return a Date object.\n * Returns null if the format is invalid.\n */\nfunction parseDisableDate(dateStr: string): Date | null {\n // Match yyyy/mm/dd format\n const match = dateStr.match(/^(\\d{4})\\/(\\d{2})\\/(\\d{2})$/);\n if (!match) return null;\n\n const year = parseInt(match[1], 10);\n const month = parseInt(match[2], 10) - 1; // JS months are 0-indexed\n const day = parseInt(match[3], 10);\n\n const date = new Date(year, month, day);\n\n // Validate the date is valid (e.g., not Feb 30)\n if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) {\n return null;\n }\n\n return date;\n}\n\n/**\n * Check if a date is within the last month (not expired).\n */\nfunction isDateWithinMonth(date: Date): boolean {\n const now = new Date();\n const oneMonthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());\n return date >= oneMonthAgo;\n}\n\ninterface DisableStatus {\n hasDisable: boolean;\n isValid: boolean;\n isExpired: boolean;\n date?: string;\n}\n\n/**\n * Check if a file has a valid, non-expired disable comment at the top (within first 5 lines).\n * Returns status object with details about the disable comment.\n */\n// webpieces-disable max-lines-new-methods -- Date validation logic requires checking multiple conditions\nfunction checkDisableComment(content: string): DisableStatus {\n const lines = content.split('\\n').slice(0, 5);\n\n for (const line of lines) {\n if (hasDisable(line, RULE_NAMES.MAX_LINES_MODIFIED_FILES)) {\n // Found disable comment, now check for date\n // Format: // webpieces-disable max-lines-modified-files yyyy/mm/dd -- reason\n const dateMatch = line.match(/max-lines-modified-files\\s+(\\d{4}\\/\\d{2}\\/\\d{2}|XXXX\\/XX\\/XX)/);\n\n if (!dateMatch) {\n // No date found - invalid disable comment\n return { hasDisable: true, isValid: false, isExpired: false };\n }\n\n const dateStr = dateMatch[1];\n\n // Secret permanent disable\n if (dateStr === 'XXXX/XX/XX') {\n return { hasDisable: true, isValid: true, isExpired: false, date: dateStr };\n }\n\n const date = parseDisableDate(dateStr);\n if (!date) {\n // Invalid date format\n return { hasDisable: true, isValid: false, isExpired: false, date: dateStr };\n }\n\n if (!isDateWithinMonth(date)) {\n // Date is expired (older than 1 month)\n return { hasDisable: true, isValid: true, isExpired: true, date: dateStr };\n }\n\n // Valid and not expired\n return { hasDisable: true, isValid: true, isExpired: false, date: dateStr };\n }\n }\n\n return { hasDisable: false, isValid: false, isExpired: false };\n}\n\n/**\n * Count lines in a file and check for violations\n */\n// webpieces-disable max-lines-new-methods -- File iteration with disable checking logic\nfunction findViolations(workspaceRoot: string, changedFiles: string[], limit: number, disableAllowed: boolean): FileViolation[] {\n const violations: FileViolation[] = [];\n\n for (const file of changedFiles) {\n const fullPath = path.join(workspaceRoot, file);\n\n if (!fs.existsSync(fullPath)) continue;\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const lineCount = content.split('\\n').length;\n\n // Skip files under the limit\n if (lineCount <= limit) continue;\n\n // When disableAllowed is false, ignore all disable comments\n if (!disableAllowed) {\n violations.push({ file, lines: lineCount });\n continue;\n }\n\n // Check for disable comment\n const disableStatus = checkDisableComment(content);\n\n if (disableStatus.hasDisable) {\n if (disableStatus.isValid && !disableStatus.isExpired) {\n // Valid, non-expired disable - skip this file\n continue;\n }\n\n if (disableStatus.isExpired) {\n // Expired disable - report as violation with expired info\n violations.push({\n file,\n lines: lineCount,\n expiredDisable: true,\n expiredDate: disableStatus.date,\n });\n continue;\n }\n\n // Invalid disable (missing/bad date) - fall through to report as violation\n }\n\n violations.push({\n file,\n lines: lineCount,\n });\n }\n\n return violations;\n}\n\n/**\n * Get today's date in yyyy/mm/dd format for error messages\n */\nfunction getTodayDateString(): string {\n const now = new Date();\n const year = now.getFullYear();\n const month = String(now.getMonth() + 1).padStart(2, '0');\n const day = String(now.getDate()).padStart(2, '0');\n return `${year}/${month}/${day}`;\n}\n\n/**\n * Report violations to console\n */\n// webpieces-disable max-lines-new-methods -- Error output formatting with multiple message sections\nfunction reportViolations(violations: FileViolation[], limit: number, disableAllowed: boolean): void {\n console.error('');\n console.error('\\u274c YOU MUST FIX THIS AND NOT be more than ' + limit + ' lines of code per file');\n console.error(' as it slows down IDEs AND is VERY VERY EASY to refactor.');\n console.error('');\n console.error('\\ud83d\\udcda With stateless systems + dependency injection, refactor is trivial:');\n console.error(' Pick a method or a few and move to new class XXXXX, then inject XXXXX');\n console.error(' into all users of those methods via the constructor.');\n console.error(' Delete those methods from original class.');\n console.error(' 99% of files can be less than ' + limit + ' lines of code.');\n console.error('');\n console.error('\\u26a0\\ufe0f *** READ .webpieces/instruct-ai/webpieces.filesize.md for detailed guidance on how to fix this easily *** \\u26a0\\ufe0f');\n console.error('');\n\n for (const v of violations) {\n if (v.expiredDisable) {\n console.error(` \\u274c ${v.file} (${v.lines} lines, max: ${limit})`);\n console.error(` \\u23f0 EXPIRED DISABLE: Your disable comment dated ${v.expiredDate} has expired (>1 month old).`);\n console.error(` You must either FIX the file or UPDATE the date to get another month.`);\n } else {\n console.error(` \\u274c ${v.file} (${v.lines} lines, max: ${limit})`);\n }\n }\n console.error('');\n\n // Only show escape hatch instructions when disableAllowed is true\n if (disableAllowed) {\n console.error(' You can disable this error, but you will be forced to fix again in 1 month');\n console.error(' since 99% of files can be less than ' + limit + ' lines of code.');\n console.error('');\n console.error(' Use escape with DATE (expires in 1 month):');\n console.error(` // webpieces-disable max-lines-modified-files ${getTodayDateString()} -- [your reason]`);\n console.error('');\n } else {\n console.error(' \\u26a0\\ufe0f disableAllowed is false - disable comments are NOT allowed.');\n console.error(' This rule must be met and cannot be disabled since nx.json disableAllowed is set to false.');\n console.error(' You MUST refactor to reduce file size.');\n console.error('');\n console.error(' For a major refactor, a human can add \"ignoreModifiedUntilEpoch\" to nx.json validate-code options.');\n console.error(' This is an expiry timestamp (epoch ms) for when we start forcing everyone to meet size rules again.');\n console.error(' Sometimes for speed, we allow files to expand during a refactor and over time,');\n console.error(' each PR reduces files as they get touched.');\n console.error(' AI agents should NOT add ignoreModifiedUntilEpoch - ask a human to do it.');\n console.error('');\n }\n}\n\nasync function runValidatorImpl(\n options: MaxFileLinesConfig,\n workspaceRoot: string\n): Promise<ExecutorResult> {\n const limit = options.limit ?? 900;\n const disableAllowed = options.disableAllowed ?? true;\n\n const rawMode: FileLimitMode = options.mode ?? 'NEW_AND_MODIFIED_FILES';\n const skip = rawMode !== 'OFF' ? shouldSkipRule(options.ignoreModifiedUntilEpoch, options.ignoreRuleWhileOnBranch) : { skip: false };\n const mode: FileLimitMode = skip.skip ? 'OFF' : rawMode;\n\n // Skip validation entirely if mode is OFF\n if (mode === 'OFF') {\n const reason = skip.skip ? skip.reason : 'mode: OFF';\n console.log(`\\n\\u23ed\\ufe0f Skipping modified files validation (${reason})`);\n console.log('');\n return { success: true };\n }\n\n // If NX_HEAD is set (via nx affected --head=X), use it; otherwise compare to working tree\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n\n if (!base) {\n console.log('\\n\\u23ed\\ufe0f Skipping modified files validation (could not detect base branch)');\n console.log(' To run explicitly: nx affected --target=validate-modified-files --base=origin/main');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n\\ud83d\\udccf Validating Modified File Sizes (auto-detected base)\\n');\n } else {\n console.log('\\n\\ud83d\\udccf Validating Modified File Sizes\\n');\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);\n console.log(` Mode: ${mode}`);\n console.log(` Max lines for modified files: ${limit}`);\n console.log(` Disable allowed: ${disableAllowed}${!disableAllowed ? ' (no escape hatch)' : ''}`);\n console.log('');\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const changedFiles = getChangedFiles(workspaceRoot, base, head);\n\n if (changedFiles.length === 0) {\n console.log('\\u2705 No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`\\ud83d\\udcc2 Checking ${changedFiles.length} changed file(s)...`);\n\n const violations = findViolations(workspaceRoot, changedFiles, limit, disableAllowed);\n\n if (violations.length === 0) {\n console.log('\\u2705 All modified files are under ' + limit + ' lines');\n return { success: true };\n }\n\n writeTmpInstructions(workspaceRoot);\n reportViolations(violations, limit, disableAllowed);\n return { success: false };\n } catch (err: unknown) {\n //const error = toError(err);\n const error = err instanceof Error ? err : new Error(String(err));\n console.error('\\u274c Modified files validation failed:', error.message);\n return { success: false };\n }\n}\n\n@provideSingleton()\n@injectable()\nexport class MaxFileLinesValidator extends CodeValidator<MaxFileLinesConfig> {\n constructor(config: MaxFileLinesConfig) {\n super(config, 'max-file-lines');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.config, workspaceRoot);\n }\n}\n"]}
1
+ {"version":3,"file":"validate-modified-files.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-modified-files.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;GAaG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAgJ;AAChJ,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AAShD,MAAM,WAAW,GAAG,uBAAuB,CAAC;AAG5C;;;GAGG;AACH,SAAS,oBAAoB,CAAC,aAAqB;IAC/C,OAAO,IAAA,4BAAa,EAAC,aAAa,EAAE,WAAW,CAAC,CAAC;AACrD,CAAC;AAED;;;GAGG;AACH,SAAS,gBAAgB,CAAC,OAAe;IACrC,0BAA0B;IAC1B,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,6BAA6B,CAAC,CAAC;IAC3D,IAAI,CAAC,KAAK;QAAE,OAAO,IAAI,CAAC;IAExB,MAAM,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IACpC,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,0BAA0B;IACpE,MAAM,GAAG,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAEnC,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;IAExC,gDAAgD;IAChD,IAAI,IAAI,CAAC,WAAW,EAAE,KAAK,IAAI,IAAI,IAAI,CAAC,QAAQ,EAAE,KAAK,KAAK,IAAI,IAAI,CAAC,OAAO,E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AAK,EAAE,CAAC;IAC9B,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,6BAA6B;QAC7B,MAAM,KAAK,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;QAClE,OAAO,CAAC,KAAK,CAAC,0CAA0C,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QACzE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;AACL,CAAC;AAGM,IAAM,qBAAqB,GAA3B,MAAM,qBAAsB,SAAQ,8BAAiC;IACxE,YAAY,MAA0B;QAClC,KAAK,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;IACpC,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,OAAO,gBAAgB,CAAC,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxD,CAAC;CACJ,CAAA;AARY,sDAAqB;gCAArB,qBAAqB;IADjC,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,iCAAkB;GAD7B,qBAAqB,CAQjC","sourcesContent":["/**\n * Validate Modified Files Executor\n *\n * Validates that modified files don't exceed a maximum line count (default 900).\n * This encourages keeping files small and focused - when you touch a file,\n * you must bring it under the limit.\n *\n * Usage:\n * nx affected --target=validate-modified-files --base=origin/main\n *\n * Escape hatch: Add webpieces-disable max-lines-modified-files comment with date and justification\n * Format: // webpieces-disable max-lines-modified-files 2025/01/15 -- [reason]\n * The disable expires after 1 month from the date specified.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { writeTemplate, hasDisable, RULE_NAMES, MaxFileLinesConfig, FileLimitMode, detectBase, getChangedFiles } from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\n\ninterface FileViolation {\n file: string;\n lines: number;\n expiredDisable?: boolean;\n expiredDate?: string;\n}\n\nconst TMP_MD_FILE = 'webpieces.filesize.md';\n\n\n/**\n * Write the instructions documentation to .webpieces/instruct-ai/.\n * Sourced from @webpieces/rules-config.\n */\nfunction writeTmpInstructions(workspaceRoot: string): string {\n return writeTemplate(workspaceRoot, TMP_MD_FILE);\n}\n\n/**\n * Parse a date string in yyyy/mm/dd format and return a Date object.\n * Returns null if the format is invalid.\n */\nfunction parseDisableDate(dateStr: string): Date | null {\n // Match yyyy/mm/dd format\n const match = dateStr.match(/^(\\d{4})\\/(\\d{2})\\/(\\d{2})$/);\n if (!match) return null;\n\n const year = parseInt(match[1], 10);\n const month = parseInt(match[2], 10) - 1; // JS months are 0-indexed\n const day = parseInt(match[3], 10);\n\n const date = new Date(year, month, day);\n\n // Validate the date is valid (e.g., not Feb 30)\n if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) {\n return null;\n }\n\n return date;\n}\n\n/**\n * Check if a date is within the last month (not expired).\n */\nfunction isDateWithinMonth(date: Date): boolean {\n const now = new Date();\n const oneMonthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());\n return date >= oneMonthAgo;\n}\n\ninterface DisableStatus {\n hasDisable: boolean;\n isValid: boolean;\n isExpired: boolean;\n date?: string;\n}\n\n/**\n * Check if a file has a valid, non-expired disable comment at the top (within first 5 lines).\n * Returns status object with details about the disable comment.\n */\n// webpieces-disable max-lines-new-methods -- Date validation logic requires checking multiple conditions\nfunction checkDisableComment(content: string): DisableStatus {\n const lines = content.split('\\n').slice(0, 5);\n\n for (const line of lines) {\n if (hasDisable(line, RULE_NAMES.MAX_LINES_MODIFIED_FILES)) {\n // Found disable comment, now check for date\n // Format: // webpieces-disable max-lines-modified-files yyyy/mm/dd -- reason\n const dateMatch = line.match(/max-lines-modified-files\\s+(\\d{4}\\/\\d{2}\\/\\d{2}|XXXX\\/XX\\/XX)/);\n\n if (!dateMatch) {\n // No date found - invalid disable comment\n return { hasDisable: true, isValid: false, isExpired: false };\n }\n\n const dateStr = dateMatch[1];\n\n // Secret permanent disable\n if (dateStr === 'XXXX/XX/XX') {\n return { hasDisable: true, isValid: true, isExpired: false, date: dateStr };\n }\n\n const date = parseDisableDate(dateStr);\n if (!date) {\n // Invalid date format\n return { hasDisable: true, isValid: false, isExpired: false, date: dateStr };\n }\n\n if (!isDateWithinMonth(date)) {\n // Date is expired (older than 1 month)\n return { hasDisable: true, isValid: true, isExpired: true, date: dateStr };\n }\n\n // Valid and not expired\n return { hasDisable: true, isValid: true, isExpired: false, date: dateStr };\n }\n }\n\n return { hasDisable: false, isValid: false, isExpired: false };\n}\n\n/**\n * Count lines in a file and check for violations\n */\n// webpieces-disable max-lines-new-methods -- File iteration with disable checking logic\nfunction findViolations(workspaceRoot: string, changedFiles: string[], limit: number, disableAllowed: boolean): FileViolation[] {\n const violations: FileViolation[] = [];\n\n for (const file of changedFiles) {\n const fullPath = path.join(workspaceRoot, file);\n\n if (!fs.existsSync(fullPath)) continue;\n\n const content = fs.readFileSync(fullPath, 'utf-8');\n const lineCount = content.split('\\n').length;\n\n // Skip files under the limit\n if (lineCount <= limit) continue;\n\n // When disableAllowed is false, ignore all disable comments\n if (!disableAllowed) {\n violations.push({ file, lines: lineCount });\n continue;\n }\n\n // Check for disable comment\n const disableStatus = checkDisableComment(content);\n\n if (disableStatus.hasDisable) {\n if (disableStatus.isValid && !disableStatus.isExpired) {\n // Valid, non-expired disable - skip this file\n continue;\n }\n\n if (disableStatus.isExpired) {\n // Expired disable - report as violation with expired info\n violations.push({\n file,\n lines: lineCount,\n expiredDisable: true,\n expiredDate: disableStatus.date,\n });\n continue;\n }\n\n // Invalid disable (missing/bad date) - fall through to report as violation\n }\n\n violations.push({\n file,\n lines: lineCount,\n });\n }\n\n return violations;\n}\n\n/**\n * Get today's date in yyyy/mm/dd format for error messages\n */\nfunction getTodayDateString(): string {\n const now = new Date();\n const year = now.getFullYear();\n const month = String(now.getMonth() + 1).padStart(2, '0');\n const day = String(now.getDate()).padStart(2, '0');\n return `${year}/${month}/${day}`;\n}\n\n/**\n * Report violations to console\n */\n// webpieces-disable max-lines-new-methods -- Error output formatting with multiple message sections\nfunction reportViolations(violations: FileViolation[], limit: number, disableAllowed: boolean): void {\n console.error('');\n console.error('\\u274c YOU MUST FIX THIS AND NOT be more than ' + limit + ' lines of code per file');\n console.error(' as it slows down IDEs AND is VERY VERY EASY to refactor.');\n console.error('');\n console.error('\\ud83d\\udcda With stateless systems + dependency injection, refactor is trivial:');\n console.error(' Pick a method or a few and move to new class XXXXX, then inject XXXXX');\n console.error(' into all users of those methods via the constructor.');\n console.error(' Delete those methods from original class.');\n console.error(' 99% of files can be less than ' + limit + ' lines of code.');\n console.error('');\n console.error('\\u26a0\\ufe0f *** READ .webpieces/instruct-ai/webpieces.filesize.md for detailed guidance on how to fix this easily *** \\u26a0\\ufe0f');\n console.error('');\n\n for (const v of violations) {\n if (v.expiredDisable) {\n console.error(` \\u274c ${v.file} (${v.lines} lines, max: ${limit})`);\n console.error(` \\u23f0 EXPIRED DISABLE: Your disable comment dated ${v.expiredDate} has expired (>1 month old).`);\n console.error(` You must either FIX the file or UPDATE the date to get another month.`);\n } else {\n console.error(` \\u274c ${v.file} (${v.lines} lines, max: ${limit})`);\n }\n }\n console.error('');\n\n // Only show escape hatch instructions when disableAllowed is true\n if (disableAllowed) {\n console.error(' You can disable this error, but you will be forced to fix again in 1 month');\n console.error(' since 99% of files can be less than ' + limit + ' lines of code.');\n console.error('');\n console.error(' Use escape with DATE (expires in 1 month):');\n console.error(` // webpieces-disable max-lines-modified-files ${getTodayDateString()} -- [your reason]`);\n console.error('');\n } else {\n console.error(' \\u26a0\\ufe0f disableAllowed is false - disable comments are NOT allowed.');\n console.error(' This rule must be met and cannot be disabled since nx.json disableAllowed is set to false.');\n console.error(' You MUST refactor to reduce file size.');\n console.error('');\n console.error(' For a major refactor, a human can add \"ignoreModifiedUntilEpoch\" to nx.json validate-code options.');\n console.error(' This is an expiry timestamp (epoch ms) for when we start forcing everyone to meet size rules again.');\n console.error(' Sometimes for speed, we allow files to expand during a refactor and over time,');\n console.error(' each PR reduces files as they get touched.');\n console.error(' AI agents should NOT add ignoreModifiedUntilEpoch - ask a human to do it.');\n console.error('');\n }\n}\n\nasync function runValidatorImpl(\n options: MaxFileLinesConfig,\n workspaceRoot: string\n): Promise<ExecutorResult> {\n const limit = options.limit ?? 900;\n const disableAllowed = options.disableAllowed ?? true;\n\n const rawMode: FileLimitMode = options.mode ?? 'NEW_AND_MODIFIED_FILES';\n const skip = rawMode !== 'OFF' ? shouldSkipRule(options.ignoreModifiedUntilEpoch, options.ignoreRuleWhileOnBranch) : { skip: false };\n const mode: FileLimitMode = skip.skip ? 'OFF' : rawMode;\n\n // Skip validation entirely if mode is OFF\n if (mode === 'OFF') {\n const reason = skip.skip ? skip.reason : 'mode: OFF';\n console.log(`\\n\\u23ed\\ufe0f Skipping modified files validation (${reason})`);\n console.log('');\n return { success: true };\n }\n\n // If NX_HEAD is set (via nx affected --head=X), use it; otherwise compare to working tree\n let base = process.env['NX_BASE'];\n const head = process.env['NX_HEAD'];\n\n if (!base) {\n base = detectBase(workspaceRoot) ?? undefined;\n\n if (!base) {\n console.log('\\n\\u23ed\\ufe0f Skipping modified files validation (could not detect base branch)');\n console.log(' To run explicitly: nx affected --target=validate-modified-files --base=origin/main');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n\\ud83d\\udccf Validating Modified File Sizes (auto-detected base)\\n');\n } else {\n console.log('\\n\\ud83d\\udccf Validating Modified File Sizes\\n');\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);\n console.log(` Mode: ${mode}`);\n console.log(` Max lines for modified files: ${limit}`);\n console.log(` Disable allowed: ${disableAllowed}${!disableAllowed ? ' (no escape hatch)' : ''}`);\n console.log('');\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const changedFiles = getChangedFiles(workspaceRoot, base, head);\n\n if (changedFiles.length === 0) {\n console.log('\\u2705 No TypeScript files changed');\n return { success: true };\n }\n\n console.log(`\\ud83d\\udcc2 Checking ${changedFiles.length} changed file(s)...`);\n\n const violations = findViolations(workspaceRoot, changedFiles, limit, disableAllowed);\n\n if (violations.length === 0) {\n console.log('\\u2705 All modified files are under ' + limit + ' lines');\n return { success: true };\n }\n\n writeTmpInstructions(workspaceRoot);\n reportViolations(violations, limit, disableAllowed);\n return { success: false };\n } catch (err: unknown) {\n //const error = toError(err);\n const error = err instanceof Error ? err : new Error(String(err));\n console.error('\\u274c Modified files validation failed:', error.message);\n return { success: false };\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class MaxFileLinesValidator extends CodeValidator<MaxFileLinesConfig> {\n constructor(config: MaxFileLinesConfig) {\n super(config, 'max-file-lines');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.config, workspaceRoot);\n }\n}\n"]}