@webpieces/code-rules 0.4.814 → 0.4.815

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DebugRunReport = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const fs = tslib_1.__importStar(require("fs"));
6
+ const path = tslib_1.__importStar(require("path"));
7
+ const rules_config_1 = require("@webpieces/rules-config");
8
+ const inversify_1 = require("inversify");
9
+ const rule_reporter_1 = require("./rule-reporter");
10
+ /** One site a rule printed: a file inside a project, and the line when the rule named one. Data-only. */
11
+ class PrintedSite {
12
+ relFile;
13
+ line;
14
+ projectRoot;
15
+ constructor(relFile, line, projectRoot) {
16
+ this.relFile = relFile;
17
+ this.line = line;
18
+ this.projectRoot = projectRoot;
19
+ }
20
+ }
21
+ /**
22
+ * Runs a DEBUG run (#1027): one rule, labelled as not the gate, its own failure text printed exactly as
23
+ * the build prints it, then a count of sites per project. Nothing is written to webpieces.config.json.
24
+ *
25
+ * The count is taken from what the rule PRINTED — every `path` / `path:line` it named that is a file in
26
+ * a project — rather than from each rule's internals, because the rules report through one renderer
27
+ * but hold their sites in thirty different shapes. A site named twice (in the message and in a cure)
28
+ * counts once. A passing run has no sites by definition, whatever file names it logged on the way.
29
+ */
30
+ let DebugRunReport = class DebugRunReport {
31
+ reporter;
32
+ constructor(reporter) {
33
+ this.reporter = reporter;
34
+ }
35
+ async run(workspaceRoot, runs, target) {
36
+ this.printBanner(target);
37
+ const captured = [];
38
+ const result = await this.capture(captured, () => this.reporter.runValidators(runs));
39
+ const sites = result.success ? [] : this.sitesIn(workspaceRoot, captured.join('\n'));
40
+ this.printCounts(workspaceRoot, target, sites);
41
+ return { success: result.success };
42
+ }
43
+ printBanner(target) {
44
+ const projects = target.projectNames === null ? 'every project' : target.projectNames.join(', ');
45
+ console.log('');
46
+ console.log('🔬 DEBUG RUN — not the gate. Nothing on disk changes; the build keeps judging the committed mode.');
47
+ console.log(` rule: ${target.rule}`);
48
+ console.log(` mode: ${target.mode}${target.mode === target.committedMode ? ' (committed)' : ` (committed: ${target.committedMode})`}`);
49
+ console.log(` projects: ${projects}`);
50
+ console.log(' turnOffRuleUntilEpoch / turnOffRuleWhileOnBranch are ignored for this run.');
51
+ console.log('');
52
+ }
53
+ // Tee console output: it still reaches the terminal, and the report reads it back afterwards.
54
+ async capture(into, work) {
55
+ const originals = [console.log, console.error, console.warn];
56
+ const tee = (original) => (...args) => {
57
+ into.push(args.map(String).join(' '));
58
+ original(...args);
59
+ };
60
+ console.log = tee(originals[0]);
61
+ console.error = tee(originals[1]);
62
+ console.warn = tee(originals[2]);
63
+ // webpieces-disable no-unmanaged-exceptions -- restores the console on every path; the reporter already isolates rule failures
64
+ try {
65
+ return await work();
66
+ }
67
+ finally {
68
+ console.log = originals[0];
69
+ console.error = originals[1];
70
+ console.warn = originals[2];
71
+ }
72
+ }
73
+ sitesIn(workspaceRoot, text) {
74
+ const projects = new rules_config_1.ProjectIndex(workspaceRoot);
75
+ const byKey = new Map();
76
+ for (const raw of text.split(/\s+/)) {
77
+ const site = this.siteOf(workspaceRoot, raw, projects);
78
+ if (site !== null)
79
+ byKey.set(`${site.relFile}:${site.line ?? ''}`, site);
80
+ }
81
+ const lined = new Set(Array.from(byKey.values()).filter((s) => s.line !== null).map((s) => s.relFile));
82
+ return Array.from(byKey.values()).filter((s) => s.line !== null || !lined.has(s.relFile));
83
+ }
84
+ siteOf(workspaceRoot, raw, projects) {
85
+ const token = raw.replace(/^[^\w./@-]+/, '').replace(/[^\w/]+$/, '');
86
+ const match = /^(.+?\.[A-Za-z0-9]+)(?::(\d+))?(?::\d+)?$/.exec(token);
87
+ if (match === null)
88
+ return null;
89
+ const prefix = workspaceRoot.endsWith('/') ? workspaceRoot : `${workspaceRoot}/`;
90
+ const relFile = match[1].startsWith(prefix) ? match[1].slice(prefix.length) : match[1];
91
+ if (path.isAbsolute(relFile) || !fs.existsSync(path.join(workspaceRoot, relFile)))
92
+ return null;
93
+ const projectRoot = projects.rootOf(relFile);
94
+ if (projectRoot === null)
95
+ return null;
96
+ return new PrintedSite(relFile, match[2] ?? null, projectRoot);
97
+ }
98
+ printCounts(workspaceRoot, target, sites) {
99
+ const projects = new rules_config_1.ProjectIndex(workspaceRoot);
100
+ const counts = new Map();
101
+ for (const root of target.projectRoots ?? [])
102
+ counts.set(root, 0);
103
+ for (const site of sites) {
104
+ if (target.projectRoots !== null && !counts.has(site.projectRoot))
105
+ continue;
106
+ counts.set(site.projectRoot, (counts.get(site.projectRoot) ?? 0) + 1);
107
+ }
108
+ const names = new Map();
109
+ for (const root of counts.keys())
110
+ names.set(root, projects.nameOf(root));
111
+ const total = Array.from(counts.values()).reduce((a, b) => a + b, 0);
112
+ const width = Math.max(5, ...Array.from(names.values()).map((n) => n.length));
113
+ console.log('');
114
+ console.log(`🔬 DEBUG RUN — ${target.rule} @ ${target.mode}: sites per project`);
115
+ for (const root of counts.keys()) {
116
+ console.log(` ${(names.get(root) ?? root).padEnd(width)} ${counts.get(root) ?? 0}`);
117
+ }
118
+ console.log(` ${'TOTAL'.padEnd(width)} ${total}`);
119
+ console.log('');
120
+ }
121
+ };
122
+ exports.DebugRunReport = DebugRunReport;
123
+ exports.DebugRunReport = DebugRunReport = tslib_1.__decorate([
124
+ (0, inversify_1.injectable)(inversify_1.bindingScopeValues.Singleton),
125
+ tslib_1.__metadata("design:paramtypes", [rule_reporter_1.RuleReporter])
126
+ ], DebugRunReport);
127
+ //# sourceMappingURL=debug-run-report.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"debug-run-report.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/debug-run-report.ts"],"names":[],"mappings":";;;;AAAA,+CAAyB;AACzB,mDAA6B;AAC7B,0DAAuD;AACvD,yCAA2D;AAI3D,mDAA+C;AAM/C,yGAAyG;AACzG,MAAM,WAAW;IAEA;IACA;IACA;IAHb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I,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC3F,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,MAAM,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,KAAK,EAAE,CAAC,CAAC;QACrD,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IACpB,CAAC;CACJ,CAAA;AAtFY,wCAAc;yBAAd,cAAc;IAD1B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAEE,4BAAY;GAD1C,cAAc,CAsF1B","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport { ProjectIndex } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { ExecutorResult, RuleRun } from './code-validator';\nimport { DebugTarget } from './rule-scope-plan';\nimport { RuleReporter } from './rule-reporter';\n\n/** The shape of console.log / console.error / console.warn. */\n// webpieces-disable no-any-unknown -- console methods take any printable values\ntype ConsoleFn = (...args: unknown[]) => void;\n\n/** One site a rule printed: a file inside a project, and the line when the rule named one. Data-only. */\nclass PrintedSite {\n constructor(\n readonly relFile: string,\n readonly line: string | null,\n readonly projectRoot: string,\n ) {}\n}\n\n/**\n * Runs a DEBUG run (#1027): one rule, labelled as not the gate, its own failure text printed exactly as\n * the build prints it, then a count of sites per project. Nothing is written to webpieces.config.json.\n *\n * The count is taken from what the rule PRINTED — every `path` / `path:line` it named that is a file in\n * a project — rather than from each rule's internals, because the rules report through one renderer\n * but hold their sites in thirty different shapes. A site named twice (in the message and in a cure)\n * counts once. A passing run has no sites by definition, whatever file names it logged on the way.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class DebugRunReport {\n constructor(private readonly reporter: RuleReporter) {}\n\n async run(workspaceRoot: string, runs: readonly RuleRun[], target: DebugTarget): Promise<ExecutorResult> {\n this.printBanner(target);\n const captured: string[] = [];\n const result = await this.capture(captured, () => this.reporter.runValidators(runs));\n const sites = result.success ? [] : this.sitesIn(workspaceRoot, captured.join('\\n'));\n this.printCounts(workspaceRoot, target, sites);\n return { success: result.success };\n }\n\n private printBanner(target: DebugTarget): void {\n const projects = target.projectNames === null ? 'every project' : target.projectNames.join(', ');\n console.log('');\n console.log('🔬 DEBUG RUN — not the gate. Nothing on disk changes; the build keeps judging the committed mode.');\n console.log(` rule: ${target.rule}`);\n console.log(` mode: ${target.mode}${target.mode === target.committedMode ? ' (committed)' : ` (committed: ${target.committedMode})`}`);\n console.log(` projects: ${projects}`);\n console.log(' turnOffRuleUntilEpoch / turnOffRuleWhileOnBranch are ignored for this run.');\n console.log('');\n }\n\n // Tee console output: it still reaches the terminal, and the report reads it back afterwards.\n private async capture(into: string[], work: () => Promise<ExecutorResult>): Promise<ExecutorResult> {\n const originals: ConsoleFn[] = [console.log, console.error, console.warn];\n const tee = (original: ConsoleFn): ConsoleFn => (...args: Parameters<ConsoleFn>): void => {\n into.push(args.map(String).join(' '));\n original(...args);\n };\n console.log = tee(originals[0]);\n console.error = tee(originals[1]);\n console.warn = tee(originals[2]);\n // webpieces-disable no-unmanaged-exceptions -- restores the console on every path; the reporter already isolates rule failures\n try {\n return await work();\n } finally {\n console.log = originals[0];\n console.error = originals[1];\n console.warn = originals[2];\n }\n }\n\n private sitesIn(workspaceRoot: string, text: string): PrintedSite[] {\n const projects = new ProjectIndex(workspaceRoot);\n const byKey = new Map<string, PrintedSite>();\n for (const raw of text.split(/\\s+/)) {\n const site = this.siteOf(workspaceRoot, raw, projects);\n if (site !== null) byKey.set(`${site.relFile}:${site.line ?? ''}`, site);\n }\n const lined = new Set(Array.from(byKey.values()).filter((s: PrintedSite) => s.line !== null).map((s: PrintedSite) => s.relFile));\n return Array.from(byKey.values()).filter((s: PrintedSite) => s.line !== null || !lined.has(s.relFile));\n }\n\n private siteOf(workspaceRoot: string, raw: string, projects: ProjectIndex): PrintedSite | null {\n const token = raw.replace(/^[^\\w./@-]+/, '').replace(/[^\\w/]+$/, '');\n const match = /^(.+?\\.[A-Za-z0-9]+)(?::(\\d+))?(?::\\d+)?$/.exec(token);\n if (match === null) return null;\n const prefix = workspaceRoot.endsWith('/') ? workspaceRoot : `${workspaceRoot}/`;\n const relFile = match[1].startsWith(prefix) ? match[1].slice(prefix.length) : match[1];\n if (path.isAbsolute(relFile) || !fs.existsSync(path.join(workspaceRoot, relFile))) return null;\n const projectRoot = projects.rootOf(relFile);\n if (projectRoot === null) return null;\n return new PrintedSite(relFile, match[2] ?? null, projectRoot);\n }\n\n private printCounts(workspaceRoot: string, target: DebugTarget, sites: readonly PrintedSite[]): void {\n const projects = new ProjectIndex(workspaceRoot);\n const counts = new Map<string, number>();\n for (const root of target.projectRoots ?? []) counts.set(root, 0);\n for (const site of sites) {\n if (target.projectRoots !== null && !counts.has(site.projectRoot)) continue;\n counts.set(site.projectRoot, (counts.get(site.projectRoot) ?? 0) + 1);\n }\n const names = new Map<string, string>();\n for (const root of counts.keys()) names.set(root, projects.nameOf(root));\n const total = Array.from(counts.values()).reduce((a: number, b: number) => a + b, 0);\n const width = Math.max(5, ...Array.from(names.values()).map((n: string) => n.length));\n console.log('');\n console.log(`🔬 DEBUG RUN — ${target.rule} @ ${target.mode}: sites per project`);\n for (const root of counts.keys()) {\n console.log(` ${(names.get(root) ?? root).padEnd(width)} ${counts.get(root) ?? 0}`);\n }\n console.log(` ${'TOTAL'.padEnd(width)} ${total}`);\n console.log('');\n }\n}\n"]}
package/src/index.d.ts CHANGED
@@ -29,4 +29,5 @@ export { EnumText } from './api-lib-enum-text';
29
29
  export { PrismaValidateDtosValidator } from './validate-dtos';
