@webpieces/code-rules 0.4.818 → 0.4.820

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 (84) hide show
  1. package/package.json +2 -2
  2. package/src/api-lib-source-rule.d.ts +5 -2
  3. package/src/api-lib-source-rule.js +8 -4
  4. package/src/api-lib-source-rule.js.map +1 -1
  5. package/src/cli.js +13 -14
  6. package/src/cli.js.map +1 -1
  7. package/src/code-rules-bootstrap.d.ts +31 -8
  8. package/src/code-rules-bootstrap.js +136 -18
  9. package/src/code-rules-bootstrap.js.map +1 -1
  10. package/src/code-rules-config-table.d.ts +3 -1
  11. package/src/code-rules-config-table.js +0 -6
  12. package/src/code-rules-config-table.js.map +1 -1
  13. package/src/code-rules-engine.d.ts +4 -13
  14. package/src/code-rules-engine.js +9 -31
  15. package/src/code-rules-engine.js.map +1 -1
  16. package/src/code-rules-run-request.d.ts +30 -34
  17. package/src/code-rules-run-request.js +43 -80
  18. package/src/code-rules-run-request.js.map +1 -1
  19. package/src/index.d.ts +4 -2
  20. package/src/index.js +14 -3
  21. package/src/index.js.map +1 -1
  22. package/src/scan-scope.d.ts +82 -0
  23. package/src/scan-scope.js +200 -0
  24. package/src/scan-scope.js.map +1 -0
  25. package/src/validate-catch-error-pattern.d.ts +3 -1
  26. package/src/validate-catch-error-pattern.js +11 -6
  27. package/src/validate-catch-error-pattern.js.map +1 -1
  28. package/src/validate-code.d.ts +4 -5
  29. package/src/validate-code.js +6 -17
  30. package/src/validate-code.js.map +1 -1
  31. package/src/validate-inject-annotation-not-needed-for-concrete-class.d.ts +3 -1
  32. package/src/validate-inject-annotation-not-needed-for-concrete-class.js +11 -6
  33. package/src/validate-inject-annotation-not-needed-for-concrete-class.js.map +1 -1
  34. package/src/validate-match-rules.d.ts +3 -0
  35. package/src/validate-match-rules.js +10 -3
  36. package/src/validate-match-rules.js.map +1 -1
  37. package/src/validate-no-any-unknown.d.ts +3 -1
  38. package/src/validate-no-any-unknown.js +11 -6
  39. package/src/validate-no-any-unknown.js.map +1 -1
  40. package/src/validate-no-client-creation-outside-server-or-client.d.ts +4 -2
  41. package/src/validate-no-client-creation-outside-server-or-client.js +10 -5
  42. package/src/validate-no-client-creation-outside-server-or-client.js.map +1 -1
  43. package/src/validate-no-custom-css.d.ts +4 -2
  44. package/src/validate-no-custom-css.js +9 -5
  45. package/src/validate-no-custom-css.js.map +1 -1
  46. package/src/validate-no-destructure.d.ts +3 -1
  47. package/src/validate-no-destructure.js +11 -6
  48. package/src/validate-no-destructure.js.map +1 -1
  49. package/src/validate-no-function-outside-class.d.ts +3 -1
  50. package/src/validate-no-function-outside-class.js +12 -6
  51. package/src/validate-no-function-outside-class.js.map +1 -1
  52. package/src/validate-no-implicit-any.d.ts +3 -1
  53. package/src/validate-no-implicit-any.js +13 -8
  54. package/src/validate-no-implicit-any.js.map +1 -1
  55. package/src/validate-no-inline-import-in-api-lib.d.ts +2 -1
  56. package/src/validate-no-inline-import-in-api-lib.js +4 -3
  57. package/src/validate-no-inline-import-in-api-lib.js.map +1 -1
  58. package/src/validate-no-process-exit-outside-main.d.ts +3 -1
  59. package/src/validate-no-process-exit-outside-main.js +12 -6
  60. package/src/validate-no-process-exit-outside-main.js.map +1 -1
  61. package/src/validate-no-state-paths-in-templates.d.ts +4 -2
  62. package/src/validate-no-state-paths-in-templates.js +9 -5
  63. package/src/validate-no-state-paths-in-templates.js.map +1 -1
  64. package/src/validate-no-symbol-di-tokens.d.ts +3 -1
  65. package/src/validate-no-symbol-di-tokens.js +11 -6
  66. package/src/validate-no-symbol-di-tokens.js.map +1 -1
  67. package/src/validate-no-unmanaged-exceptions.d.ts +3 -1
  68. package/src/validate-no-unmanaged-exceptions.js +11 -6
  69. package/src/validate-no-unmanaged-exceptions.js.map +1 -1
  70. package/src/validate-no-utility-types-in-api-lib.d.ts +2 -1
  71. package/src/validate-no-utility-types-in-api-lib.js +4 -3
  72. package/src/validate-no-utility-types-in-api-lib.js.map +1 -1
  73. package/src/validate-one-enum-spelling-in-api-lib.d.ts +2 -1
  74. package/src/validate-one-enum-spelling-in-api-lib.js +4 -3
  75. package/src/validate-one-enum-spelling-in-api-lib.js.map +1 -1
  76. package/src/validate-required-type-suffix.d.ts +13 -27
  77. package/src/validate-required-type-suffix.js +25 -52
  78. package/src/validate-required-type-suffix.js.map +1 -1
  79. package/src/debug-run-report.d.ts +0 -22
  80. package/src/debug-run-report.js +0 -127
  81. package/src/debug-run-report.js.map +0 -1
  82. package/src/rule-scope-plan.d.ts +0 -72
  83. package/src/rule-scope-plan.js +0 -132
  84. package/src/rule-scope-plan.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"validate-no-unmanaged-exceptions.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-unmanaged-exceptions.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAiL;AACjL,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AAQhD;;;GAGG;AACH,SAAS,iBAAiB,CAAC,KAAe,EAAE,UAAkB;IAC1D,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,UAAU,GAAG,CAAC,CAAC,CAAC;IAC/C,KAAK,IAAI,CAAC,GAAG,UAAU,GAAG,CAAC,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,EAAE,EAAE,CAAC;QAChD,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;QACpC,IAAI,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;YAClF,MAAM;QACV,CAAC;QACD,IAAI,IAAA,yBAAU,EAAC,IAAI,EAAE,yBAAU,CAAC,uBAAuB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","sourcesContent":["/**\n * Validate No Unmanaged Exceptions Executor\n *\n * Validates that try/catch blocks are not used outside chokepoints.\n * Uses LINE-BASED detection (not method-based) for git diff filtering.\n *\n * ============================================================================\n * VIOLATIONS (BAD) - These patterns are flagged:\n * ============================================================================\n *\n * - try { — any try/catch block in non-test code\n *\n * ============================================================================\n * ALLOWED (skip — NOT violations)\n * ============================================================================\n *\n * - Test files (.spec.ts, .test.ts, __tests__/)\n * - Lines with // webpieces-disable no-unmanaged-exceptions -- [reason]\n *\n * ============================================================================\n * MODES (LINE-BASED)\n * ============================================================================\n * - OFF: Skip validation entirely\n * - NEW_AND_MODIFIED_CODE: Flag try/catch on changed lines (lines in diff hunks)\n * - NEW_AND_MODIFIED_FILES: Flag ALL try/catch in files that were modified\n *\n * ============================================================================\n * ESCAPE HATCH\n * ============================================================================\n * Add comment above the violation:\n * // webpieces-disable no-unmanaged-exceptions -- [your justification]\n * try {\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { hasDisable, RULE_NAMES, NoUnmanagedExceptionsConfig, ModifiedCodeMode, 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 TryCatchViolation {\n file: string;\n line: number;\n context: string;\n}\n\n/**\n * Check if a line contains a disable comment for no-unmanaged-exceptions.\n * Recognizes both webpieces-disable and eslint-disable-next-line @webpieces/ formats.\n */\nfunction hasDisableComment(lines: string[], lineNumber: number): boolean {\n const startCheck = Math.max(0, lineNumber - 5);\n for (let i = lineNumber - 2; i >= startCheck; i--) {\n const line = lines[i]?.trim() ?? '';\n if (line.startsWith('function ') || line.startsWith('class ') || line.endsWith('}')) {\n break;\n }\n if (hasDisable(line, RULE_NAMES.NO_UNMANAGED_EXCEPTIONS)) {\n return true;\n }\n if (line.includes('@webpieces/no-unmanaged-exceptions')) {\n return true;\n }\n }\n return false;\n}\n\nconst TRY_PATTERN = /\\btry\\s*\\{/;\n\ninterface TryCatchInfo {\n line: number;\n context: string;\n hasDisableComment: boolean;\n}\n\n/**\n * Find all try/catch patterns in a file using line-based scanning.\n */\nfunction findTryCatchInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean): TryCatchInfo[] {\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 violations: TryCatchInfo[] = [];\n\n for (let i = 0; i < fileLines.length; i++) {\n const line = fileLines[i];\n const trimmed = line.trim();\n // Skip comment lines (JSDoc, block comments, line comments)\n if (trimmed.startsWith('*') || trimmed.startsWith('//') || trimmed.startsWith('/*')) continue;\n if (!TRY_PATTERN.test(line)) continue;\n\n const lineNum = i + 1;\n const disabled = hasDisableComment(fileLines, lineNum);\n\n if (!disableAllowed && disabled) {\n violations.push({ line: lineNum, context: line.trim(), hasDisableComment: false });\n } else {\n violations.push({ line: lineNum, context: line.trim(), hasDisableComment: disabled });\n }\n }\n\n return violations;\n}\n\n/**\n * NEW_AND_MODIFIED_CODE mode: Flag violations on changed lines in diff hunks.\n */\nfunction findViolationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean,\n): TryCatchViolation[] {\n const violations: TryCatchViolation[] = [];\n\n for (const file of changedFiles) {\n const diff = getFileDiff(workspaceRoot, file, base, head);\n const changedLines = getChangedLineNumbers(diff);\n\n if (changedLines.size === 0) continue;\n\n const allViolations = findTryCatchInFile(file, workspaceRoot, disableAllowed);\n\n for (const v of allViolations) {\n if (disableAllowed && v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n\n violations.push({ file, line: v.line, context: v.context });\n }\n }\n\n return violations;\n}\n\n/**\n * NEW_AND_MODIFIED_FILES mode: Flag ALL violations in files that were modified.\n */\nfunction findViolationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n disableAllowed: boolean,\n): TryCatchViolation[] {\n const violations: TryCatchViolation[] = [];\n\n for (const file of changedFiles) {\n const allViolations = findTryCatchInFile(file, workspaceRoot, disableAllowed);\n\n for (const v of allViolations) {\n if (disableAllowed && v.hasDisableComment) continue;\n violations.push({ file, line: v.line, context: v.context });\n }\n }\n\n return violations;\n}\n\n/**\n * Report violations to console.\n */\nfunction reportViolations(violations: TryCatchViolation[], mode: ModifiedCodeMode, disableAllowed: boolean): void {\n console.error('');\n console.error('\\u274c Unmanaged try/catch blocks found! Exceptions should bubble to chokepoints.');\n console.error('');\n console.error('\\ud83d\\udcda Philosophy: Most code should NOT catch exceptions.');\n console.error(' Exceptions should bubble to chokepoints (filter in Node.js, globalErrorHandler in Angular)');\n console.error(' where they are logged with traceId for debugging.');\n console.error('');\n\n for (const v of violations) {\n console.error(` \\u274c ${v.file}:${v.line}`);\n console.error(` ${v.context}`);\n }\n console.error('');\n\n if (disableAllowed) {\n console.error(' Escape hatch (use sparingly):');\n console.error(' // webpieces-disable no-unmanaged-exceptions -- [your reason]');\n console.error('');\n console.error(' When try/catch IS used, the catch block MUST follow:');\n console.error(' catch (err: unknown) { const error = toError(err); ... }');\n console.error(' or: catch (err: unknown) { //const error = toError(err); }');\n } else {\n console.error(' Escape hatch: DISABLED (disableAllowed: false)');\n console.error(' Disable comments are ignored. Remove the try/catch.');\n }\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n}\n\n/**\n * Resolve mode considering turnOffRuleUntilEpoch override.\n */\nfunction resolveMode(normalMode: ModifiedCodeMode, epoch: number | undefined, branchPattern: string | undefined): ModifiedCodeMode {\n if (normalMode === 'OFF') {\n return normalMode;\n }\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n\\u23ed\\ufe0f Skipping no-unmanaged-exceptions validation (${skip.reason})`);\n console.log('');\n return 'OFF';\n }\n return normalMode;\n}\n\nasync function runValidatorImpl(\n options: NoUnmanagedExceptionsConfig,\n workspaceRoot: string\n): Promise<ExecutorResult> {\n const mode: ModifiedCodeMode = resolveMode(options.mode ?? 'OFF', options.turnOffRuleUntilEpoch, (options.turnOffRuleWhileOnBranch ?? undefined));\n const disableAllowed = options.disableAllowed ?? true;\n\n if (mode === 'OFF') {\n console.log('\\n\\u23ed\\ufe0f Skipping no-unmanaged-exceptions validation (mode: OFF)');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n\\ud83d\\udccf Validating No Unmanaged Exceptions\\n');\n console.log(` Mode: ${mode}`);\n\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 no-unmanaged-exceptions validation (could not detect base branch)');\n console.log('');\n return { success: true };\n }\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);\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 let violations: TryCatchViolation[] = [];\n\n if (mode === 'NEW_AND_MODIFIED_CODE') {\n violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);\n } else if (mode === 'NEW_AND_MODIFIED_FILES') {\n violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\n }\n\n if (violations.length === 0) {\n console.log('\\u2705 No unmanaged try/catch blocks found');\n return { success: true };\n }\n\n reportViolations(violations, mode, disableAllowed);\n\n return { success: false };\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoUnmanagedExceptionsValidator extends CodeValidator<NoUnmanagedExceptionsConfig> {\n constructor(config: NoUnmanagedExceptionsConfig) {\n super(config, 'no-unmanaged-exceptions', 'no-unmanaged-exceptions');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.config, workspaceRoot);\n }\n}\n"]}