30
30
  export { PrismaConverterValidator } from './validate-prisma-converters';
31
31
  export { default as validateCode } from './validate-code';
32
+ export { CodeRulesRunRequest, CodeRulesRunRequestParser } from './code-rules-run-request';
32
33
  export { ReactNativeCompatibility } from './react-native-compatibility';
package/src/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ReactNativeCompatibility = exports.validateCode = exports.PrismaConverterValidator = exports.PrismaValidateDtosValidator = exports.EnumText = exports.ApiLibEnumIndex = exports.UtilityTypeScanner = exports.NoUtilityTypesInApiLibValidator = exports.EnumSpellingScanner = exports.OneEnumSpellingInApiLibValidator = exports.InlineImportScanner = exports.NoInlineImportInApiLibValidator = exports.ApiLibSite = exports.ApiLibFile = exports.findDirectlyChangedProjectRoots = exports.auditSecurityContracts = exports.SecurityContractViolation = exports.EnsureWeAreSecureValidator = exports.RoleTagValidator = exports.FrameworkTagValidator = exports.findRedundantInjectInSource = exports.InjectAnnotationNotNeededForConcreteClassValidator = exports.NoFunctionOutsideClassValidator = exports.NoProcessExitOutsideMainValidator = exports.ProjectRoleResolver = exports.StatePathViolation = exports.StatePathHit = exports.NoStatePathsInTemplatesValidator = exports.NoClientCreationOutsideServerOrClientValidator = exports.NoSymbolDiTokensValidator = exports.NoDirectApiResolverValidator = exports.NoDestructureValidator = exports.NoUnmanagedExceptionsValidator = exports.CatchErrorPatternValidator = exports.NoInlineTypeLiteralsValidator = exports.RequireReturnTypeValidator = exports.MaxFileLinesValidator = exports.runNewMethods = exports.runModifiedMethods = exports.MaxMethodLinesValidator = exports.NoImplicitAnyValidator = exports.NoAnyUnknownValidator = exports.CodeValidator = void 0;
3
+ exports.ReactNativeCompatibility = exports.CodeRulesRunRequestParser = exports.CodeRulesRunRequest = exports.validateCode = exports.PrismaConverterValidator = exports.PrismaValidateDtosValidator = exports.EnumText = exports.ApiLibEnumIndex = exports.UtilityTypeScanner = exports.NoUtilityTypesInApiLibValidator = exports.EnumSpellingScanner = exports.OneEnumSpellingInApiLibValidator = exports.InlineImportScanner = exports.NoInlineImportInApiLibValidator = exports.ApiLibSite = exports.ApiLibFile = exports.findDirectlyChangedProjectRoots = exports.auditSecurityContracts = exports.SecurityContractViolation = exports.EnsureWeAreSecureValidator = exports.RoleTagValidator = exports.FrameworkTagValidator = exports.findRedundantInjectInSource = exports.InjectAnnotationNotNeededForConcreteClassValidator = exports.NoFunctionOutsideClassValidator = exports.NoProcessExitOutsideMainValidator = exports.ProjectRoleResolver = exports.StatePathViolation = exports.StatePathHit = exports.NoStatePathsInTemplatesValidator = exports.NoClientCreationOutsideServerOrClientValidator = exports.NoSymbolDiTokensValidator = exports.NoDirectApiResolverValidator = exports.NoDestructureValidator = exports.NoUnmanagedExceptionsValidator = exports.CatchErrorPatternValidator = exports.NoInlineTypeLiteralsValidator = exports.RequireReturnTypeValidator = exports.MaxFileLinesValidator = exports.runNewMethods = exports.runModifiedMethods = exports.MaxMethodLinesValidator = exports.NoImplicitAnyValidator = exports.NoAnyUnknownValidator = exports.CodeValidator = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  var code_validator_1 = require("./code-validator");
6
6
  Object.defineProperty(exports, "CodeValidator", { enumerable: true, get: function () { return code_validator_1.CodeValidator; } });
@@ -75,6 +75,9 @@ var validate_prisma_converters_1 = require("./validate-prisma-converters");
75
75
  Object.defineProperty(exports, "PrismaConverterValidator", { enumerable: true, get: function () { return validate_prisma_converters_1.PrismaConverterValidator; } });
76
76
  var validate_code_1 = require("./validate-code");
77
77
  Object.defineProperty(exports, "validateCode", { enumerable: true, get: function () { return tslib_1.__importDefault(validate_code_1).default; } });
78
+ var code_rules_run_request_1 = require("./code-rules-run-request");
79
+ Object.defineProperty(exports, "CodeRulesRunRequest", { enumerable: true, get: function () { return code_rules_run_request_1.CodeRulesRunRequest; } });
80
+ Object.defineProperty(exports, "CodeRulesRunRequestParser", { enumerable: true, get: function () { return code_rules_run_request_1.CodeRulesRunRequestParser; } });
78
81
  var react_native_compatibility_1 = require("./react-native-compatibility");
79
82
  Object.defineProperty(exports, "ReactNativeCompatibility", { enumerable: true, get: function () { return react_native_compatibility_1.ReactNativeCompatibility; } });
80
83
  //# sourceMappingURL=index.js.map
package/src/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/index.ts"],"names":[],"mappings":";;;;AAAA,mDAAiE;AAAxD,+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,OAAA;AAAE,2IAAA,mBAAmB,OAAA;AAC7D,iGAAgH;AAAvG,yJAAA,gCAAgC,OAAA;AAAE,4IAAA,mBAAmB,OAAA;AAC9D,+FAA6G;AAApG,uJAAA,+BAA+B,OAAA;AAAE,0IAAA,kBAAkB,OAAA;AAC5D,2DAAuD;AAA9C,qHAAA,eAAe,OAAA;AACxB,yDAA+C;AAAtC,6GAAA,QAAQ,OAAA;AACjB,iDAA8D;AAArD,4HAAA,2BAA2B,OAAA;AACpC,2EAAwE;AAA/D,sIAAA,wBAAwB,OAAA;AACjC,iDAA0D;AAAjD,sIAAA,OAAO,OAAgB;AAEhC,2EAAwE;AAA/D,sIAAA,wBAAwB,OAAA","sourcesContent":["export { CodeValidator, ExecutorResult } from './code-validator';\n\nexport { NoAnyUnknownValidator } from './validate-no-any-unknown';\nexport { NoImplicitAnyValidator } from './validate-no-implicit-any';\nexport { MaxMethodLinesValidator, runModifiedMethods } from './validate-modified-methods';\nexport { runNewMethods } from './validate-new-methods';\nexport { MaxFileLinesValidator } from './validate-modified-files';\nexport { RequireReturnTypeValidator } from './validate-return-types';\nexport { NoInlineTypeLiteralsValidator } from './validate-no-inline-types';\nexport { CatchErrorPatternValidator } from './validate-catch-error-pattern';\nexport { NoUnmanagedExceptionsValidator } from './validate-no-unmanaged-exceptions';\nexport { NoDestructureValidator } from './validate-no-destructure';\nexport { NoDirectApiResolverValidator } from './validate-no-direct-api-resolver';\nexport { NoSymbolDiTokensValidator } from './validate-no-symbol-di-tokens';\nexport { NoClientCreationOutsideServerOrClientValidator } from './validate-no-client-creation-outside-server-or-client';\nexport {\n NoStatePathsInTemplatesValidator,\n StatePathHit,\n StatePathViolation,\n} from './validate-no-state-paths-in-templates';\nexport { ProjectRoleResolver } from './project-role-resolver';\nexport { NoProcessExitOutsideMainValidator } from './validate-no-process-exit-outside-main';\nexport { NoFunctionOutsideClassValidator } from './validate-no-function-outside-class';\nexport {\n InjectAnnotationNotNeededForConcreteClassValidator,\n findRedundantInjectInSource,\n} from './validate-inject-annotation-not-needed-for-concrete-class';\nexport { FrameworkTagValidator } from './validate-framework-tag';\nexport { RoleTagValidator } from './validate-role-tag';\nexport {\n EnsureWeAreSecureValidator,\n SecurityContractViolation,\n auditSecurityContracts,\n findDirectlyChangedProjectRoots,\n} from './validate-ensure-we-are-secure';\nexport { ApiLibFile, ApiLibSite } from './api-lib-source-rule';\nexport { NoInlineImportInApiLibValidator, InlineImportScanner } from './validate-no-inline-import-in-api-lib';\nexport { OneEnumSpellingInApiLibValidator, EnumSpellingScanner } from './validate-one-enum-spelling-in-api-lib';\nexport { NoUtilityTypesInApiLibValidator, UtilityTypeScanner } from './validate-no-utility-types-in-api-lib';\nexport { ApiLibEnumIndex } from './api-lib-enum-index';\nexport { EnumText } from './api-lib-enum-text';\nexport { PrismaValidateDtosValidator } from './validate-dtos';\nexport { PrismaConverterValidator } from './validate-prisma-converters';\nexport { default as validateCode } from './validate-code';\n\nexport { ReactNativeCompatibility } from './react-native-compatibility';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/index.ts"],"names":[],"mappings":";;;;AAAA,mDAAiE;AAAxD,+GAAA,aAAa,OAAA;AAEtB,qEAAkE;AAAzD,gIAAA,qBAAqB,OAAA;AAC9B,uEAAoE;AAA3D,kIAAA,sBAAsB,OAAA;AAC/B,yEAA0F;AAAjF,oIAAA,uBAAuB,OAAA;AAAE,+HAAA,kBAAkB,OAAA;AACpD,+DAAuD;AAA9C,qHAAA,aAAa,OAAA;AACtB,qEAAkE;AAAzD,gIAAA,qBAAqB,OAAA;AAC9B,iEAAqE;AAA5D,mIAAA,0BAA0B,OAAA;AACnC,uEAA2E;AAAlE,yIAAA,6BAA6B,OAAA;AACtC,+EAA4E;AAAnE,0IAAA,0BAA0B,OAAA;AACnC,uFAAoF;AAA3E,kJAAA,8BAA8B,OAAA;AACvC,qEAAmE;AAA1D,iIAAA,sBAAsB,OAAA;AAC/B,qFAAiF;AA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OAAA","sourcesContent":["export { CodeValidator, ExecutorResult } from './code-validator';\n\nexport { NoAnyUnknownValidator } from './validate-no-any-unknown';\nexport { NoImplicitAnyValidator } from './validate-no-implicit-any';\nexport { MaxMethodLinesValidator, runModifiedMethods } from './validate-modified-methods';\nexport { runNewMethods } from './validate-new-methods';\nexport { MaxFileLinesValidator } from './validate-modified-files';\nexport { RequireReturnTypeValidator } from './validate-return-types';\nexport { NoInlineTypeLiteralsValidator } from './validate-no-inline-types';\nexport { CatchErrorPatternValidator } from './validate-catch-error-pattern';\nexport { NoUnmanagedExceptionsValidator } from './validate-no-unmanaged-exceptions';\nexport { NoDestructureValidator } from './validate-no-destructure';\nexport { NoDirectApiResolverValidator } from './validate-no-direct-api-resolver';\nexport { NoSymbolDiTokensValidator } from './validate-no-symbol-di-tokens';\nexport { NoClientCreationOutsideServerOrClientValidator } from './validate-no-client-creation-outside-server-or-client';\nexport {\n NoStatePathsInTemplatesValidator,\n StatePathHit,\n StatePathViolation,\n} from './validate-no-state-paths-in-templates';\nexport { ProjectRoleResolver } from './project-role-resolver';\nexport { NoProcessExitOutsideMainValidator } from './validate-no-process-exit-outside-main';\nexport { NoFunctionOutsideClassValidator } from './validate-no-function-outside-class';\nexport {\n InjectAnnotationNotNeededForConcreteClassValidator,\n findRedundantInjectInSource,\n} from './validate-inject-annotation-not-needed-for-concrete-class';\nexport { FrameworkTagValidator } from './validate-framework-tag';\nexport { RoleTagValidator } from './validate-role-tag';\nexport {\n EnsureWeAreSecureValidator,\n SecurityContractViolation,\n auditSecurityContracts,\n findDirectlyChangedProjectRoots,\n} from './validate-ensure-we-are-secure';\nexport { ApiLibFile, ApiLibSite } from './api-lib-source-rule';\nexport { NoInlineImportInApiLibValidator, InlineImportScanner } from './validate-no-inline-import-in-api-lib';\nexport { OneEnumSpellingInApiLibValidator, EnumSpellingScanner } from './validate-one-enum-spelling-in-api-lib';\nexport { NoUtilityTypesInApiLibValidator, UtilityTypeScanner } from './validate-no-utility-types-in-api-lib';\nexport { ApiLibEnumIndex } from './api-lib-enum-index';\nexport { EnumText } from './api-lib-enum-text';\nexport { PrismaValidateDtosValidator } from './validate-dtos';\nexport { PrismaConverterValidator } from './validate-prisma-converters';\nexport { default as validateCode } from './validate-code';\nexport { CodeRulesRunRequest, CodeRulesRunRequestParser } from './code-rules-run-request';\n\nexport { ReactNativeCompatibility } from './react-native-compatibility';\n"]}
@@ -0,0 +1,72 @@
1
+ import { BaseRuleConfig, FileScope } from '@webpieces/rules-config';
2
+ import { CodeRulesRunRequest } from './code-rules-run-request';
3
+ /** What a debug run is judging, for its banner and its per-project report. Data-only. */
4
+ export declare class DebugTarget {
5
+ readonly rule: string;
6
+ /** The mode webpieces.config.json commits the rule to. */
7
+ readonly committedMode: string;
8
+ /** The mode this run judges at (`--mode`, else the committed one). */
9
+ readonly mode: string;
10
+ /** `--projects` as given, or null for every project. */
11
+ readonly projectNames: readonly string[] | null;
12
+ /** Their repo-relative roots, in the same order, or null. */
13
+ readonly projectRoots: readonly string[] | null;
14
+ constructor(rule: string,
15
+ /** The mode webpieces.config.json commits the rule to. */
16
+ committedMode: string,
17
+ /** The mode this run judges at (`--mode`, else the committed one). */
18
+ mode: string,
19
+ /** `--projects` as given, or null for every project. */
20
+ projectNames: readonly string[] | null,
21
+ /** Their repo-relative roots, in the same order, or null. */
22
+ projectRoots: readonly string[] | null);
23
+ }
24
+ /**
25
+ * The {@link FileScope} each rule runs inside, keyed by config key (a match-rule by its name), plus the
26
+ * debug target when this is a debug run. Bound at the composition root; the engine wraps each rule's
27
+ * run in `diffScope.within(scopes.of(key), …)`. A rule with no entry runs in today's plain diff scope.
28
+ */
29
+ export declare class RuleScopes {
30
+ private readonly byKey;
31
+ readonly debugTarget: DebugTarget | null;
32
+ constructor(byKey: ReadonlyMap<string, FileScope>, debugTarget: DebugTarget | null);
33
+ of(key: string): FileScope;
34
+ }
35
+ /**
36
+ * Composition-time planner: turns each rule's COMMITTED config (plus a debug request) into the config
37
+ * the rule actually runs with and the {@link FileScope} it runs inside. This is the one place the
38
+ * whole-scope modes of #1027 are applied to a rule, for every rule at once:
39
+ *
40
+ * - a DIFF-scoped rule whose mode is MODIFIED_PROJECTS / RUN_EVERY_TIME runs with its most-whole
41
+ * per-file mode (e.g. NEW_AND_MODIFIED_FILES) inside a widened FileScope — so the rule's own code
42
+ * never has to know the two modes exist;
43
+ * - a rule whose mode set has no diff-scoped mode (PROJECT_MODES) keeps its mode untouched — its own
44
+ * MODIFIED_PROJECTS is its native behaviour, not a widening;
45
+ * - the debug target additionally takes `--mode`, is restricted to `--projects`, and ignores the two
46
+ * escape hatches for this run (it is a measurement, not the gate).
47
+ *
48
+ * The committed config object is never mutated: a rule that needs a different mode gets a copy.
49
+ */
50
+ export declare class RuleScopePlanner {
51
+ private readonly request;
52
+ private readonly projectRoots;
53
+ /**
54
+ * The one rule whose NEW_AND_MODIFIED_FILES is NOT a whole-file judgement, so the generic choice
55
+ * (WholeScopeModes.wholeFileJudgeMode) would silently judge less than the whole file. max-method-lines at
56
+ * NEW_AND_MODIFIED_FILES runs only its modified-methods sub-check, which leaves every NEW method to
57
+ * the new-methods sub-check — and inside a whole scope every method reads as new. Its
58
+ * NEW_AND_MODIFIED_METHODS runs both sub-checks, which is the whole file. Pinned by
59
+ * whole-scope-modes.spec.ts, which fails if this entry is removed.
60
+ */
61
+ private static readonly WHOLE_FILE_JUDGE_OVERRIDES;
62
+ private readonly scopes;
63
+ private readonly wholeScope;
64
+ private target;
65
+ constructor(request: CodeRulesRunRequest, projectRoots: readonly string[] | null);
66
+ /** The config `key`'s rule runs with. `modeSet` is the modes its schema accepts. */
67
+ plan<C extends BaseRuleConfig>(key: string, config: C, modeSet: readonly string[]): C;
68
+ /** The scopes planned so far. Throws when a debug run named a rule no `plan` call saw. */
69
+ result(): RuleScopes;
70
+ private judgeModeFor;
71
+ private targetMode;
72
+ }
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RuleScopePlanner = exports.RuleScopes = exports.DebugTarget = void 0;
4
+ const rules_config_1 = require("@webpieces/rules-config");
5
+ /** What a debug run is judging, for its banner and its per-project report. Data-only. */
6
+ class DebugTarget {
7
+ rule;
8
+ committedMode;
9
+ mode;
10
+ projectNames;
11
+ projectRoots;
12
+ constructor(rule,
13
+ /** The mode webpieces.config.json commits the rule to. */
14
+ committedMode,
15
+ /** The mode this run judges at (`--mode`, else the committed one). */
16
+ mode,
17
+ /** `--projects` as given, or null for every project. */
18
+ projectNames,
19
+ /** Their repo-relative roots, in the same order, or null. */
20
+ projectRoots) {
21
+ this.rule = rule;
22
+ this.committedMode = committedMode;
23
+ this.mode = mode;
24
+ this.projectNames = projectNames;
25
+ this.projectRoots = projectRoots;
26
+ }
27
+ }
28
+ exports.DebugTarget = DebugTarget;
29
+ /**
30
+ * The {@link FileScope} each rule runs inside, keyed by config key (a match-rule by its name), plus the
31
+ * debug target when this is a debug run. Bound at the composition root; the engine wraps each rule's
32
+ * run in `diffScope.within(scopes.of(key), …)`. A rule with no entry runs in today's plain diff scope.
33
+ */
34
+ class RuleScopes {
35
+ byKey;
36
+ debugTarget;
37
+ constructor(byKey, debugTarget) {
38
+ this.byKey = byKey;
39
+ this.debugTarget = debugTarget;
40
+ }
41
+ of(key) {
42
+ return this.byKey.get(key) ?? rules_config_1.FileScope.DIFF;
43
+ }
44
+ }
45
+ exports.RuleScopes = RuleScopes;
46
+ /**
47
+ * Composition-time planner: turns each rule's COMMITTED config (plus a debug request) into the config
48
+ * the rule actually runs with and the {@link FileScope} it runs inside. This is the one place the
49
+ * whole-scope modes of #1027 are applied to a rule, for every rule at once:
50
+ *
51
+ * - a DIFF-scoped rule whose mode is MODIFIED_PROJECTS / RUN_EVERY_TIME runs with its most-whole
52
+ * per-file mode (e.g. NEW_AND_MODIFIED_FILES) inside a widened FileScope — so the rule's own code
53
+ * never has to know the two modes exist;
54
+ * - a rule whose mode set has no diff-scoped mode (PROJECT_MODES) keeps its mode untouched — its own
55
+ * MODIFIED_PROJECTS is its native behaviour, not a widening;
56
+ * - the debug target additionally takes `--mode`, is restricted to `--projects`, and ignores the two
57
+ * escape hatches for this run (it is a measurement, not the gate).
58
+ *
59
+ * The committed config object is never mutated: a rule that needs a different mode gets a copy.
60
+ */
61
+ class RuleScopePlanner {
62
+ request;
63
+ projectRoots;
64
+ /**
65
+ * The one rule whose NEW_AND_MODIFIED_FILES is NOT a whole-file judgement, so the generic choice
66
+ * (WholeScopeModes.wholeFileJudgeMode) would silently judge less than the whole file. max-method-lines at
67
+ * NEW_AND_MODIFIED_FILES runs only its modified-methods sub-check, which leaves every NEW method to
68
+ * the new-methods sub-check — and inside a whole scope every method reads as new. Its
69
+ * NEW_AND_MODIFIED_METHODS runs both sub-checks, which is the whole file. Pinned by
70
+ * whole-scope-modes.spec.ts, which fails if this entry is removed.
71
+ */
72
+ static WHOLE_FILE_JUDGE_OVERRIDES = new Map([
73
+ ['max-method-lines', 'NEW_AND_MODIFIED_METHODS'],
74
+ ]);
75
+ scopes = new Map();
76
+ wholeScope = new rules_config_1.WholeScopeModes();
77
+ target = null;
78
+ constructor(request, projectRoots) {
79
+ this.request = request;
80
+ this.projectRoots = projectRoots;
81
+ }
82
+ /** The config `key`'s rule runs with. `modeSet` is the modes its schema accepts. */
83
+ plan(key, config, modeSet) {
84
+ const isTarget = this.request.rule === key;
85
+ const committed = config.mode ?? 'OFF';
86
+ const mode = isTarget ? this.targetMode(key, committed, modeSet) : committed;
87
+ const judge = this.wholeScope.isWholeScopeMode(mode) ? this.judgeModeFor(key, modeSet) : null;
88
+ const kind = judge !== null && this.wholeScope.isWholeScopeMode(mode) ? mode : 'DIFF';
89
+ const scope = new rules_config_1.FileScope(kind, isTarget ? this.projectRoots : null);
90
+ if (!scope.isPlainDiff())
91
+ this.scopes.set(key, scope);
92
+ if (isTarget) {
93
+ this.target = new DebugTarget(key, committed, mode, this.request.projects, this.projectRoots);
94
+ }
95
+ if (judge === null && !isTarget)
96
+ return config;
97
+ const copy = Object.assign(Object.create(Object.getPrototypeOf(config)), config);
98
+ const base = copy;
99
+ base.mode = judge ?? mode;
100
+ if (isTarget) {
101
+ base.turnOffRuleUntilEpoch = 0;
102
+ base.turnOffRuleWhileOnBranch = null;
103
+ }
104
+ return copy;
105
+ }
106
+ /** The scopes planned so far. Throws when a debug run named a rule no `plan` call saw. */
107
+ result() {
108
+ const rule = this.request.rule;
109
+ if (rule !== null && this.target === null) {
110
+ throw new rules_config_1.InformAiError(`--rule=${rule} names no code rule and no match-rule in webpieces.config.json. A debug run judges ` +
111
+ `a rule @webpieces/code-rules runs at build time (the keys under "rules", or a "match-rules" name).`);
112
+ }
113
+ return new RuleScopes(this.scopes, this.target);
114
+ }
115
+ judgeModeFor(key, modeSet) {
116
+ const generic = this.wholeScope.wholeFileJudgeMode(modeSet);
117
+ return generic === null ? null : (RuleScopePlanner.WHOLE_FILE_JUDGE_OVERRIDES.get(key) ?? generic);
118
+ }
119
+ targetMode(key, committed, modeSet) {
120
+ const mode = this.request.mode ?? committed;
121
+ if (this.request.mode !== null && !modeSet.includes(mode)) {
122
+ throw new rules_config_1.InformAiError(`--mode=${mode} is not a mode of ${key}. Its modes: ${modeSet.join(', ')}.`);
123
+ }
124
+ if (mode === 'OFF') {
125
+ throw new rules_config_1.InformAiError(`${key} is "mode": "OFF" in webpieces.config.json, so a debug run at the committed mode judges ` +
126
+ `nothing. Pass --mode=<MODE> to judge it at another mode for this run: ${modeSet.filter((m) => m !== 'OFF').join(', ')}.`);
127
+ }
128
+ return mode;
129
+ }
130
+ }
131
+ exports.RuleScopePlanner = RuleScopePlanner;
132
+ //# sourceMappingURL=rule-scope-plan.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rule-scope-plan.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/rule-scope-plan.ts"],"names":[],"mappings":";;;AAAA,0DAAmH;AAInH,yFAAyF;AACzF,MAAa,WAAW;IAEP;IAEA;IAEA;IAEA;IAEA;IATb,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4BAAa,CACnB,GAAG,GAAG,0FAA0F;gBAC5F,yEAAyE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,KAAK,KAAK,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CACxI,CAAC;QACN,CAAC;QACD,OAAO,IAAI,CAAC;IAChB,CAAC;;AA5EL,4CA6EC","sourcesContent":["import { BaseRuleConfig, FileScope, FileScopeKind, InformAiError, WholeScopeModes } from '@webpieces/rules-config';\n\nimport { CodeRulesRunRequest } from './code-rules-run-request';\n\n/** What a debug run is judging, for its banner and its per-project report. Data-only. */\nexport class DebugTarget {\n constructor(\n readonly rule: string,\n /** The mode webpieces.config.json commits the rule to. */\n readonly committedMode: string,\n /** The mode this run judges at (`--mode`, else the committed one). */\n readonly mode: string,\n /** `--projects` as given, or null for every project. */\n readonly projectNames: readonly string[] | null,\n /** Their repo-relative roots, in the same order, or null. */\n readonly projectRoots: readonly string[] | null,\n ) {}\n}\n\n/**\n * The {@link FileScope} each rule runs inside, keyed by config key (a match-rule by its name), plus the\n * debug target when this is a debug run. Bound at the composition root; the engine wraps each rule's\n * run in `diffScope.within(scopes.of(key), …)`. A rule with no entry runs in today's plain diff scope.\n */\nexport class RuleScopes {\n constructor(\n private readonly byKey: ReadonlyMap<string, FileScope>,\n readonly debugTarget: DebugTarget | null,\n ) {}\n\n of(key: string): FileScope {\n return this.byKey.get(key) ?? FileScope.DIFF;\n }\n}\n\n/**\n * Composition-time planner: turns each rule's COMMITTED config (plus a debug request) into the config\n * the rule actually runs with and the {@link FileScope} it runs inside. This is the one place the\n * whole-scope modes of #1027 are applied to a rule, for every rule at once:\n *\n * - a DIFF-scoped rule whose mode is MODIFIED_PROJECTS / RUN_EVERY_TIME runs with its most-whole\n * per-file mode (e.g. NEW_AND_MODIFIED_FILES) inside a widened FileScope — so the rule's own code\n * never has to know the two modes exist;\n * - a rule whose mode set has no diff-scoped mode (PROJECT_MODES) keeps its mode untouched — its own\n * MODIFIED_PROJECTS is its native behaviour, not a widening;\n * - the debug target additionally takes `--mode`, is restricted to `--projects`, and ignores the two\n * escape hatches for this run (it is a measurement, not the gate).\n *\n * The committed config object is never mutated: a rule that needs a different mode gets a copy.\n */\nexport class RuleScopePlanner {\n /**\n * The one rule whose NEW_AND_MODIFIED_FILES is NOT a whole-file judgement, so the generic choice\n * (WholeScopeModes.wholeFileJudgeMode) would silently judge less than the whole file. max-method-lines at\n * NEW_AND_MODIFIED_FILES runs only its modified-methods sub-check, which leaves every NEW method to\n * the new-methods sub-check — and inside a whole scope every method reads as new. Its\n * NEW_AND_MODIFIED_METHODS runs both sub-checks, which is the whole file. Pinned by\n * whole-scope-modes.spec.ts, which fails if this entry is removed.\n */\n private static readonly WHOLE_FILE_JUDGE_OVERRIDES: ReadonlyMap<string, string> = new Map([\n ['max-method-lines', 'NEW_AND_MODIFIED_METHODS'],\n ]);\n\n private readonly scopes = new Map<string, FileScope>();\n private readonly wholeScope = new WholeScopeModes();\n private target: DebugTarget | null = null;\n\n constructor(\n private readonly request: CodeRulesRunRequest,\n private readonly projectRoots: readonly string[] | null,\n ) {}\n\n /** The config `key`'s rule runs with. `modeSet` is the modes its schema accepts. */\n plan<C extends BaseRuleConfig>(key: string, config: C, modeSet: readonly string[]): C {\n const isTarget = this.request.rule === key;\n const committed = config.mode ?? 'OFF';\n const mode = isTarget ? this.targetMode(key, committed, modeSet) : committed;\n const judge = this.wholeScope.isWholeScopeMode(mode) ? this.judgeModeFor(key, modeSet) : null;\n const kind: FileScopeKind = judge !== null && this.wholeScope.isWholeScopeMode(mode) ? mode : 'DIFF';\n const scope = new FileScope(kind, isTarget ? this.projectRoots : null);\n if (!scope.isPlainDiff()) this.scopes.set(key, scope);\n if (isTarget) {\n this.target = new DebugTarget(key, committed, mode, this.request.projects, this.projectRoots);\n }\n if (judge === null && !isTarget) return config;\n const copy = Object.assign(Object.create(Object.getPrototypeOf(config) as object) as C, config);\n const base: BaseRuleConfig = copy;\n base.mode = judge ?? mode;\n if (isTarget) {\n base.turnOffRuleUntilEpoch = 0;\n base.turnOffRuleWhileOnBranch = null;\n }\n return copy;\n }\n\n /** The scopes planned so far. Throws when a debug run named a rule no `plan` call saw. */\n result(): RuleScopes {\n const rule = this.request.rule;\n if (rule !== null && this.target === null) {\n throw new InformAiError(\n `--rule=${rule} names no code rule and no match-rule in webpieces.config.json. A debug run judges ` +\n `a rule @webpieces/code-rules runs at build time (the keys under \"rules\", or a \"match-rules\" name).`,\n );\n }\n return new RuleScopes(this.scopes, this.target);\n }\n\n private judgeModeFor(key: string, modeSet: readonly string[]): string | null {\n const generic = this.wholeScope.wholeFileJudgeMode(modeSet);\n return generic === null ? null : (RuleScopePlanner.WHOLE_FILE_JUDGE_OVERRIDES.get(key) ?? generic);\n }\n\n private targetMode(key: string, committed: string, modeSet: readonly string[]): string {\n const mode = this.request.mode ?? committed;\n if (this.request.mode !== null && !modeSet.includes(mode)) {\n throw new InformAiError(\n `--mode=${mode} is not a mode of ${key}. Its modes: ${modeSet.join(', ')}.`,\n );\n }\n if (mode === 'OFF') {\n throw new InformAiError(\n `${key} is \"mode\": \"OFF\" in webpieces.config.json, so a debug run at the committed mode judges ` +\n `nothing. Pass --mode=<MODE> to judge it at another mode for this run: ${modeSet.filter((m: string) => m !== 'OFF').join(', ')}.`,\n );\n }\n return mode;\n }\n}\n"]}
@@ -1,14 +1,14 @@
1
1
  import 'reflect-metadata';