1
+ {"version":3,"file":"validate-no-unmanaged-exceptions.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-unmanaged-exceptions.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAgK;AAChK,qDAAiE;AACjE,yCAA2D;AAC3D,iDAAgD;AAChD,6CAAyC;AAQzC;;;GAGG;AACH,SAAS,iBAAiB,CAAC,KAAe,EAAE,UAAkB;IAC1D,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,UAAU,GAAG,CAAC,CAAC,CAAC;IAC/C,KAAK,IAAI,CAAC,GAAG,UAAU,GAAG,CAAC,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,EAAE,EAAE,CAAC;QAChD,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;QACpC,IAAI,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;YAClF,MAAM;QACV,CAAC;QACD,IAAI,IAAA,yBAAU,EAAC,IAAI,EAAE,yBAAU,CAAC,uBAAuB,CAAC,EAAE,CAAC;YACvD,OAAO,IAAI,CAAC;QAChB,CAAC;QACD,IAAI,IAAI,CAAC,QAAQ,CAAC,oCAAoC,CAAC,EAAE,CAAC;YACtD,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;IACD,OAAO,KAAK,CAAC;AACjB,CAAC;AAED,MAAM,WAAW,GAAG,YAAY,CAAC;AAQjC;;GAEG;AACH,SAAS,kBAAkB,CAAC,QAAgB,EAAE,aAAqB,EAAE,cAAuB;IACxF,MAAM,QAAQ,G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,GAAG,6BAA6B,CAAC,aAAa,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,EAAE,cAAc,CAAC,CAAC;IACxG,CAAC;SAAM,CAAC;QACJ,+FAA+F;QAC/F,UAAU,GAAG,8BAA8B,CAAC,aAAa,EAAE,YAAY,EAAE,cAAc,CAAC,CAAC;IAC7F,CAAC;IAED,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1B,OAAO,CAAC,GAAG,CAAC,4CAA4C,CAAC,CAAC;QAC1D,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAED,IAAI,CAAC,WAAW,CAAC,yBAAyB,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,CAAoB,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IAC9F,gBAAgB,CAAC,UAAU,EAAE,IAAI,EAAE,cAAc,CAAC,CAAC;IAEnD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC;AAGM,IAAM,8BAA8B,GAApC,MAAM,8BAA+B,SAAQ,8BAA0C;IACxB;IAAlE,YAAY,MAAmC,EAAmB,SAAoB;QAClF,KAAK,CAAC,MAAM,EAAE,yBAAyB,EAAE,yBAAyB,CAAC,CAAC;QADN,cAAS,GAAT,SAAS,CAAW;IAEtF,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,aAAqB;QAC3B,OAAO,gBAAgB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IACxE,CAAC;CACJ,CAAA;AARY,wEAA8B;yCAA9B,8BAA8B;IAD1C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEjB,0CAA2B,EAA8B,sBAAS;GAD7E,8BAA8B,CAQ1C","sourcesContent":["/**\n * Validate No Unmanaged Exceptions Executor\n *\n * Validates that try/catch blocks are not used outside chokepoints.\n * Uses LINE-BASED detection (not method-based) for git diff filtering.\n *\n * ============================================================================\n * VIOLATIONS (BAD) - These patterns are flagged:\n * ============================================================================\n *\n * - try { — any try/catch block in non-test code\n *\n * ============================================================================\n * ALLOWED (skip — NOT violations)\n * ============================================================================\n *\n * - Test files (.spec.ts, .test.ts, __tests__/)\n * - Lines with // webpieces-disable no-unmanaged-exceptions -- [reason]\n *\n * ============================================================================\n * MODES (LINE-BASED)\n * ============================================================================\n * - OFF: Skip validation entirely\n * - NEW_AND_MODIFIED_CODE: Flag try/catch on changed lines (lines in diff hunks)\n * - NEW_AND_MODIFIED_FILES: Flag ALL try/catch in files that were modified\n *\n * ============================================================================\n * ESCAPE HATCH\n * ============================================================================\n * Add comment above the violation:\n * // webpieces-disable no-unmanaged-exceptions -- [your justification]\n * try {\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { hasDisable, RULE_NAMES, NoUnmanagedExceptionsConfig, ModifiedCodeMode, detectBase, getFileDiff, getChangedLineNumbers } from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport { shouldSkipRule } from './resolve-mode';\nimport { ScanScope } from './scan-scope';\n\ninterface TryCatchViolation {\n file: string;\n line: number;\n context: string;\n}\n\n/**\n * Check if a line contains a disable comment for no-unmanaged-exceptions.\n * Recognizes both webpieces-disable and eslint-disable-next-line @webpieces/ formats.\n */\nfunction hasDisableComment(lines: string[], lineNumber: number): boolean {\n const startCheck = Math.max(0, lineNumber - 5);\n for (let i = lineNumber - 2; i >= startCheck; i--) {\n const line = lines[i]?.trim() ?? '';\n if (line.startsWith('function ') || line.startsWith('class ') || line.endsWith('}')) {\n break;\n }\n if (hasDisable(line, RULE_NAMES.NO_UNMANAGED_EXCEPTIONS)) {\n return true;\n }\n if (line.includes('@webpieces/no-unmanaged-exceptions')) {\n return true;\n }\n }\n return false;\n}\n\nconst TRY_PATTERN = /\\btry\\s*\\{/;\n\ninterface TryCatchInfo {\n line: number;\n context: string;\n hasDisableComment: boolean;\n}\n\n/**\n * Find all try/catch patterns in a file using line-based scanning.\n */\nfunction findTryCatchInFile(filePath: string, workspaceRoot: string, disableAllowed: boolean): TryCatchInfo[] {\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 violations: TryCatchInfo[] = [];\n\n for (let i = 0; i < fileLines.length; i++) {\n const line = fileLines[i];\n const trimmed = line.trim();\n // Skip comment lines (JSDoc, block comments, line comments)\n if (trimmed.startsWith('*') || trimmed.startsWith('//') || trimmed.startsWith('/*')) continue;\n if (!TRY_PATTERN.test(line)) continue;\n\n const lineNum = i + 1;\n const disabled = hasDisableComment(fileLines, lineNum);\n\n if (!disableAllowed && disabled) {\n violations.push({ line: lineNum, context: line.trim(), hasDisableComment: false });\n } else {\n violations.push({ line: lineNum, context: line.trim(), hasDisableComment: disabled });\n }\n }\n\n return violations;\n}\n\n/**\n * NEW_AND_MODIFIED_CODE mode: Flag violations on changed lines in diff hunks.\n */\nfunction findViolationsForModifiedCode(\n workspaceRoot: string,\n changedFiles: string[],\n base: string,\n head: string | undefined,\n disableAllowed: boolean,\n): TryCatchViolation[] {\n const violations: TryCatchViolation[] = [];\n\n for (const file of changedFiles) {\n const diff = getFileDiff(workspaceRoot, file, base, head);\n const changedLines = getChangedLineNumbers(diff);\n\n if (changedLines.size === 0) continue;\n\n const allViolations = findTryCatchInFile(file, workspaceRoot, disableAllowed);\n\n for (const v of allViolations) {\n if (disableAllowed && v.hasDisableComment) continue;\n if (!changedLines.has(v.line)) continue;\n\n violations.push({ file, line: v.line, context: v.context });\n }\n }\n\n return violations;\n}\n\n/**\n * NEW_AND_MODIFIED_FILES mode: Flag ALL violations in files that were modified.\n */\nfunction findViolationsForModifiedFiles(\n workspaceRoot: string,\n changedFiles: string[],\n disableAllowed: boolean,\n): TryCatchViolation[] {\n const violations: TryCatchViolation[] = [];\n\n for (const file of changedFiles) {\n const allViolations = findTryCatchInFile(file, workspaceRoot, disableAllowed);\n\n for (const v of allViolations) {\n if (disableAllowed && v.hasDisableComment) continue;\n violations.push({ file, line: v.line, context: v.context });\n }\n }\n\n return violations;\n}\n\n/**\n * Report violations to console.\n */\nfunction reportViolations(violations: TryCatchViolation[], mode: ModifiedCodeMode, disableAllowed: boolean): void {\n console.error('');\n console.error('\\u274c Unmanaged try/catch blocks found! Exceptions should bubble to chokepoints.');\n console.error('');\n console.error('\\ud83d\\udcda Philosophy: Most code should NOT catch exceptions.');\n console.error(' Exceptions should bubble to chokepoints (filter in Node.js, globalErrorHandler in Angular)');\n console.error(' where they are logged with traceId for debugging.');\n console.error('');\n\n for (const v of violations) {\n console.error(` \\u274c ${v.file}:${v.line}`);\n console.error(` ${v.context}`);\n }\n console.error('');\n\n if (disableAllowed) {\n console.error(' Escape hatch (use sparingly):');\n console.error(' // webpieces-disable no-unmanaged-exceptions -- [your reason]');\n console.error('');\n console.error(' When try/catch IS used, the catch block MUST follow:');\n console.error(' catch (err: unknown) { const error = toError(err); ... }');\n console.error(' or: catch (err: unknown) { //const error = toError(err); }');\n } else {\n console.error(' Escape hatch: DISABLED (disableAllowed: false)');\n console.error(' Disable comments are ignored. Remove the try/catch.');\n }\n console.error('');\n console.error(` Current mode: ${mode}`);\n console.error('');\n}\n\n/**\n * Resolve mode considering turnOffRuleUntilEpoch override.\n */\nfunction resolveMode(normalMode: ModifiedCodeMode, epoch: number | undefined, branchPattern: string | undefined): ModifiedCodeMode {\n if (normalMode === 'OFF') {\n return normalMode;\n }\n const skip = shouldSkipRule(epoch, branchPattern);\n if (skip.skip) {\n console.log(`\\n\\u23ed\\ufe0f Skipping no-unmanaged-exceptions validation (${skip.reason})`);\n console.log('');\n return 'OFF';\n }\n return normalMode;\n}\n\nasync function runValidatorImpl(\n scan: ScanScope,\n options: NoUnmanagedExceptionsConfig,\n workspaceRoot: string\n): Promise<ExecutorResult> {\n const mode: ModifiedCodeMode = resolveMode(options.mode ?? 'OFF', options.turnOffRuleUntilEpoch, (options.turnOffRuleWhileOnBranch ?? undefined));\n const disableAllowed = options.disableAllowed ?? true;\n\n if (mode === 'OFF') {\n console.log('\\n\\u23ed\\ufe0f Skipping no-unmanaged-exceptions validation (mode: OFF)');\n console.log('');\n return { success: true };\n }\n\n console.log('\\n\\ud83d\\udccf Validating No Unmanaged Exceptions\\n');\n console.log(` Mode: ${mode}`);\n\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 no-unmanaged-exceptions validation (could not detect base branch)');\n console.log('');\n return { success: true };\n }\n }\n\n console.log(` Base: ${base}`);\n console.log(` Head: ${head ?? 'working tree (includes uncommitted changes)'}`);\n console.log('');\n\n const changedFiles = scan.files(workspaceRoot, mode, 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 let violations: TryCatchViolation[] = [];\n\n if (mode === 'NEW_AND_MODIFIED_CODE') {\n violations = findViolationsForModifiedCode(workspaceRoot, changedFiles, base, head, disableAllowed);\n } else {\n // NEW_AND_MODIFIED_FILES and the whole-scope modes (#1027) all judge every site of every file.\n violations = findViolationsForModifiedFiles(workspaceRoot, changedFiles, disableAllowed);\n }\n\n if (violations.length === 0) {\n console.log('\\u2705 No unmanaged try/catch blocks found');\n return { success: true };\n }\n\n scan.recordSites('no-unmanaged-exceptions', violations.map((v: TryCatchViolation) => v.file));\n reportViolations(violations, mode, disableAllowed);\n\n return { success: false };\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoUnmanagedExceptionsValidator extends CodeValidator<NoUnmanagedExceptionsConfig> {\n constructor(config: NoUnmanagedExceptionsConfig, private readonly scanScope: ScanScope) {\n super(config, 'no-unmanaged-exceptions', 'no-unmanaged-exceptions');\n }\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n return runValidatorImpl(this.scanScope, this.config, workspaceRoot);\n }\n}\n"]}
@@ -28,6 +28,7 @@
28
28
  import { DiffScope, NoUtilityTypesInApiLibConfig } from '@webpieces/rules-config';