2
2
  import { ExecutorResult } from './code-validator';
3
+ import { CodeRulesRunRequest } from './code-rules-run-request';
3
4
  export { ExecutorResult } from './code-validator';
4
5
  /**
5
- * Run all configured code validators against the workspace root (the nx `validate-code` executor's
6
+ * Run the configured code validators against the workspace root (the nx `validate-code` executor's
6
7
  * entry, via `@webpieces/code-rules`'s `validateCode` export).
7
8
  *
8
- * Composition root: binds the workspace root + each rule's typed config into an inversify container,
9
- * then RESOLVES {@link CodeRulesApp} so inversify constructs the ENTIRE validator DAG — nothing in the
10
- * DAG is `new`-ed (every validator, the reporter, and the match-rules checker are injected). Config
11
- * comes from webpieces.config.json (loaded via @webpieces/rules-config so ai-hooks and this executor
12
- * agree on every rule's mode/options).
9
+ * `request` is {@link CodeRulesRunRequest.GATE} for the build: every rule at its committed mode. A debug
10
+ * request (`--rule` / `--mode` / `--projects` on the nx target) judges one rule without a config edit.
11
+ * Config comes from webpieces.config.json, loaded via @webpieces/rules-config so ai-hooks and this
12
+ * executor agree on every rule's mode/options; the DAG is built by {@link CodeRulesBootstrap}.
13
13
  */
14
- export default function runValidator(workspaceRoot: string): Promise<ExecutorResult>;
14
+ export default function runValidator(workspaceRoot: string, request: CodeRulesRunRequest): Promise<ExecutorResult>;
@@ -2,37 +2,28 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.default = runValidator;
4
4
  require("reflect-metadata");
5
- const inversify_1 = require("inversify");
6
5
  const rules_config_1 = require("@webpieces/rules-config");
7
6
  const code_rules_app_1 = require("./code-rules-app");
8
- const code_rules_context_1 = require("./code-rules-context");
9
- const code_rules_config_table_1 = require("./code-rules-config-table");
7
+ const code_rules_bootstrap_1 = require("./code-rules-bootstrap");
10
8
  /**
11
- * Run all configured code validators against the workspace root (the nx `validate-code` executor's
9
+ * Run the configured code validators against the workspace root (the nx `validate-code` executor's
12
10
  * entry, via `@webpieces/code-rules`'s `validateCode` export).
13
11
  *
14
- * Composition root: binds the workspace root + each rule's typed config into an inversify container,
15
- * then RESOLVES {@link CodeRulesApp} so inversify constructs the ENTIRE validator DAG — nothing in the
16
- * DAG is `new`-ed (every validator, the reporter, and the match-rules checker are injected). Config
17
- * comes from webpieces.config.json (loaded via @webpieces/rules-config so ai-hooks and this executor
18
- * agree on every rule's mode/options).
12
+ * `request` is {@link CodeRulesRunRequest.GATE} for the build: every rule at its committed mode. A debug
13
+ * request (`--rule` / `--mode` / `--projects` on the nx target) judges one rule without a config edit.
14
+ * Config comes from webpieces.config.json, loaded via @webpieces/rules-config so ai-hooks and this
15
+ * executor agree on every rule's mode/options; the DAG is built by {@link CodeRulesBootstrap}.
19
16
  */