29
29
  import { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';
30
30
  import { ProjectRoleResolver } from './project-role-resolver';
31
+ import { ScanScope } from './scan-scope';
31
32
  /** Finds every refused utility-type reference in one parsed file. */
32
33
  export declare class UtilityTypeScanner {
33
34
  /** The refused utility types, each with what it computes. */
@@ -49,7 +50,7 @@ export declare class UtilityTypeScanner {
49
50
  }
50
51
  export declare class NoUtilityTypesInApiLibValidator extends ApiLibSourceRule<NoUtilityTypesInApiLibConfig> {
51
52
  private readonly scanner;
52
- constructor(config: NoUtilityTypesInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope);
53
+ constructor(config: NoUtilityTypesInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope, scanScope: ScanScope);
53
54
  protected sitesIn(file: ApiLibFile): ApiLibSite[];
54
55
  /** Scoped by the configured `paths` globs, not the role tag — an empty list judges nothing. */
55
56
  protected isApiLibrarySource(_workspaceRoot: string, relFile: string): boolean;
@@ -34,6 +34,7 @@ const inversify_1 = require("inversify");
34
34
  const ts = tslib_1.__importStar(require("typescript"));
35
35
  const api_lib_source_rule_1 = require("./api-lib-source-rule");
36
36
  const project_role_resolver_1 = require("./project-role-resolver");
37
+ const scan_scope_1 = require("./scan-scope");
37
38
  /** Finds every refused utility-type reference in one parsed file. */
38
39
  class UtilityTypeScanner {
39
40
  /** The refused utility types, each with what it computes. */
@@ -150,8 +151,8 @@ class UtilityTypeScanner {
150
151
  exports.UtilityTypeScanner = UtilityTypeScanner;
151
152
  let NoUtilityTypesInApiLibValidator = class NoUtilityTypesInApiLibValidator extends api_lib_source_rule_1.ApiLibSourceRule {
152
153
  scanner = new UtilityTypeScanner();
153
- constructor(config, roleResolver, diffScope) {
154
- super(config, rules_config_1.RULE_NAMES.NO_UTILITY_TYPES_IN_API_LIB, roleResolver, diffScope);
154
+ constructor(config, roleResolver, diffScope, scanScope) {
155
+ super(config, rules_config_1.RULE_NAMES.NO_UTILITY_TYPES_IN_API_LIB, roleResolver, diffScope, scanScope);
155
156
  }
156
157
  sitesIn(file) {
157
158
  return this.scanner.scan(file);
@@ -171,6 +172,6 @@ let NoUtilityTypesInApiLibValidator = class NoUtilityTypesInApiLibValidator exte
171
172
  exports.NoUtilityTypesInApiLibValidator = NoUtilityTypesInApiLibValidator;
172
173
  exports.NoUtilityTypesInApiLibValidator = NoUtilityTypesInApiLibValidator = tslib_1.__decorate([
173
174
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
174
- tslib_1.__metadata("design:paramtypes", [rules_config_1.NoUtilityTypesInApiLibConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope])
175
+ tslib_1.__metadata("design:paramtypes", [rules_config_1.NoUtilityTypesInApiLibConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope, scan_scope_1.ScanScope])
175
176
  ], NoUtilityTypesInApiLibValidator);
176
177
  //# sourceMappingURL=validate-no-utility-types-in-api-lib.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate-no-utility-types-in-api-lib.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-utility-types-in-api-lib.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;;;;AAEH,0DAA8G;AAC9G,yCAA2D;AAC3D,uDAAiC;AACjC,+DAAiF;AACjF,mEAA8D;AAE9D,qEAAqE;AACrE,MAAa,kBAAkB;IAC3B,6DAA6D;IAC7D,MAAM,CAAU,OAAO,GAAgC,IAAI,GAAG,CAAiB;QAC3E,CAAC,MAAM,EAAE,oEAAoE,CAAC;QAC9E,CAAC,MAAM,EAAE,gEAAgE,CAAC;QAC1E,CAAC,SA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AAO,SAAS,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;QAC7F,IAAI,EAAE,CAAC,sBAAsB,CAAC,IAAI,CAAC;YAAE,OAAO,QAAQ,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;QACrE,OAAO,SAAS,CAAC;IACrB,CAAC;;AA5GL,gDA6GC;AAGM,IAAM,+BAA+B,GAArC,MAAM,+BAAgC,SAAQ,sCAA8C;IAC9E,OAAO,GAAG,IAAI,kBAAkB,EAAE,CAAC;IAEpD,YAAY,MAAoC,EAAE,YAAiC,EAAE,SAAoB;QACrG,KAAK,CAAC,MAAM,EAAE,yBAAU,CAAC,2BAA2B,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC;IACnF,CAAC;IAES,OAAO,CAAC,IAAgB;QAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACnC,CAAC;IAED,+FAA+F;IAC5E,kBAAkB,CAAC,cAAsB,EAAE,OAAe;QACzE,OAAO,IAAA,6BAAc,EAAC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACtD,CAAC;IAEkB,UAAU;QACzB,OAAO,mCAAmC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;IAC9E,CAAC;IAES,GAAG;QACT,OAAO,wGAAwG;YAC3G,oGAAoG,CAAC;IAC7G,CAAC;CACJ,CAAA;AAxBY,0EAA+B;0CAA/B,+BAA+B;IAD3C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIjB,2CAA4B,EAAgB,2CAAmB,EAAa,wBAAS;GAHhG,+BAA+B,CAwB3C","sourcesContent":["/**\n * `no-utility-types-in-api-lib` (#1026) — an API contract writes its fields out.\n *\n * In every `.ts` file under the configured `paths` (e.g. `libraries/apis/**`) this refuses the\n * utility types that turn a DTO's field list, or a set of keys, into a type-level computation:\n *\n * export interface LessonPassageDto extends Omit<LessonPassageReservationDto, OptionalField> { … }\n * draft?: Partial<LessonDto>;\n * export type Summary = Pick<LessonDto, 'id' | 'title'>;\n * export type Kind = Exclude<AllKinds, 'legacy'>;\n *\n * — `Omit`, `Pick`, `Partial`, `Required`, `Exclude` and `Extract`, in an `extends` / `implements`\n * clause, a field, a type alias or a generic argument.\n *\n * Why: an api library is the contract every client, server and document generator reads. A utility\n * type makes a reader open a second file and subtract (or add) names in their head to learn which\n * fields a DTO carries; it cannot become a DTO class (`class X extends Omit<…>` does not compile — a\n * utility type has no runtime value); and a key union that only exists to feed `Omit` collides with\n * `one-enum-spelling-in-api-lib`, whose enum cure removes nothing from an `Omit`. The whole family is\n * refused, not `Omit` alone, because banning one just moves the computation into its sibling\n * (`Pick<T, Exclude<keyof T, K>>` is `Omit<T, K>`). `Record`, `Readonly` and `Array` stay allowed:\n * they do not hide which fields a DTO carries.\n *\n * The cure is to write the fields out — a shared base interface both DTOs extend, each adding its own\n * required or optional fields, or a flat interface / class listing every field. The wire JSON is\n * unchanged either way.\n */\n\nimport { DiffScope, NoUtilityTypesInApiLibConfig, RULE_NAMES, matchesAnyGlob } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport * as ts from 'typescript';\nimport { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';\nimport { ProjectRoleResolver } from './project-role-resolver';\n\n/** Finds every refused utility-type reference in one parsed file. */\nexport class UtilityTypeScanner {\n /** The refused utility types, each with what it computes. */\n static readonly REFUSED: ReadonlyMap<string, string> = new Map<string, string>([\n ['Omit', 'a DTO\\'s field list computed by SUBTRACTING keys from another type'],\n ['Pick', 'a DTO\\'s field list computed by SELECTING keys of another type'],\n ['Partial', 'a DTO\\'s field list computed by making every field of another type optional'],\n ['Required', 'a DTO\\'s field list computed by making every field of another type required'],\n ['Exclude', 'a set of keys or values computed by SUBTRACTING from another union'],\n ['Extract', 'a set of keys or values computed by SELECTING from another union'],\n ]);\n\n scan(file: ApiLibFile): ApiLibSite[] {\n const shadowed = this.locallyDeclaredNames(file.source);\n const sites: ApiLibSite[] = [];\n const visit = (node: ts.Node): void => {\n const name = this.refusedNameOf(node, shadowed);\n if (name !== undefined) sites.push(this.siteFor(file, node, name));\n ts.forEachChild(node, visit);\n };\n visit(file.source);\n return sites;\n }\n\n /** The utility's name when `node` is a refused reference: `Omit<…>` as a type, or in a heritage clause. */\n private refusedNameOf(node: ts.Node, shadowed: ReadonlySet<string>): string | undefined {\n let name: string | undefined;\n if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) name = node.typeName.text;\n else if (ts.isExpressionWithTypeArguments(node) && ts.isIdentifier(node.expression)) name = node.expression.text;\n if (name === undefined || !UtilityTypeScanner.REFUSED.has(name) || shadowed.has(name)) return undefined;\n return name;\n }\n\n /**\n * Names the file declares or imports itself — a local `type Omit = …` or an imported `Pick` class\n * is not the global utility type, so it is not refused.\n */\n private locallyDeclaredNames(source: ts.SourceFile): Set<string> {\n const names = new Set<string>();\n for (const statement of source.statements) {\n if ((ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement) ||\n ts.isClassDeclaration(statement) || ts.isEnumDeclaration(statement)) && statement.name !== undefined) {\n names.add(statement.name.text);\n }\n const bindings = ts.isImportDeclaration(statement) ? statement.importClause?.namedBindings : undefined;\n if (bindings !== undefined && ts.isNamedImports(bindings)) {\n for (const element of bindings.elements) names.add(element.name.text);\n }\n }\n return names;\n }\n\n private siteFor(file: ApiLibFile, node: ts.Node, name: string): ApiLibSite {\n const args = this.typeArgumentsOf(node).map((arg: ts.TypeNode) => arg.getText(file.source).replace(/\\s+/g, ' '));\n const what = `\\`${name}<…>\\` — ${UtilityTypeScanner.REFUSED.get(name)}; an API writes its fields out`;\n return file.site(node, what, `${this.cureFor(name, args[0] ?? 'T', args[1] ?? 'K')} ${this.owner(file, node)}`.trim());\n }\n\n private typeArgumentsOf(node: ts.Node): readonly ts.TypeNode[] {\n if (ts.isTypeReferenceNode(node) || ts.isExpressionWithTypeArguments(node)) return node.typeArguments ?? [];\n return [];\n }\n\n private cureFor(name: string, target: string, keys: string): string {\n const wire = 'The wire JSON is unchanged.';\n switch (name) {\n case 'Omit':\n return `write the fields out instead of \\`Omit<${target}, ${keys}>\\`: move the fields both types share into a ` +\n `base interface that ${target} and this type both extend, each adding its own required or optional ` +\n `fields — or list every field of ${target} except ${keys} in a flat interface or class. ${wire}`;\n case 'Pick':\n return `write the fields out instead of \\`Pick<${target}, ${keys}>\\`: put the picked fields (${keys}) in a ` +\n `base interface that ${target} extends and use it here — or list them in a flat interface or class. ${wire}`;\n case 'Partial':\n return `write the fields out instead of \\`Partial<${target}>\\`: declare an interface or class listing every ` +\n `field of ${target} as optional (\\`field?: X\\`). ${wire}`;\n case 'Required':\n return `write the fields out instead of \\`Required<${target}>\\`: declare an interface or class listing every ` +\n `field of ${target} as required. ${wire}`;\n default:\n return `write the set out instead of \\`${name}<${target}, ${keys}>\\`: for keys of a DTO, write that DTO's ` +\n `fields out; for values, declare the string enum holding exactly the members meant ` +\n `(one-enum-spelling-in-api-lib), or a union of its members. ${wire}`;\n }\n }\n\n /** `(on interface X)` for a heritage clause, `(in X.field)` for a member, `(in type X)` for an alias. */\n private owner(file: ApiLibFile, node: ts.Node): string {\n let current: ts.Node | undefined = node.parent;\n let member: string | undefined;\n while (current !== undefined && current !== file.source) {\n if ((ts.isPropertySignature(current) || ts.isPropertyDeclaration(current)) && member === undefined) {\n member = current.name.getText(file.source);\n }\n const declared = this.declaredName(current);\n if (declared !== undefined) {\n if (ts.isHeritageClause(node.parent)) return `(on ${declared})`;\n return member === undefined ? `(in ${declared})` : `(in ${declared}.${member})`;\n }\n current = current.parent;\n }\n return '';\n }\n\n private declaredName(node: ts.Node): string | undefined {\n if (ts.isInterfaceDeclaration(node)) return `interface ${node.name.text}`;\n if (ts.isClassDeclaration(node) && node.name !== undefined) return `class ${node.name.text}`;\n if (ts.isTypeAliasDeclaration(node)) return `type ${node.name.text}`;\n return undefined;\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoUtilityTypesInApiLibValidator extends ApiLibSourceRule<NoUtilityTypesInApiLibConfig> {\n private readonly scanner = new UtilityTypeScanner();\n\n constructor(config: NoUtilityTypesInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope) {\n super(config, RULE_NAMES.NO_UTILITY_TYPES_IN_API_LIB, roleResolver, diffScope);\n }\n\n protected sitesIn(file: ApiLibFile): ApiLibSite[] {\n return this.scanner.scan(file);\n }\n\n /** Scoped by the configured `paths` globs, not the role tag — an empty list judges nothing. */\n protected override isApiLibrarySource(_workspaceRoot: string, relFile: string): boolean {\n return matchesAnyGlob(relFile, this.config.paths);\n }\n\n protected override scopeLabel(): string {\n return `an API contract library (paths: ${this.config.paths.join(', ')})`;\n }\n\n protected why(): string {\n return 'an API writes its fields out — Omit / Pick / Partial / Required / Exclude / Extract make every reader ' +\n 'of the contract compute its field list from another file, and none of them can become a DTO class.';\n }\n}\n"]}
1
+ {"version":3,"file":"validate-no-utility-types-in-api-lib.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-no-utility-types-in-api-lib.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;;;;AAEH,0DAA8G;AAC9G,yCAA2D;AAC3D,uDAAiC;AACjC,+DAAiF;AACjF,mEAA8D;AAC9D,6CAAyC;AAEzC,qEAAqE;AACrE,MAAa,kBAAkB;IAC3B,6DAA6D;IAC7D,MAAM,CAAU,OAAO,GAAgC,IAAI,GAAG,CAAiB;QAC3E,CAAC,MAAM,EAAE,oEAAoE,CAAC;QAC9E,CAAC,MAAM,EAAE,gEAAgE,CAAC;QAC1E,CAAC,SAAS,EAAE,6EAA6E,CAAC;QAC1F,CAAC,UAAU,EAAE,6EAA6E,CAAC;QAC3F,CAAC,SAAS,EAAE,oEAAoE,CAAC;QACjF,CAAC,SAAS,EAAE,kEAAkE,CAAC;KAClF,C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AAI,EAAE,CAAC;QACrE,OAAO,SAAS,CAAC;IACrB,CAAC;;AA5GL,gDA6GC;AAGM,IAAM,+BAA+B,GAArC,MAAM,+BAAgC,SAAQ,sCAA8C;IAC9E,OAAO,GAAG,IAAI,kBAAkB,EAAE,CAAC;IAEpD,YAAY,MAAoC,EAAE,YAAiC,EAAE,SAAoB,EAAE,SAAoB;QAC3H,KAAK,CAAC,MAAM,EAAE,yBAAU,CAAC,2BAA2B,EAAE,YAAY,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC;IAC9F,CAAC;IAES,OAAO,CAAC,IAAgB;QAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACnC,CAAC;IAED,+FAA+F;IAC5E,kBAAkB,CAAC,cAAsB,EAAE,OAAe;QACzE,OAAO,IAAA,6BAAc,EAAC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACtD,CAAC;IAEkB,UAAU;QACzB,OAAO,mCAAmC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;IAC9E,CAAC;IAES,GAAG;QACT,OAAO,wGAAwG;YAC3G,oGAAoG,CAAC;IAC7G,CAAC;CACJ,CAAA;AAxBY,0EAA+B;0CAA/B,+BAA+B;IAD3C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIjB,2CAA4B,EAAgB,2CAAmB,EAAa,wBAAS,EAAa,sBAAS;GAHtH,+BAA+B,CAwB3C","sourcesContent":["/**\n * `no-utility-types-in-api-lib` (#1026) — an API contract writes its fields out.\n *\n * In every `.ts` file under the configured `paths` (e.g. `libraries/apis/**`) this refuses the\n * utility types that turn a DTO's field list, or a set of keys, into a type-level computation:\n *\n * export interface LessonPassageDto extends Omit<LessonPassageReservationDto, OptionalField> { … }\n * draft?: Partial<LessonDto>;\n * export type Summary = Pick<LessonDto, 'id' | 'title'>;\n * export type Kind = Exclude<AllKinds, 'legacy'>;\n *\n * — `Omit`, `Pick`, `Partial`, `Required`, `Exclude` and `Extract`, in an `extends` / `implements`\n * clause, a field, a type alias or a generic argument.\n *\n * Why: an api library is the contract every client, server and document generator reads. A utility\n * type makes a reader open a second file and subtract (or add) names in their head to learn which\n * fields a DTO carries; it cannot become a DTO class (`class X extends Omit<…>` does not compile — a\n * utility type has no runtime value); and a key union that only exists to feed `Omit` collides with\n * `one-enum-spelling-in-api-lib`, whose enum cure removes nothing from an `Omit`. The whole family is\n * refused, not `Omit` alone, because banning one just moves the computation into its sibling\n * (`Pick<T, Exclude<keyof T, K>>` is `Omit<T, K>`). `Record`, `Readonly` and `Array` stay allowed:\n * they do not hide which fields a DTO carries.\n *\n * The cure is to write the fields out — a shared base interface both DTOs extend, each adding its own\n * required or optional fields, or a flat interface / class listing every field. The wire JSON is\n * unchanged either way.\n */\n\nimport { DiffScope, NoUtilityTypesInApiLibConfig, RULE_NAMES, matchesAnyGlob } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport * as ts from 'typescript';\nimport { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';\nimport { ProjectRoleResolver } from './project-role-resolver';\nimport { ScanScope } from './scan-scope';\n\n/** Finds every refused utility-type reference in one parsed file. */\nexport class UtilityTypeScanner {\n /** The refused utility types, each with what it computes. */\n static readonly REFUSED: ReadonlyMap<string, string> = new Map<string, string>([\n ['Omit', 'a DTO\\'s field list computed by SUBTRACTING keys from another type'],\n ['Pick', 'a DTO\\'s field list computed by SELECTING keys of another type'],\n ['Partial', 'a DTO\\'s field list computed by making every field of another type optional'],\n ['Required', 'a DTO\\'s field list computed by making every field of another type required'],\n ['Exclude', 'a set of keys or values computed by SUBTRACTING from another union'],\n ['Extract', 'a set of keys or values computed by SELECTING from another union'],\n ]);\n\n scan(file: ApiLibFile): ApiLibSite[] {\n const shadowed = this.locallyDeclaredNames(file.source);\n const sites: ApiLibSite[] = [];\n const visit = (node: ts.Node): void => {\n const name = this.refusedNameOf(node, shadowed);\n if (name !== undefined) sites.push(this.siteFor(file, node, name));\n ts.forEachChild(node, visit);\n };\n visit(file.source);\n return sites;\n }\n\n /** The utility's name when `node` is a refused reference: `Omit<…>` as a type, or in a heritage clause. */\n private refusedNameOf(node: ts.Node, shadowed: ReadonlySet<string>): string | undefined {\n let name: string | undefined;\n if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) name = node.typeName.text;\n else if (ts.isExpressionWithTypeArguments(node) && ts.isIdentifier(node.expression)) name = node.expression.text;\n if (name === undefined || !UtilityTypeScanner.REFUSED.has(name) || shadowed.has(name)) return undefined;\n return name;\n }\n\n /**\n * Names the file declares or imports itself — a local `type Omit = …` or an imported `Pick` class\n * is not the global utility type, so it is not refused.\n */\n private locallyDeclaredNames(source: ts.SourceFile): Set<string> {\n const names = new Set<string>();\n for (const statement of source.statements) {\n if ((ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement) ||\n ts.isClassDeclaration(statement) || ts.isEnumDeclaration(statement)) && statement.name !== undefined) {\n names.add(statement.name.text);\n }\n const bindings = ts.isImportDeclaration(statement) ? statement.importClause?.namedBindings : undefined;\n if (bindings !== undefined && ts.isNamedImports(bindings)) {\n for (const element of bindings.elements) names.add(element.name.text);\n }\n }\n return names;\n }\n\n private siteFor(file: ApiLibFile, node: ts.Node, name: string): ApiLibSite {\n const args = this.typeArgumentsOf(node).map((arg: ts.TypeNode) => arg.getText(file.source).replace(/\\s+/g, ' '));\n const what = `\\`${name}<…>\\` — ${UtilityTypeScanner.REFUSED.get(name)}; an API writes its fields out`;\n return file.site(node, what, `${this.cureFor(name, args[0] ?? 'T', args[1] ?? 'K')} ${this.owner(file, node)}`.trim());\n }\n\n private typeArgumentsOf(node: ts.Node): readonly ts.TypeNode[] {\n if (ts.isTypeReferenceNode(node) || ts.isExpressionWithTypeArguments(node)) return node.typeArguments ?? [];\n return [];\n }\n\n private cureFor(name: string, target: string, keys: string): string {\n const wire = 'The wire JSON is unchanged.';\n switch (name) {\n case 'Omit':\n return `write the fields out instead of \\`Omit<${target}, ${keys}>\\`: move the fields both types share into a ` +\n `base interface that ${target} and this type both extend, each adding its own required or optional ` +\n `fields — or list every field of ${target} except ${keys} in a flat interface or class. ${wire}`;\n case 'Pick':\n return `write the fields out instead of \\`Pick<${target}, ${keys}>\\`: put the picked fields (${keys}) in a ` +\n `base interface that ${target} extends and use it here — or list them in a flat interface or class. ${wire}`;\n case 'Partial':\n return `write the fields out instead of \\`Partial<${target}>\\`: declare an interface or class listing every ` +\n `field of ${target} as optional (\\`field?: X\\`). ${wire}`;\n case 'Required':\n return `write the fields out instead of \\`Required<${target}>\\`: declare an interface or class listing every ` +\n `field of ${target} as required. ${wire}`;\n default:\n return `write the set out instead of \\`${name}<${target}, ${keys}>\\`: for keys of a DTO, write that DTO's ` +\n `fields out; for values, declare the string enum holding exactly the members meant ` +\n `(one-enum-spelling-in-api-lib), or a union of its members. ${wire}`;\n }\n }\n\n /** `(on interface X)` for a heritage clause, `(in X.field)` for a member, `(in type X)` for an alias. */\n private owner(file: ApiLibFile, node: ts.Node): string {\n let current: ts.Node | undefined = node.parent;\n let member: string | undefined;\n while (current !== undefined && current !== file.source) {\n if ((ts.isPropertySignature(current) || ts.isPropertyDeclaration(current)) && member === undefined) {\n member = current.name.getText(file.source);\n }\n const declared = this.declaredName(current);\n if (declared !== undefined) {\n if (ts.isHeritageClause(node.parent)) return `(on ${declared})`;\n return member === undefined ? `(in ${declared})` : `(in ${declared}.${member})`;\n }\n current = current.parent;\n }\n return '';\n }\n\n private declaredName(node: ts.Node): string | undefined {\n if (ts.isInterfaceDeclaration(node)) return `interface ${node.name.text}`;\n if (ts.isClassDeclaration(node) && node.name !== undefined) return `class ${node.name.text}`;\n if (ts.isTypeAliasDeclaration(node)) return `type ${node.name.text}`;\n return undefined;\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class NoUtilityTypesInApiLibValidator extends ApiLibSourceRule<NoUtilityTypesInApiLibConfig> {\n private readonly scanner = new UtilityTypeScanner();\n\n constructor(config: NoUtilityTypesInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope, scanScope: ScanScope) {\n super(config, RULE_NAMES.NO_UTILITY_TYPES_IN_API_LIB, roleResolver, diffScope, scanScope);\n }\n\n protected sitesIn(file: ApiLibFile): ApiLibSite[] {\n return this.scanner.scan(file);\n }\n\n /** Scoped by the configured `paths` globs, not the role tag — an empty list judges nothing. */\n protected override isApiLibrarySource(_workspaceRoot: string, relFile: string): boolean {\n return matchesAnyGlob(relFile, this.config.paths);\n }\n\n protected override scopeLabel(): string {\n return `an API contract library (paths: ${this.config.paths.join(', ')})`;\n }\n\n protected why(): string {\n return 'an API writes its fields out — Omit / Pick / Partial / Required / Exclude / Extract make every reader ' +\n 'of the contract compute its field list from another file, and none of them can become a DTO class.';\n }\n}\n"]}
@@ -24,6 +24,7 @@ import { DiffScope, OneEnumSpellingInApiLibConfig } from '@webpieces/rules-confi
24
24
  import { ApiLibEnumIndex } from './api-lib-enum-index';
25
25
  import { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';
26
26
  import { ProjectRoleResolver } from './project-role-resolver';
27
+ import { ScanScope } from './scan-scope';
27
28
  /** Finds every non-enum spelling of a closed string set in one parsed file. */
28
29
  export declare class EnumSpellingScanner {
29
30
  scan(file: ApiLibFile, index: ApiLibEnumIndex): ApiLibSite[];
@@ -55,7 +56,7 @@ export declare class OneEnumSpellingInApiLibValidator extends ApiLibSourceRule<O
55
56
  private readonly scanner;
56
57
  /** One index per api-library directory, per run: the union and its branches are in different files. */
57
58
  private readonly indexes;
58
- constructor(config: OneEnumSpellingInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope);
59
+ constructor(config: OneEnumSpellingInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope, scanScope: ScanScope);
59
60
  protected sitesIn(file: ApiLibFile): ApiLibSite[];
60
61
  protected why(): string;
61
62
  }
@@ -31,6 +31,7 @@ const api_lib_enum_index_1 = require("./api-lib-enum-index");
31
31
  const api_lib_enum_text_1 = require("./api-lib-enum-text");
32
32
  const api_lib_source_rule_1 = require("./api-lib-source-rule");
33
33
  const project_role_resolver_1 = require("./project-role-resolver");
34
+ const scan_scope_1 = require("./scan-scope");
34
35
  const ONE_SPELLING = 'a fixed set of string values in an API is a string enum, and only a string enum';
35
36
  /** Where a type is written: the declaration that names it, for naming the enum. Data-only. */
36
37
  class Holder {
@@ -230,8 +231,8 @@ let OneEnumSpellingInApiLibValidator = class OneEnumSpellingInApiLibValidator ex
230
231
  scanner = new EnumSpellingScanner();
231
232
  /** One index per api-library directory, per run: the union and its branches are in different files. */
232
233
  indexes = new Map();
233
- constructor(config, roleResolver, diffScope) {
234
- super(config, rules_config_1.RULE_NAMES.ONE_ENUM_SPELLING_IN_API_LIB, roleResolver, diffScope);
234
+ constructor(config, roleResolver, diffScope, scanScope) {
235
+ super(config, rules_config_1.RULE_NAMES.ONE_ENUM_SPELLING_IN_API_LIB, roleResolver, diffScope, scanScope);
235
236
  }
236
237
  sitesIn(file) {
237
238
  let index = this.indexes.get(file.projectDir);
@@ -250,6 +251,6 @@ let OneEnumSpellingInApiLibValidator = class OneEnumSpellingInApiLibValidator ex
250
251
  exports.OneEnumSpellingInApiLibValidator = OneEnumSpellingInApiLibValidator;
251
252
  exports.OneEnumSpellingInApiLibValidator = OneEnumSpellingInApiLibValidator = tslib_1.__decorate([
252
253
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
253
- tslib_1.__metadata("design:paramtypes", [rules_config_1.OneEnumSpellingInApiLibConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope])
254
+ tslib_1.__metadata("design:paramtypes", [rules_config_1.OneEnumSpellingInApiLibConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope, scan_scope_1.ScanScope])
254
255
  ], OneEnumSpellingInApiLibValidator);
255
256
  //# sourceMappingURL=validate-one-enum-spelling-in-api-lib.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate-one-enum-spelling-in-api-lib.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-one-enum-spelling-in-api-lib.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;;;;AAEH,0DAA+F;AAC/F,yCAA2D;AAC3D,uDAAiC;AACjC,6DAAoE;AACpE,2DAA+C;AAC/C,+DAAiF;AACjF,mEAA8D;AAE9D,MAAM,YAAY,GAAG,iFAAiF,CAAC;AAEvG,8FAA8F;AAC9F,MAAM,MAAM;IAGK;IACA;IAEA;IALb;IACI,mDAAmD;IAC1C,IAAY,EACZ,IAAY;IACrB,sEAAsE;IAC7D,KAAyB;QAHzB,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CAAQ;QAEZ,UAAK,GAAL,KAAK,CAAoB;IACnC,CAAC;CACP;AAED,sGAAsG;AACtG,MAAM,aAAa;IAEF;IACA;IAFb,YACa,QAAgB,EAChB,MAAyB;QADzB,aAAQ,GAAR,QAAQ,CAAQ;QAChB,WAAM,GAAN,MAAM,CAAmB;IACnC,CAAC;CACP;AAED,+EAA+E;AAC/E,MAAa,mBAAmB;IAC5B,IAAI,CAAC,IAAgB,EAAE,KAAsB;QACzC,MAAM,KAAK,GAAiB,EAAE,CAAC;QAC/B,MAAM,KAAK,GAAG,CAAC,IAAa,EAAQ,EAAE;YAClC,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;YAC5C,IAAI,IAAI,KAAK,SAAS;gBAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACzC,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QACjC,CAAC,CAAC;QACF,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACnB,OAAO,KAAK,CAA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uGAAuG;IACtF,OAAO,GAAG,IAAI,GAAG,EAA2B,CAAC;IAE9D,YAAY,MAAqC,EAAE,YAAiC,EAAE,SAAoB;QACtG,KAAK,CAAC,MAAM,EAAE,yBAAU,CAAC,4BAA4B,EAAE,YAAY,EAAE,SAAS,CAAC,CAAC;IACpF,CAAC;IAES,OAAO,CAAC,IAAgB;QAC9B,IAAI,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAC9C,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACtB,KAAK,GAAG,oCAAe,CAAC,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YAC5C,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;QAC7C,CAAC;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IAC1C,CAAC;IAES,GAAG;QACT,OAAO,GAAG,YAAY,qFAAqF;YACvG,uGAAuG;YACvG,sBAAsB,CAAC;IAC/B,CAAC;CACJ,CAAA;AAvBY,4EAAgC;2CAAhC,gCAAgC;IAD5C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAMjB,4CAA6B,EAAgB,2CAAmB,EAAa,wBAAS;GALjG,gCAAgC,CAuB5C","sourcesContent":["/**\n * `one-enum-spelling-in-api-lib` (#1023) — ONE spelling for a fixed set of string values in an API:\n *\n * export enum SpeakerGender { FEMALE = 'female', MALE = 'male' }\n * gender!: SpeakerGender; // the enum\n * mode: VoiceMode.RANDOM; // one member (a union discriminator)\n * mode: VoiceMode.A | VoiceMode.B; // a union of members\n *\n * In every `role:api-lib` project this refuses, each with a cure that PRINTS the enum to write:\n *\n * type LessonType = 'story' | 'lesson'; kind?: 'audio' | 'slot'; (a 2+ string-literal union)\n * gender!: (typeof SPEAKER_GENDERS)[number]; key: keyof typeof LABELS;\n * mode: 'random'; (a single literal used as a union discriminator)\n * enum Level { LOW, HIGH } enum Mixed { A = 'a', B = 2 } const enum Tone { … }\n *\n * Why ONE spelling: two ways to write a closed set means every reader, reviewer and the document\n * generator has to understand both, and the derived spellings (`(typeof X)[number]`, a `string` field\n * whose legal values live in some array) are exactly the ones the generator does not read — they can\n * only be supported later, deliberately, if ever. A numeric enum puts NUMBERS on the wire, which no\n * partner reading `gender: 1` can interpret. The generator itself keeps supporting literal unions;\n * this rule is what forbids new ones in an api library.\n */\n\nimport { DiffScope, OneEnumSpellingInApiLibConfig, RULE_NAMES } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport * as ts from 'typescript';\nimport { ApiLibEnumIndex, ObjectUnion } from './api-lib-enum-index';\nimport { EnumText } from './api-lib-enum-text';\nimport { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';\nimport { ProjectRoleResolver } from './project-role-resolver';\n\nconst ONE_SPELLING = 'a fixed set of string values in an API is a string enum, and only a string enum';\n\n/** Where a type is written: the declaration that names it, for naming the enum. Data-only. */\nclass Holder {\n constructor(\n /** 'alias' | 'property' | 'parameter' | 'none'. */\n readonly kind: string,\n readonly name: string,\n /** The enclosing named type / class / function, when there is one. */\n readonly owner: string | undefined,\n ) {}\n}\n\n/** A property that discriminates a union, and every value the union's branches give it. Data-only. */\nclass Discriminator {\n constructor(\n readonly enumName: string,\n readonly values: readonly string[],\n ) {}\n}\n\n/** Finds every non-enum spelling of a closed string set in one parsed file. */\nexport class EnumSpellingScanner {\n scan(file: ApiLibFile, index: ApiLibEnumIndex): ApiLibSite[] {\n const sites: ApiLibSite[] = [];\n const visit = (node: ts.Node): void => {\n const site = this.siteAt(file, index, node);\n if (site !== undefined) sites.push(site);\n ts.forEachChild(node, visit);\n };\n visit(file.source);\n return sites;\n }\n\n private siteAt(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.Node): ApiLibSite | undefined {\n if (ts.isUnionTypeNode(node)) return this.literalUnion(file, index, node);\n if (ts.isLiteralTypeNode(node) && ts.isStringLiteral(node.literal)) return this.singleLiteral(file, index, node);\n if (ts.isIndexedAccessTypeNode(node)) return this.typeofIndex(file, index, node);\n if (ts.isTypeOperatorNode(node) && node.operator === ts.SyntaxKind.KeyOfKeyword) return this.keyofTypeof(file, index, node);\n if (ts.isEnumDeclaration(node)) return this.badEnum(file, node);\n return undefined;\n }\n\n /** `'a' | 'b'` — two or more string-literal branches, anywhere a type is written. */\n private literalUnion(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.UnionTypeNode): ApiLibSite | undefined {\n const values = node.types\n .filter((t: ts.TypeNode) => ts.isLiteralTypeNode(t) && ts.isStringLiteral(t.literal))\n .map((t: ts.TypeNode) => ((t as ts.LiteralTypeNode).literal as ts.StringLiteral).text);\n if (values.length < 2) return undefined;\n const holder = this.holderOf(node);\n const discriminator = this.discriminatorOf(index, holder);\n const what = `a string-literal union — ${ONE_SPELLING}`;\n if (discriminator !== undefined) {\n const members = values.map((v: string) => EnumText.memberRef(discriminator.enumName, v, discriminator.values)).join(' | ');\n return file.site(node, what,\n `declare \\`${EnumText.declaration(discriminator.enumName, discriminator.values)}\\` (every value of the ` +\n `\\`${holder.name}\\` discriminator) and write \\`${holder.name}: ${members}\\` here.`);\n }\n if (holder.kind === 'alias') {\n return file.site(node, what,\n `replace \\`type ${holder.name} = …\\` with \\`${EnumText.declaration(holder.name, values)}\\` — every use of ` +\n `${holder.name} as a type keeps compiling; a literal VALUE becomes ${EnumText.memberRef(holder.name, values[0]!, values)}.`);\n }\n const name = this.enumNameFor(holder);\n return file.site(node, what,\n `declare \\`${EnumText.declaration(name, values)}\\` and write \\`${name}\\` here in place of the union.`);\n }\n\n /** `mode: 'random'` on a branch of a union — a discriminator, which is one enum member. */\n private singleLiteral(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.LiteralTypeNode): ApiLibSite | undefined {\n const direct = node.parent;\n const property = ts.isUnionTypeNode(direct) ? direct.parent : direct;\n if (!ts.isPropertySignature(property) && !ts.isPropertyDeclaration(property)) return undefined;\n if (ts.isUnionTypeNode(direct) && direct.types.filter((t: ts.TypeNode) => !ApiLibEnumIndex.isNullish(t)).length !== 1) {\n return undefined;\n }\n const discriminator = this.discriminatorOf(index, this.holderOf(node));\n if (discriminator === undefined) return undefined;\n const value = (node.literal as ts.StringLiteral).text;\n const key = property.name.getText(file.source);\n return file.site(node, `a single string-literal discriminator — ${ONE_SPELLING}`,\n `declare \\`${EnumText.declaration(discriminator.enumName, discriminator.values)}\\` (every value of the ` +\n `\\`${key}\\` discriminator) and write \\`${key}: ${EnumText.memberRef(discriminator.enumName, value, discriminator.values)}\\` here.`);\n }\n\n /** `(typeof X)[number]` — the values live in a runtime list; the enum IS that list. */\n private typeofIndex(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.IndexedAccessTypeNode): ApiLibSite | undefined {\n let object: ts.TypeNode = node.objectType;\n while (ts.isParenthesizedTypeNode(object)) object = object.type;\n if (!ts.isTypeQueryNode(object) || node.indexType.kind !== ts.SyntaxKind.NumberKeyword) return undefined;\n const list = object.exprName.getText(file.source);\n const name = EnumText.singularPascal(list.split('.').pop() ?? list);\n const values = index.constList(list);\n const declaration = values === undefined\n ? `export enum ${name} { /* one MEMBER = 'value' per element of ${list} */ }`\n : EnumText.declaration(name, values);\n return file.site(node, `\\`(typeof ${list})[number]\\` — ${ONE_SPELLING}`,\n `replace \\`${list}\\` with \\`${declaration}\\` and write \\`${name}\\` here; code that needs the runtime ` +\n `list uses \\`Object.values(${name})\\`.`);\n }\n\n /** `keyof typeof X` — the values are an object's keys; the enum states them. */\n private keyofTypeof(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.TypeOperatorNode): ApiLibSite | undefined {\n if (!ts.isTypeQueryNode(node.type)) return undefined;\n const object = node.type.exprName.getText(file.source);\n const name = `${EnumText.pascal(object.split('.').pop() ?? object)}Key`;\n const keys = index.constKeysOf(object);\n const declaration = keys === undefined\n ? `export enum ${name} { /* one MEMBER = 'key' per key of ${object} */ }`\n : EnumText.declaration(name, keys);\n return file.site(node, `\\`keyof typeof ${object}\\` — ${ONE_SPELLING}`,\n `declare \\`${declaration}\\` and write \\`${name}\\` here (key ${object} by it: \\`Record<${name}, …>\\`).`);\n }\n\n /** A `const`, numeric, heterogeneous or uninitialised enum. */\n private badEnum(file: ApiLibFile, node: ts.EnumDeclaration): ApiLibSite | undefined {\n const isConst = (node.modifiers ?? []).some((m: ts.ModifierLike) => m.kind === ts.SyntaxKind.ConstKeyword);\n const bad = node.members.filter((m: ts.EnumMember) => m.initializer === undefined || !ts.isStringLiteral(m.initializer));\n if (!isConst && bad.length === 0) return undefined;\n const values = node.members.map((m: ts.EnumMember) =>\n m.initializer !== undefined && ts.isStringLiteral(m.initializer) ? m.initializer.text : EnumText.valueFor(m.name.getText(file.source)));\n const reason = isConst\n ? 'a `const enum` — it is erased at compile time, so no runtime value exists for a client or the generator to read'\n : `member(s) ${bad.map((m: ts.EnumMember) => m.name.getText(file.source)).join(', ')} are not initialised with a string ` +\n 'literal — a numeric enum puts NUMBERS on the wire';\n const members = node.members.map((m: ts.EnumMember, i: number) => `${m.name.getText(file.source)} = '${values[i]}'`).join(', ');\n return file.site(node.name, `${reason}; ${ONE_SPELLING}`,\n `write \\`export enum ${node.name.text} { ${members} }\\` — every member string-initialised, no \\`const\\` ` +\n '(the suggested values are a starting point: they are the wire format, so choose them deliberately).');\n }\n\n /** The declaration a written type belongs to — climbing through arrays, parens, unions and generics. */\n private holderOf(node: ts.Node): Holder {\n let current: ts.Node = node.parent;\n while (current !== undefined && ts.isTypeNode(current)) current = current.parent;\n if (current === undefined) return new Holder('none', 'Values', undefined);\n if (ts.isTypeAliasDeclaration(current)) return new Holder('alias', current.name.text, undefined);\n if ((ts.isPropertySignature(current) || ts.isPropertyDeclaration(current)) &&\n (ts.isIdentifier(current.name) || ts.isStringLiteral(current.name))) {\n return new Holder('property', current.name.text, this.ownerOf(current));\n }\n if (ts.isParameter(current) && ts.isIdentifier(current.name)) {\n return new Holder('parameter', current.name.text, this.ownerOf(current));\n }\n return new Holder('none', 'Values', this.ownerOf(current));\n }\n\n /** The nearest enclosing named interface, class, type alias or function. */\n private ownerOf(node: ts.Node): string | undefined {\n for (let at: ts.Node | undefined = node.parent; at !== undefined; at = at.parent) {\n if ((ts.isInterfaceDeclaration(at) || ts.isClassDeclaration(at) || ts.isTypeAliasDeclaration(at) ||\n ts.isFunctionDeclaration(at) || ts.isMethodDeclaration(at)) && at.name !== undefined && ts.isIdentifier(at.name)) {\n return at.name.text;\n }\n }\n return undefined;\n }\n\n /**\n * When the holder is a property of a union BRANCH that every branch declares, it discriminates the\n * union: the enum is named for the union and property, and holds every branch's values.\n */\n private discriminatorOf(index: ApiLibEnumIndex, holder: Holder): Discriminator | undefined {\n if (holder.kind !== 'property' || holder.owner === undefined) return undefined;\n const union = index.unionsOf(holder.owner)\n .find((u: ObjectUnion) => u.branches.every((b: string) => index.propertyOf(b, holder.name) !== undefined));\n if (union === undefined) return undefined;\n const values: string[] = [];\n for (const branch of union.branches) {\n for (const value of this.literalValues(index.propertyOf(branch, holder.name)!)) {\n if (!values.includes(value)) values.push(value);\n }\n }\n return new Discriminator(`${union.name ?? holder.owner}${EnumText.pascal(holder.name)}`, values);\n }\n\n /** The string literals a property type spells: `'a'` or `'a' | 'b'`. */\n private literalValues(type: ts.TypeNode): string[] {\n const branches = ts.isUnionTypeNode(type) ? [...type.types] : [type];\n return branches\n .filter((t: ts.TypeNode) => ts.isLiteralTypeNode(t) && ts.isStringLiteral(t.literal))\n .map((t: ts.TypeNode) => ((t as ts.LiteralTypeNode).literal as ts.StringLiteral).text);\n }\n\n private enumNameFor(holder: Holder): string {\n if (holder.kind === 'none') return `${holder.owner === undefined ? '' : EnumText.pascal(holder.owner)}Values`;\n return `${holder.owner === undefined ? '' : EnumText.pascal(holder.owner)}${EnumText.pascal(holder.name)}`;\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class OneEnumSpellingInApiLibValidator extends ApiLibSourceRule<OneEnumSpellingInApiLibConfig> {\n private readonly scanner = new EnumSpellingScanner();\n /** One index per api-library directory, per run: the union and its branches are in different files. */\n private readonly indexes = new Map<string, ApiLibEnumIndex>();\n\n constructor(config: OneEnumSpellingInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope) {\n super(config, RULE_NAMES.ONE_ENUM_SPELLING_IN_API_LIB, roleResolver, diffScope);\n }\n\n protected sitesIn(file: ApiLibFile): ApiLibSite[] {\n let index = this.indexes.get(file.projectDir);\n if (index === undefined) {\n index = ApiLibEnumIndex.of(file.projectDir);\n this.indexes.set(file.projectDir, index);\n }\n return this.scanner.scan(file, index);\n }\n\n protected why(): string {\n return `${ONE_SPELLING} — every member explicitly initialised with a string literal. Two spellings of one ` +\n 'thing is two things every reader and the document generator must understand, and a numeric enum puts ' +\n 'numbers on the wire.';\n }\n}\n"]}
1
+ {"version":3,"file":"validate-one-enum-spelling-in-api-lib.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-one-enum-spelling-in-api-lib.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;;;;AAEH,0DAA+F;AAC/F,yCAA2D;AAC3D,uDAAiC;AACjC,6DAAoE;AACpE,2DAA+C;AAC/C,+DAAiF;AACjF,mEAA8D;AAC9D,6CAAyC;AAEzC,MAAM,YAAY,GAAG,iFAAiF,CAAC;AAEvG,8FAA8F;AAC9F,MAAM,MAAM;IAGK;IACA;IAEA;IALb;IACI,mDAAmD;IAC1C,IAAY,EACZ,IAAY;IACrB,sEAAsE;IAC7D,KAAyB;QAHzB,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CAAQ;QAEZ,UAAK,GAAL,KAAK,CAAoB;IACnC,CAAC;CACP;AAED,sGAAsG;AACtG,MAAM,aAAa;IAEF;IACA;IAFb,YACa,QAAgB,EAChB,MAAyB;QADzB,aAAQ,GAAR,QAAQ,CA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AuG;YACvG,sBAAsB,CAAC;IAC/B,CAAC;CACJ,CAAA;AAvBY,4EAAgC;2CAAhC,gCAAgC;IAD5C,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAMjB,4CAA6B,EAAgB,2CAAmB,EAAa,wBAAS,EAAa,sBAAS;GALvH,gCAAgC,CAuB5C","sourcesContent":["/**\n * `one-enum-spelling-in-api-lib` (#1023) — ONE spelling for a fixed set of string values in an API:\n *\n * export enum SpeakerGender { FEMALE = 'female', MALE = 'male' }\n * gender!: SpeakerGender; // the enum\n * mode: VoiceMode.RANDOM; // one member (a union discriminator)\n * mode: VoiceMode.A | VoiceMode.B; // a union of members\n *\n * In every `role:api-lib` project this refuses, each with a cure that PRINTS the enum to write:\n *\n * type LessonType = 'story' | 'lesson'; kind?: 'audio' | 'slot'; (a 2+ string-literal union)\n * gender!: (typeof SPEAKER_GENDERS)[number]; key: keyof typeof LABELS;\n * mode: 'random'; (a single literal used as a union discriminator)\n * enum Level { LOW, HIGH } enum Mixed { A = 'a', B = 2 } const enum Tone { … }\n *\n * Why ONE spelling: two ways to write a closed set means every reader, reviewer and the document\n * generator has to understand both, and the derived spellings (`(typeof X)[number]`, a `string` field\n * whose legal values live in some array) are exactly the ones the generator does not read — they can\n * only be supported later, deliberately, if ever. A numeric enum puts NUMBERS on the wire, which no\n * partner reading `gender: 1` can interpret. The generator itself keeps supporting literal unions;\n * this rule is what forbids new ones in an api library.\n */\n\nimport { DiffScope, OneEnumSpellingInApiLibConfig, RULE_NAMES } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\nimport * as ts from 'typescript';\nimport { ApiLibEnumIndex, ObjectUnion } from './api-lib-enum-index';\nimport { EnumText } from './api-lib-enum-text';\nimport { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';\nimport { ProjectRoleResolver } from './project-role-resolver';\nimport { ScanScope } from './scan-scope';\n\nconst ONE_SPELLING = 'a fixed set of string values in an API is a string enum, and only a string enum';\n\n/** Where a type is written: the declaration that names it, for naming the enum. Data-only. */\nclass Holder {\n constructor(\n /** 'alias' | 'property' | 'parameter' | 'none'. */\n readonly kind: string,\n readonly name: string,\n /** The enclosing named type / class / function, when there is one. */\n readonly owner: string | undefined,\n ) {}\n}\n\n/** A property that discriminates a union, and every value the union's branches give it. Data-only. */\nclass Discriminator {\n constructor(\n readonly enumName: string,\n readonly values: readonly string[],\n ) {}\n}\n\n/** Finds every non-enum spelling of a closed string set in one parsed file. */\nexport class EnumSpellingScanner {\n scan(file: ApiLibFile, index: ApiLibEnumIndex): ApiLibSite[] {\n const sites: ApiLibSite[] = [];\n const visit = (node: ts.Node): void => {\n const site = this.siteAt(file, index, node);\n if (site !== undefined) sites.push(site);\n ts.forEachChild(node, visit);\n };\n visit(file.source);\n return sites;\n }\n\n private siteAt(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.Node): ApiLibSite | undefined {\n if (ts.isUnionTypeNode(node)) return this.literalUnion(file, index, node);\n if (ts.isLiteralTypeNode(node) && ts.isStringLiteral(node.literal)) return this.singleLiteral(file, index, node);\n if (ts.isIndexedAccessTypeNode(node)) return this.typeofIndex(file, index, node);\n if (ts.isTypeOperatorNode(node) && node.operator === ts.SyntaxKind.KeyOfKeyword) return this.keyofTypeof(file, index, node);\n if (ts.isEnumDeclaration(node)) return this.badEnum(file, node);\n return undefined;\n }\n\n /** `'a' | 'b'` — two or more string-literal branches, anywhere a type is written. */\n private literalUnion(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.UnionTypeNode): ApiLibSite | undefined {\n const values = node.types\n .filter((t: ts.TypeNode) => ts.isLiteralTypeNode(t) && ts.isStringLiteral(t.literal))\n .map((t: ts.TypeNode) => ((t as ts.LiteralTypeNode).literal as ts.StringLiteral).text);\n if (values.length < 2) return undefined;\n const holder = this.holderOf(node);\n const discriminator = this.discriminatorOf(index, holder);\n const what = `a string-literal union — ${ONE_SPELLING}`;\n if (discriminator !== undefined) {\n const members = values.map((v: string) => EnumText.memberRef(discriminator.enumName, v, discriminator.values)).join(' | ');\n return file.site(node, what,\n `declare \\`${EnumText.declaration(discriminator.enumName, discriminator.values)}\\` (every value of the ` +\n `\\`${holder.name}\\` discriminator) and write \\`${holder.name}: ${members}\\` here.`);\n }\n if (holder.kind === 'alias') {\n return file.site(node, what,\n `replace \\`type ${holder.name} = …\\` with \\`${EnumText.declaration(holder.name, values)}\\` — every use of ` +\n `${holder.name} as a type keeps compiling; a literal VALUE becomes ${EnumText.memberRef(holder.name, values[0]!, values)}.`);\n }\n const name = this.enumNameFor(holder);\n return file.site(node, what,\n `declare \\`${EnumText.declaration(name, values)}\\` and write \\`${name}\\` here in place of the union.`);\n }\n\n /** `mode: 'random'` on a branch of a union — a discriminator, which is one enum member. */\n private singleLiteral(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.LiteralTypeNode): ApiLibSite | undefined {\n const direct = node.parent;\n const property = ts.isUnionTypeNode(direct) ? direct.parent : direct;\n if (!ts.isPropertySignature(property) && !ts.isPropertyDeclaration(property)) return undefined;\n if (ts.isUnionTypeNode(direct) && direct.types.filter((t: ts.TypeNode) => !ApiLibEnumIndex.isNullish(t)).length !== 1) {\n return undefined;\n }\n const discriminator = this.discriminatorOf(index, this.holderOf(node));\n if (discriminator === undefined) return undefined;\n const value = (node.literal as ts.StringLiteral).text;\n const key = property.name.getText(file.source);\n return file.site(node, `a single string-literal discriminator — ${ONE_SPELLING}`,\n `declare \\`${EnumText.declaration(discriminator.enumName, discriminator.values)}\\` (every value of the ` +\n `\\`${key}\\` discriminator) and write \\`${key}: ${EnumText.memberRef(discriminator.enumName, value, discriminator.values)}\\` here.`);\n }\n\n /** `(typeof X)[number]` — the values live in a runtime list; the enum IS that list. */\n private typeofIndex(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.IndexedAccessTypeNode): ApiLibSite | undefined {\n let object: ts.TypeNode = node.objectType;\n while (ts.isParenthesizedTypeNode(object)) object = object.type;\n if (!ts.isTypeQueryNode(object) || node.indexType.kind !== ts.SyntaxKind.NumberKeyword) return undefined;\n const list = object.exprName.getText(file.source);\n const name = EnumText.singularPascal(list.split('.').pop() ?? list);\n const values = index.constList(list);\n const declaration = values === undefined\n ? `export enum ${name} { /* one MEMBER = 'value' per element of ${list} */ }`\n : EnumText.declaration(name, values);\n return file.site(node, `\\`(typeof ${list})[number]\\` — ${ONE_SPELLING}`,\n `replace \\`${list}\\` with \\`${declaration}\\` and write \\`${name}\\` here; code that needs the runtime ` +\n `list uses \\`Object.values(${name})\\`.`);\n }\n\n /** `keyof typeof X` — the values are an object's keys; the enum states them. */\n private keyofTypeof(file: ApiLibFile, index: ApiLibEnumIndex, node: ts.TypeOperatorNode): ApiLibSite | undefined {\n if (!ts.isTypeQueryNode(node.type)) return undefined;\n const object = node.type.exprName.getText(file.source);\n const name = `${EnumText.pascal(object.split('.').pop() ?? object)}Key`;\n const keys = index.constKeysOf(object);\n const declaration = keys === undefined\n ? `export enum ${name} { /* one MEMBER = 'key' per key of ${object} */ }`\n : EnumText.declaration(name, keys);\n return file.site(node, `\\`keyof typeof ${object}\\` — ${ONE_SPELLING}`,\n `declare \\`${declaration}\\` and write \\`${name}\\` here (key ${object} by it: \\`Record<${name}, …>\\`).`);\n }\n\n /** A `const`, numeric, heterogeneous or uninitialised enum. */\n private badEnum(file: ApiLibFile, node: ts.EnumDeclaration): ApiLibSite | undefined {\n const isConst = (node.modifiers ?? []).some((m: ts.ModifierLike) => m.kind === ts.SyntaxKind.ConstKeyword);\n const bad = node.members.filter((m: ts.EnumMember) => m.initializer === undefined || !ts.isStringLiteral(m.initializer));\n if (!isConst && bad.length === 0) return undefined;\n const values = node.members.map((m: ts.EnumMember) =>\n m.initializer !== undefined && ts.isStringLiteral(m.initializer) ? m.initializer.text : EnumText.valueFor(m.name.getText(file.source)));\n const reason = isConst\n ? 'a `const enum` — it is erased at compile time, so no runtime value exists for a client or the generator to read'\n : `member(s) ${bad.map((m: ts.EnumMember) => m.name.getText(file.source)).join(', ')} are not initialised with a string ` +\n 'literal — a numeric enum puts NUMBERS on the wire';\n const members = node.members.map((m: ts.EnumMember, i: number) => `${m.name.getText(file.source)} = '${values[i]}'`).join(', ');\n return file.site(node.name, `${reason}; ${ONE_SPELLING}`,\n `write \\`export enum ${node.name.text} { ${members} }\\` — every member string-initialised, no \\`const\\` ` +\n '(the suggested values are a starting point: they are the wire format, so choose them deliberately).');\n }\n\n /** The declaration a written type belongs to — climbing through arrays, parens, unions and generics. */\n private holderOf(node: ts.Node): Holder {\n let current: ts.Node = node.parent;\n while (current !== undefined && ts.isTypeNode(current)) current = current.parent;\n if (current === undefined) return new Holder('none', 'Values', undefined);\n if (ts.isTypeAliasDeclaration(current)) return new Holder('alias', current.name.text, undefined);\n if ((ts.isPropertySignature(current) || ts.isPropertyDeclaration(current)) &&\n (ts.isIdentifier(current.name) || ts.isStringLiteral(current.name))) {\n return new Holder('property', current.name.text, this.ownerOf(current));\n }\n if (ts.isParameter(current) && ts.isIdentifier(current.name)) {\n return new Holder('parameter', current.name.text, this.ownerOf(current));\n }\n return new Holder('none', 'Values', this.ownerOf(current));\n }\n\n /** The nearest enclosing named interface, class, type alias or function. */\n private ownerOf(node: ts.Node): string | undefined {\n for (let at: ts.Node | undefined = node.parent; at !== undefined; at = at.parent) {\n if ((ts.isInterfaceDeclaration(at) || ts.isClassDeclaration(at) || ts.isTypeAliasDeclaration(at) ||\n ts.isFunctionDeclaration(at) || ts.isMethodDeclaration(at)) && at.name !== undefined && ts.isIdentifier(at.name)) {\n return at.name.text;\n }\n }\n return undefined;\n }\n\n /**\n * When the holder is a property of a union BRANCH that every branch declares, it discriminates the\n * union: the enum is named for the union and property, and holds every branch's values.\n */\n private discriminatorOf(index: ApiLibEnumIndex, holder: Holder): Discriminator | undefined {\n if (holder.kind !== 'property' || holder.owner === undefined) return undefined;\n const union = index.unionsOf(holder.owner)\n .find((u: ObjectUnion) => u.branches.every((b: string) => index.propertyOf(b, holder.name) !== undefined));\n if (union === undefined) return undefined;\n const values: string[] = [];\n for (const branch of union.branches) {\n for (const value of this.literalValues(index.propertyOf(branch, holder.name)!)) {\n if (!values.includes(value)) values.push(value);\n }\n }\n return new Discriminator(`${union.name ?? holder.owner}${EnumText.pascal(holder.name)}`, values);\n }\n\n /** The string literals a property type spells: `'a'` or `'a' | 'b'`. */\n private literalValues(type: ts.TypeNode): string[] {\n const branches = ts.isUnionTypeNode(type) ? [...type.types] : [type];\n return branches\n .filter((t: ts.TypeNode) => ts.isLiteralTypeNode(t) && ts.isStringLiteral(t.literal))\n .map((t: ts.TypeNode) => ((t as ts.LiteralTypeNode).literal as ts.StringLiteral).text);\n }\n\n private enumNameFor(holder: Holder): string {\n if (holder.kind === 'none') return `${holder.owner === undefined ? '' : EnumText.pascal(holder.owner)}Values`;\n return `${holder.owner === undefined ? '' : EnumText.pascal(holder.owner)}${EnumText.pascal(holder.name)}`;\n }\n}\n\n@injectable(bindingScopeValues.Singleton)\nexport class OneEnumSpellingInApiLibValidator extends ApiLibSourceRule<OneEnumSpellingInApiLibConfig> {\n private readonly scanner = new EnumSpellingScanner();\n /** One index per api-library directory, per run: the union and its branches are in different files. */\n private readonly indexes = new Map<string, ApiLibEnumIndex>();\n\n constructor(config: OneEnumSpellingInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope, scanScope: ScanScope) {\n super(config, RULE_NAMES.ONE_ENUM_SPELLING_IN_API_LIB, roleResolver, diffScope, scanScope);\n }\n\n protected sitesIn(file: ApiLibFile): ApiLibSite[] {\n let index = this.indexes.get(file.projectDir);\n if (index === undefined) {\n index = ApiLibEnumIndex.of(file.projectDir);\n this.indexes.set(file.projectDir, index);\n }\n return this.scanner.scan(file, index);\n }\n\n protected why(): string {\n return `${ONE_SPELLING} — every member explicitly initialised with a string literal. Two spellings of one ` +\n 'thing is two things every reader and the document generator must understand, and a numeric enum puts ' +\n 'numbers on the wire.';\n }\n}\n"]}
@@ -15,8 +15,9 @@
15
15
  * Why: in review a `…Dto` is a wire type and a `…Fs` a Firestore document, while `TopNamePlaceInput` reads
16
16
  * the same as a server-internal or vendor type. The suffix is the one place the layer can be stated.
17
17
  *
18
- * Overlapping entries: the MOST SPECIFIC entry governs a file ({@link SuffixEntryPicker}); suffixes are
19
- * never unioned across entries.
18
+ * Overlapping entries: the FIRST entry in config order whose paths match governs a file
19
+ * ({@link SuffixEntryPicker}), so a narrower entry must be listed before a broader one; suffixes are never
20
+ * unioned across entries.
20
21
  *
21
22
  * Under NEW_AND_MODIFIED_CODE only a declaration whose NAME line is new or changed is judged — a new type
22
23
  * or a renamed one — so legacy names are grandfathered and a repo with hundreds of them can convert slowly.
@@ -24,37 +25,22 @@
24
25
  import { DiffScope, RequiredTypeSuffixConfig, RequiredTypeSuffixEntry } from '@webpieces/rules-config';
25
26
  import { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';
26
27
  import { ProjectRoleResolver } from './project-role-resolver';
27
- /** One glob of one entry, with how specific it is. Data-only. */
28
- export declare class RankedGlob {
28
+ import { ScanScope } from './scan-scope';
29
+ /** The entry that governs a file, and the glob of it that matched — named in every failure. Data-only. */
30
+ export declare class GoverningGlob {
29
31
  readonly entry: RequiredTypeSuffixEntry;
30
32
  readonly glob: string;
31
- /** Characters before the first glob metacharacter (`*`, `?`, `[`, `{`). */
32
- readonly literalPrefix: number;
33
- /** Every non-metacharacter in the glob. */
34
- readonly literalChars: number;
35
- /** Position of the entry in the config — the final tie-break. */
36
- readonly order: number;
37
- constructor(entry: RequiredTypeSuffixEntry, glob: string,
38
- /** Characters before the first glob metacharacter (`*`, `?`, `[`, `{`). */
39
- literalPrefix: number,
40
- /** Every non-metacharacter in the glob. */
41
- literalChars: number,
42
- /** Position of the entry in the config — the final tie-break. */
43
- order: number);
33
+ constructor(entry: RequiredTypeSuffixEntry, glob: string);
44
34
  }
45
35
  /**
46
- * Picks the ONE entry that governs a file. Among the entries with a glob matching the file, the one whose
47
- * matching glob has the longest LITERAL PREFIX (the characters before its first `*`, `?`, `[` or `{`)
48
- * wins; a tie goes to the glob with more literal characters overall, then to the entry listed first. So
49
- * `libraries/apis/internal/**` beats `libraries/apis/**` whatever order they are listed in.
36
+ * Picks the ONE entry that governs a file: the FIRST entry, in config order, with a glob matching the
37
+ * file. Order matters — to give a narrower directory stricter suffixes, list its entry ABOVE the broader
38
+ * one; listed below, it never applies to the files the broader entry already covers.
50
39
  */
51
40
  export declare class SuffixEntryPicker {
52
- private static readonly META;
53
41
  entryFor(relFile: string, entries: readonly RequiredTypeSuffixEntry[]): RequiredTypeSuffixEntry | undefined;
54
- /** The winning glob (and its entry) for `relFile`, or undefined when no entry covers it. */
55
- winner(relFile: string, entries: readonly RequiredTypeSuffixEntry[]): RankedGlob | undefined;
56
- private rank;
57
- private beats;
42
+ /** The first matching entry (and its matching glob) for `relFile`, or undefined when no entry covers it. */
43
+ winner(relFile: string, entries: readonly RequiredTypeSuffixEntry[]): GoverningGlob | undefined;
58
44
  }
59
45
  /** The rename a failure suggests: the name's layer-less tail swapped for each allowed suffix. */
60
46
  export declare class SuffixRename {
@@ -81,7 +67,7 @@ export declare class ExportedTypeScanner {
81
67
  export declare class RequiredTypeSuffixValidator extends ApiLibSourceRule<RequiredTypeSuffixConfig> {
82
68
  private readonly picker;
83
69
  private readonly scanner;
84
- constructor(config: RequiredTypeSuffixConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope);
70
+ constructor(config: RequiredTypeSuffixConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope, scanScope: ScanScope);
85
71
  protected sitesIn(file: ApiLibFile): ApiLibSite[];
86
72
  /** Scoped by the configured entries' `paths` globs, not the role tag. */
87
73
  protected isApiLibrarySource(_workspaceRoot: string, relFile: string): boolean;
@@ -16,79 +16,49 @@
16
16
  * Why: in review a `…Dto` is a wire type and a `…Fs` a Firestore document, while `TopNamePlaceInput` reads
17
17
  * the same as a server-internal or vendor type. The suffix is the one place the layer can be stated.
18
18
  *
19
- * Overlapping entries: the MOST SPECIFIC entry governs a file ({@link SuffixEntryPicker}); suffixes are
20
- * never unioned across entries.
19
+ * Overlapping entries: the FIRST entry in config order whose paths match governs a file
20
+ * ({@link SuffixEntryPicker}), so a narrower entry must be listed before a broader one; suffixes are never
21
+ * unioned across entries.
21
22
  *
22
23
  * Under NEW_AND_MODIFIED_CODE only a declaration whose NAME line is new or changed is judged — a new type
23
24
  * or a renamed one — so legacy names are grandfathered and a repo with hundreds of them can convert slowly.
24
25
  */
25
26
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.RequiredTypeSuffixValidator = exports.ExportedTypeScanner = exports.SuffixRename = exports.SuffixEntryPicker = exports.RankedGlob = void 0;
27
+ exports.RequiredTypeSuffixValidator = exports.ExportedTypeScanner = exports.SuffixRename = exports.SuffixEntryPicker = exports.GoverningGlob = void 0;
27
28
  const tslib_1 = require("tslib");
28
29
  const rules_config_1 = require("@webpieces/rules-config");
29
30
  const inversify_1 = require("inversify");
30
31
  const ts = tslib_1.__importStar(require("typescript"));
31
32
  const api_lib_source_rule_1 = require("./api-lib-source-rule");
32
33
  const project_role_resolver_1 = require("./project-role-resolver");
33
- /** One glob of one entry, with how specific it is. Data-only. */
34
- class RankedGlob {
34
+ const scan_scope_1 = require("./scan-scope");
35
+ /** The entry that governs a file, and the glob of it that matched — named in every failure. Data-only. */
36
+ class GoverningGlob {
35
37
  entry;
36
38
  glob;
37
- literalPrefix;
38
- literalChars;
39
- order;
40
- constructor(entry, glob,
41
- /** Characters before the first glob metacharacter (`*`, `?`, `[`, `{`). */
42
- literalPrefix,
43
- /** Every non-metacharacter in the glob. */
44
- literalChars,
45
- /** Position of the entry in the config — the final tie-break. */
46
- order) {
39
+ constructor(entry, glob) {
47
40
  this.entry = entry;
48
41
  this.glob = glob;
49
- this.literalPrefix = literalPrefix;
50
- this.literalChars = literalChars;
51
- this.order = order;
52
42
  }
53
43
  }
54
- exports.RankedGlob = RankedGlob;
44
+ exports.GoverningGlob = GoverningGlob;
55
45
  /**
56
- * Picks the ONE entry that governs a file. Among the entries with a glob matching the file, the one whose
57
- * matching glob has the longest LITERAL PREFIX (the characters before its first `*`, `?`, `[` or `{`)
58
- * wins; a tie goes to the glob with more literal characters overall, then to the entry listed first. So
59
- * `libraries/apis/internal/**` beats `libraries/apis/**` whatever order they are listed in.
46
+ * Picks the ONE entry that governs a file: the FIRST entry, in config order, with a glob matching the
47
+ * file. Order matters — to give a narrower directory stricter suffixes, list its entry ABOVE the broader
48
+ * one; listed below, it never applies to the files the broader entry already covers.
60
49
  */
61
50
  class SuffixEntryPicker {
62
- static META = /[*?[\]{}]/;
63
51
  entryFor(relFile, entries) {
64
52
  return this.winner(relFile, entries)?.entry;
65
53
  }
66
- /** The winning glob (and its entry) for `relFile`, or undefined when no entry covers it. */
54
+ /** The first matching entry (and its matching glob) for `relFile`, or undefined when no entry covers it. */
67
55
  winner(relFile, entries) {
68
- let best;
69
- entries.forEach((entry, order) => {
70
- for (const glob of entry.paths) {
71
- if (!(0, rules_config_1.matchesAnyGlob)(relFile, [glob]))
72
- continue;
73
- const ranked = this.rank(entry, glob, order);
74
- if (best === undefined || this.beats(ranked, best))
75
- best = ranked;
76
- }
77
- });
78
- return best;
79
- }
80
- rank(entry, glob, order) {
81
- const firstMeta = glob.search(SuffixEntryPicker.META);
82
- const literalPrefix = firstMeta === -1 ? glob.length : firstMeta;
83
- const literalChars = glob.replace(/[*?[\]{}]/g, '').length;
84
- return new RankedGlob(entry, glob, literalPrefix, literalChars, order);
85
- }
86
- beats(a, b) {
87
- if (a.literalPrefix !== b.literalPrefix)
88
- return a.literalPrefix > b.literalPrefix;
89
- if (a.literalChars !== b.literalChars)
90
- return a.literalChars > b.literalChars;
91
- return a.order < b.order;
56
+ for (const entry of entries) {
57
+ const glob = entry.paths.find((g) => (0, rules_config_1.matchesAnyGlob)(relFile, [g]));
58
+ if (glob !== undefined)
59
+ return new GoverningGlob(entry, glob);
60
+ }
61
+ return undefined;
92
62
  }
93
63
  }
94
64
  exports.SuffixEntryPicker = SuffixEntryPicker;
@@ -205,8 +175,8 @@ exports.ExportedTypeScanner = ExportedTypeScanner;
205
175
  let RequiredTypeSuffixValidator = class RequiredTypeSuffixValidator extends api_lib_source_rule_1.ApiLibSourceRule {
206
176
  picker = new SuffixEntryPicker();
207
177
  scanner = new ExportedTypeScanner();
208
- constructor(config, roleResolver, diffScope) {
209
- super(config, rules_config_1.RULE_NAMES.REQUIRED_TYPE_SUFFIX, roleResolver, diffScope);
178
+ constructor(config, roleResolver, diffScope, scanScope) {
179
+ super(config, rules_config_1.RULE_NAMES.REQUIRED_TYPE_SUFFIX, roleResolver, diffScope, scanScope);
210
180
  }
211
181
  sitesIn(file) {
212
182
  const winner = this.picker.winner(file.relFile, this.config.entries);
@@ -231,6 +201,9 @@ let RequiredTypeSuffixValidator = class RequiredTypeSuffixValidator extends api_
231
201
  exports.RequiredTypeSuffixValidator = RequiredTypeSuffixValidator;
232
202
  exports.RequiredTypeSuffixValidator = RequiredTypeSuffixValidator = tslib_1.__decorate([
233
203
  (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
234
- tslib_1.__metadata("design:paramtypes", [rules_config_1.RequiredTypeSuffixConfig, project_role_resolver_1.ProjectRoleResolver, rules_config_1.DiffScope])
204
+ tslib_1.__metadata("design:paramtypes", [rules_config_1.RequiredTypeSuffixConfig,
205
+ project_role_resolver_1.ProjectRoleResolver,
206
+ rules_config_1.DiffScope,
207
+ scan_scope_1.ScanScope])
235
208
  ], RequiredTypeSuffixValidator);
236
209
  //# sourceMappingURL=validate-required-type-suffix.js.map