20
- async function runValidator(workspaceRoot) {
17
+ // webpieces-disable no-function-outside-class -- the nx validate-code executor's entry point (exported as validateCode), the executor-side twin of cli.ts main()
18
+ async function runValidator(workspaceRoot, request) {
21
19
  const loaded = (0, rules_config_1.loadAndValidate)(workspaceRoot);
22
20
  if (loaded.configPath === null) {
23
21
  console.error('\n❌ No webpieces.config.json found at workspace root (or any ancestor).\n');
24
22
  return { success: false };
25
23
  }
26
24
  console.log(`\n📄 Loaded config: ${loaded.configPath}`);
27
- // autobind self-binds every @injectable(Singleton) tooling class (replaces the buildProviderModule registry scan)
28
- const container = new inversify_1.Container({ autobind: true });
29
- container.bind(code_rules_context_1.WorkspaceRoot).toConstantValue(new code_rules_context_1.WorkspaceRoot(workspaceRoot));
30
- container.bind(code_rules_context_1.MatchRulesHolder).toConstantValue(new code_rules_context_1.MatchRulesHolder(loaded.matchRules));
31
- for (const binding of code_rules_config_table_1.CONFIG_BINDINGS) {
32
- const ConfigClass = binding[0];
33
- const configured = loaded.rulesConfig[binding[1]];
34
- container.bind(ConfigClass).toConstantValue(configured ?? new ConfigClass());
35
- }
36
- return container.get(code_rules_app_1.CodeRulesApp).run();
25
+ const container = new code_rules_bootstrap_1.CodeRulesBootstrap().container(workspaceRoot, loaded, request);
26
+ const app = container.get(code_rules_app_1.CodeRulesApp);
27
+ return app.run();
37
28
  }
38
29
  //# sourceMappingURL=validate-code.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate-code.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-code.ts"],"names":[],"mappings":";;AAqBA,+BAmBC;AAxCD,4BAA0B;AAC1B,yCAAsC;AACtC,0DAA0E;AAG1E,qDAAgD;AAChD,6DAAuE;AACvE,uEAA4D;AAI5D;;;;;;;;;GASG;AACY,KAAK,UAAU,YAAY,CAAC,aAAqB;IAC5D,MAAM,MAAM,GAAG,IAAA,8BAAe,EAAC,aAAa,CAAC,CAAC;IAC9C,IAAI,MAAM,CAAC,UAAU,KAAK,IAAI,EAAE,CAAC;QAC7B,OAAO,CAAC,KAAK,CAAC,2EAA2E,CAAC,CAAC;QAC3F,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,uBAAuB,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC;IAExD,kHAAkH;IAClH,MAAM,SAAS,GAAG,IAAI,qBAAS,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;IACpD,SAAS,CAAC,IAAI,CAAC,kCAAa,CAAC,CAAC,eAAe,CAAC,IAAI,kCAAa,CAAC,aAAa,CAAC,CAAC,CAAC;IAChF,SAAS,CAAC,IAAI,CAAC,qCAAgB,CAAC,CAAC,eAAe,CAAC,IAAI,qCAAgB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC;IAC1F,KAAK,MAAM,OAAO,IAAI,yCAAe,EAAE,CAAC;QACpC,MAAM,WAAW,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;QAC/B,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAA+B,CAAC;QAChF,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,eAAe,CAAC,UAAU,IAAI,IAAI,WAAW,EAAE,CAAC,CAAC;IACjF,CAAC;IAED,OAAO,SAAS,CAAC,GAAG,CAAC,6BAAY,CAAC,CAAC,GAAG,EAAE,CAAC;AAC7C,CAAC","sourcesContent":["import 'reflect-metadata';\nimport { Container } from 'inversify';\nimport { loadAndValidate, BaseRuleConfig } from '@webpieces/rules-config';\n\nimport { ExecutorResult } from './code-validator';\nimport { CodeRulesApp } from './code-rules-app';\nimport { WorkspaceRoot, MatchRulesHolder } from './code-rules-context';\nimport { CONFIG_BINDINGS } from './code-rules-config-table';\n\nexport { ExecutorResult } from './code-validator';\n\n/**\n * Run all configured code validators against the workspace root (the nx `validate-code` executor's\n * entry, via `@webpieces/code-rules`'s `validateCode` export).\n *\n * Composition root: binds the workspace root + each rule's typed config into an inversify container,\n * then RESOLVES {@link CodeRulesApp} so inversify constructs the ENTIRE validator DAG — nothing in the\n * DAG is `new`-ed (every validator, the reporter, and the match-rules checker are injected). Config\n * comes from webpieces.config.json (loaded via @webpieces/rules-config so ai-hooks and this executor\n * agree on every rule's mode/options).\n */\nexport default async function runValidator(workspaceRoot: string): Promise<ExecutorResult> {\n const loaded = loadAndValidate(workspaceRoot);\n if (loaded.configPath === null) {\n console.error('\\n❌ No webpieces.config.json found at workspace root (or any ancestor).\\n');\n return { success: false };\n }\n console.log(`\\n📄 Loaded config: ${loaded.configPath}`);\n\n // autobind self-binds every @injectable(Singleton) tooling class (replaces the buildProviderModule registry scan)\n const container = new Container({ autobind: true });\n container.bind(WorkspaceRoot).toConstantValue(new WorkspaceRoot(workspaceRoot));\n container.bind(MatchRulesHolder).toConstantValue(new MatchRulesHolder(loaded.matchRules));\n for (const binding of CONFIG_BINDINGS) {\n const ConfigClass = binding[0];\n const configured = loaded.rulesConfig[binding[1]] as BaseRuleConfig | undefined;\n container.bind(ConfigClass).toConstantValue(configured ?? new ConfigClass());\n }\n\n return container.get(CodeRulesApp).run();\n}\n"]}
1
+ {"version":3,"file":"validate-code.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/validate-code.ts"],"names":[],"mappings":";;AAoBA,+BAaC;AAjCD,4BAA0B;AAC1B,0DAA0D;AAG1D,qDAAgD;AAChD,iEAA4D;AAK5D;;;;;;;;GAQG;AACH,iKAAiK;AAClJ,KAAK,UAAU,YAAY,CACtC,aAAqB,EACrB,OAA4B;IAE5B,MAAM,MAAM,GAAG,IAAA,8BAAe,EAAC,aAAa,CAAC,CAAC;IAC9C,IAAI,MAAM,CAAC,UAAU,KAAK,IAAI,EAAE,CAAC;QAC7B,OAAO,CAAC,KAAK,CAAC,2EAA2E,CAAC,CAAC;QAC3F,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,uBAAuB,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC;IACxD,MAAM,SAAS,GAAG,IAAI,yCAAkB,EAAE,CAAC,SAAS,CAAC,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IACrF,MAAM,GAAG,GAAG,SAAS,CAAC,GAAG,CAAC,6BAAY,CAAC,CAAC;IACxC,OAAO,GAAG,CAAC,GAAG,EAAE,CAAC;AACrB,CAAC","sourcesContent":["import 'reflect-metadata';\nimport { loadAndValidate } from '@webpieces/rules-config';\n\nimport { ExecutorResult } from './code-validator';\nimport { CodeRulesApp } from './code-rules-app';\nimport { CodeRulesBootstrap } from './code-rules-bootstrap';\nimport { CodeRulesRunRequest } from './code-rules-run-request';\n\nexport { ExecutorResult } from './code-validator';\n\n/**\n * Run the configured code validators against the workspace root (the nx `validate-code` executor's\n * entry, via `@webpieces/code-rules`'s `validateCode` export).\n *\n * `request` is {@link CodeRulesRunRequest.GATE} for the build: every rule at its committed mode. A debug\n * request (`--rule` / `--mode` / `--projects` on the nx target) judges one rule without a config edit.\n * Config comes from webpieces.config.json, loaded via @webpieces/rules-config so ai-hooks and this\n * executor agree on every rule's mode/options; the DAG is built by {@link CodeRulesBootstrap}.\n */\n// webpieces-disable no-function-outside-class -- the nx validate-code executor's entry point (exported as validateCode), the executor-side twin of cli.ts main()\nexport default async function runValidator(\n workspaceRoot: string,\n request: CodeRulesRunRequest,\n): Promise<ExecutorResult> {\n const loaded = loadAndValidate(workspaceRoot);\n if (loaded.configPath === null) {\n console.error('\\n❌ No webpieces.config.json found at workspace root (or any ancestor).\\n');\n return { success: false };\n }\n console.log(`\\n📄 Loaded config: ${loaded.configPath}`);\n const container = new CodeRulesBootstrap().container(workspaceRoot, loaded, request);\n const app = container.get(CodeRulesApp);\n return app.run();\n}\n"]}
@@ -11,7 +11,8 @@
11
11
  * flags violations on changed lines, so a legacy Angular app is never retroactively flooded — the
12
12
  * rule bites when a file is next edited.
13
13
  *
14
- * MODES: OFF | NEW_AND_MODIFIED_CODE (changed lines) | NEW_AND_MODIFIED_FILES (all in changed files).
14
+ * MODES: OFF | NEW_AND_MODIFIED_CODE (changed lines) | NEW_AND_MODIFIED_FILES (all in changed files)
15
+ * | MODIFIED_PROJECTS / RUN_EVERY_TIME (whole-scope, #1027 — widened centrally by DiffScope).
15
16
  *
16
17
  * ESCAPE HATCH (a genuinely dynamic runtime value):
17
18
  * .ts: // webpieces-disable no-custom-css -- <reason>
@@ -12,7 +12,8 @@
12
12
  * flags violations on changed lines, so a legacy Angular app is never retroactively flooded — the
13
13
  * rule bites when a file is next edited.
14
14
  *
15
- * MODES: OFF | NEW_AND_MODIFIED_CODE (changed lines) | NEW_AND_MODIFIED_FILES (all in changed files).
15
+ * MODES: OFF | NEW_AND_MODIFIED_CODE (changed lines) | NEW_AND_MODIFIED_FILES (all in changed files)
16
+ * | MODIFIED_PROJECTS / RUN_EVERY_TIME (whole-scope, #1027 — widened centrally by DiffScope).
16
17
  *
17
18
  * ESCAPE HATCH (a genuinely dynamic runtime value):
18
19
  * .ts: // webpieces-disable no-custom-css -- <reason>