@webpieces/code-rules 0.4.813 → 0.4.814
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/api-lib-source-rule.d.ts +10 -5
- package/src/api-lib-source-rule.js +13 -4
- package/src/api-lib-source-rule.js.map +1 -1
- package/src/code-rules-config-table.js +1 -0
- package/src/code-rules-config-table.js.map +1 -1
- package/src/code-rules-engine.d.ts +3 -1
- package/src/code-rules-engine.js +7 -2
- package/src/code-rules-engine.js.map +1 -1
- package/src/index.d.ts +1 -0
- package/src/index.js +4 -1
- package/src/index.js.map +1 -1
- package/src/validate-no-utility-types-in-api-lib.d.ts +58 -0
- package/src/validate-no-utility-types-in-api-lib.js +176 -0
- package/src/validate-no-utility-types-in-api-lib.js.map +1 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/code-rules",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.814",
|
|
4
4
|
"description": "Standalone code validation rules extracted from architecture-validators, no Nx dependency required",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"directory": "packages/tooling/code-rules"
|
|
17
17
|
},
|
|
18
18
|
"dependencies": {
|
|
19
|
-
"@webpieces/rules-config": "0.4.
|
|
19
|
+
"@webpieces/rules-config": "0.4.814",
|
|
20
20
|
"@inversifyjs/binding-decorators": "1.1.5",
|
|
21
21
|
"inversify": "7.10.4",
|
|
22
22
|
"reflect-metadata": "0.2.2"
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The shared half of the two `role:api-lib` spelling rules (#1023)
|
|
3
|
-
* `one-enum-spelling-in-api-lib
|
|
2
|
+
* The shared half of the api-library source rules: the two `role:api-lib` spelling rules (#1023),
|
|
3
|
+
* `no-inline-import-in-api-lib` and `one-enum-spelling-in-api-lib`, and `no-utility-types-in-api-lib`
|
|
4
|
+
* (#1026), which scopes itself by its configured `paths` globs instead of the role tag.
|
|
4
5
|
*
|
|
5
6
|
* Both judge the SOURCE of an api library — the contract every consumer and the OpenAPI / MCP
|
|
6
7
|
* generator read — and both have the same rollout shape: `mode` NEW_AND_MODIFIED_CODE judges only the
|
|
@@ -13,7 +14,7 @@
|
|
|
13
14
|
* what it refuses, and a parse cannot be diverted to a `.d.ts` by module resolution.
|
|
14
15
|
*/
|
|
15
16
|
import * as ts from 'typescript';
|
|
16
|
-
import { DiffScope, NoInlineImportInApiLibConfig, OneEnumSpellingInApiLibConfig } from '@webpieces/rules-config';
|
|
17
|
+
import { DiffScope, NoInlineImportInApiLibConfig, NoUtilityTypesInApiLibConfig, OneEnumSpellingInApiLibConfig } from '@webpieces/rules-config';
|
|
17
18
|
import { CodeValidator, ExecutorResult } from './code-validator';
|
|
18
19
|
import { ProjectRoleResolver } from './project-role-resolver';
|
|
19
20
|
/** One violating site: where, what it is, and the edit that replaces it. Data-only. */
|
|
@@ -47,7 +48,7 @@ export declare class ApiLibFile {
|
|
|
47
48
|
/** A site at `node`, its text collapsed to one line. */
|
|
48
49
|
site(node: ts.Node, what: string, cure: string): ApiLibSite;
|
|
49
50
|
}
|
|
50
|
-
type ApiLibConfig = NoInlineImportInApiLibConfig | OneEnumSpellingInApiLibConfig;
|
|
51
|
+
type ApiLibConfig = NoInlineImportInApiLibConfig | OneEnumSpellingInApiLibConfig | NoUtilityTypesInApiLibConfig;
|
|
51
52
|
export declare abstract class ApiLibSourceRule<C extends ApiLibConfig> extends CodeValidator<C> {
|
|
52
53
|
private readonly roleResolver;
|
|
53
54
|
private readonly diffScope;
|
|
@@ -59,8 +60,12 @@ export declare abstract class ApiLibSourceRule<C extends ApiLibConfig> extends C
|
|
|
59
60
|
run(workspaceRoot: string): Promise<ExecutorResult>;
|
|
60
61
|
/** The unexempt, in-scope violating sites of one changed file. */
|
|
61
62
|
private judge;
|
|
62
|
-
/** A non-test `.ts` file, not under `allowedPaths`,
|
|
63
|
+
/** A non-test `.ts` file, not under `allowedPaths`, that {@link isApiLibrarySource} claims. */
|
|
63
64
|
private inScope;
|
|
65
|
+
/** Is `relFile` part of an api library? By default: its owning project is tagged `role:api-lib`. */
|
|
66
|
+
protected isApiLibrarySource(workspaceRoot: string, relFile: string): boolean;
|
|
67
|
+
/** How the failure names where the sites are — must agree with {@link isApiLibrarySource}. */
|
|
68
|
+
protected scopeLabel(): string;
|
|
64
69
|
/** `// webpieces-disable <rule> -- <reason>` on the site's line or the line above. */
|
|
65
70
|
private disabled;
|
|
66
71
|
/** The nearest ancestor of `relFile` holding a project.json, absolute. */
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
/**
|
|
3
|
-
* The shared half of the two `role:api-lib` spelling rules (#1023)
|
|
4
|
-
* `one-enum-spelling-in-api-lib
|
|
3
|
+
* The shared half of the api-library source rules: the two `role:api-lib` spelling rules (#1023),
|
|
4
|
+
* `no-inline-import-in-api-lib` and `one-enum-spelling-in-api-lib`, and `no-utility-types-in-api-lib`
|
|
5
|
+
* (#1026), which scopes itself by its configured `paths` globs instead of the role tag.
|
|
5
6
|
*
|
|
6
7
|
* Both judge the SOURCE of an api library — the contract every consumer and the OpenAPI / MCP
|
|
7
8
|
* generator read — and both have the same rollout shape: `mode` NEW_AND_MODIFIED_CODE judges only the
|
|
@@ -121,7 +122,7 @@ class ApiLibSourceRule extends code_validator_1.CodeValidator {
|
|
|
121
122
|
.filter((site) => !this.disabled(lines, site.line))
|
|
122
123
|
.map((site) => new FoundSite(relFile, site));
|
|
123
124
|
}
|
|
124
|
-
/** A non-test `.ts` file, not under `allowedPaths`,
|
|
125
|
+
/** A non-test `.ts` file, not under `allowedPaths`, that {@link isApiLibrarySource} claims. */
|
|
125
126
|
inScope(workspaceRoot, relFile) {
|
|
126
127
|
if (!relFile.endsWith('.ts') || relFile.endsWith('.d.ts'))
|
|
127
128
|
return false;
|
|
@@ -131,8 +132,16 @@ class ApiLibSourceRule extends code_validator_1.CodeValidator {
|
|
|
131
132
|
return false;
|
|
132
133
|
if (!fs.existsSync(path.join(workspaceRoot, relFile)))
|
|
133
134
|
return false;
|
|
135
|
+
return this.isApiLibrarySource(workspaceRoot, relFile);
|
|
136
|
+
}
|
|
137
|
+
/** Is `relFile` part of an api library? By default: its owning project is tagged `role:api-lib`. */
|
|
138
|
+
isApiLibrarySource(workspaceRoot, relFile) {
|
|
134
139
|
return this.roleResolver.roleOf(workspaceRoot, relFile) === API_LIB_ROLE;
|
|
135
140
|
}
|
|
141
|
+
/** How the failure names where the sites are — must agree with {@link isApiLibrarySource}. */
|
|
142
|
+
scopeLabel() {
|
|
143
|
+
return 'a role:api-lib project';
|
|
144
|
+
}
|
|
136
145
|
/** `// webpieces-disable <rule> -- <reason>` on the site's line or the line above. */
|
|
137
146
|
disabled(lines, line) {
|
|
138
147
|
return (0, rules_config_1.hasDisable)(lines[line - 1] ?? '', this.name) || (0, rules_config_1.hasDisable)(lines[line - 2] ?? '', this.name);
|
|
@@ -146,7 +155,7 @@ class ApiLibSourceRule extends code_validator_1.CodeValidator {
|
|
|
146
155
|
return dir;
|
|
147
156
|
}
|
|
148
157
|
failure(found) {
|
|
149
|
-
const message = `${found.length} site(s) in
|
|
158
|
+
const message = `${found.length} site(s) in ${this.scopeLabel()}: ${this.why()}\n` +
|
|
150
159
|
found.map((each) => ` ${each.relFile}:${each.site.line} — ${each.site.what}\n ${each.site.snippet}`).join('\n') +
|
|
151
160
|
`\n Last resort, per site: // webpieces-disable ${this.name} -- <reason>`;
|
|
152
161
|
return new rules_config_1.RuleFailError(this.name, message, undefined, undefined, found.map((each) => new rules_config_1.Option(`${each.relFile}:${each.site.line}: ${each.site.cure}`, true)));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-lib-source-rule.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/api-lib-source-rule.ts"],"names":[],"mappings":";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ClE,YAAY,CAAC,aAAqB,EAAE,OAAe;QACvD,IAAI,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC,CAAC;QAC1D,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,GAAG,EAAE,CAAC;YACjF,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAC5B,CAAC;QACD,OAAO,GAAG,CAAC;IACf,CAAC;IAEO,OAAO,CAAC,KAA2B;QACvC,MAAM,OAAO,GACT,GAAG,KAAK,CAAC,MAAM,uCAAuC,IAAI,CAAC,GAAG,EAAE,IAAI;YACpE,KAAK,CAAC,GAAG,CAAC,CAAC,IAAe,EAAE,EAAE,CAAC,KAAK,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,CAAC,IAAI,WAAW,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;YAChI,mDAAmD,IAAI,CAAC,IAAI,cAAc,CAAC;QAC/E,OAAO,IAAI,4BAAa,CACpB,IAAI,CAAC,IAAI,EACT,OAAO,EACP,SAAS,EACT,SAAS,EACT,KAAK,CAAC,GAAG,CAAC,CAAC,IAAe,EAAE,EAAE,CAAC,IAAI,qBAAM,CAAC,GAAG,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,IAAI,CAAC,CAAC,CAC3G,CAAC;IACN,CAAC;CACJ;AA9FD,4CA8FC","sourcesContent":["/**\n * The shared half of the two `role:api-lib` spelling rules (#1023): `no-inline-import-in-api-lib` and\n * `one-enum-spelling-in-api-lib`.\n *\n * Both judge the SOURCE of an api library — the contract every consumer and the OpenAPI / MCP\n * generator read — and both have the same rollout shape: `mode` NEW_AND_MODIFIED_CODE judges only the\n * changed lines (so existing code is grandfathered until someone touches it), NEW_AND_MODIFIED_FILES\n * judges every site in a changed file. This class owns that scoping, the api-lib test, the escape\n * hatches, and the ONE failure spelling: a thrown `RuleFailError` with one `Option` per site, which\n * `RuleReporter` renders. A subclass only says what a violating site IS.\n *\n * Parser-only on purpose (no `ts.Program`): each rule reads the syntax as written, which is exactly\n * what it refuses, and a parse cannot be diverted to a `.d.ts` by module resolution.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport {\n DiffScope,\n ModifiedCodeMode,\n NoInlineImportInApiLibConfig,\n OneEnumSpellingInApiLibConfig,\n Option,\n RuleFailError,\n hasDisable,\n isPathExcluded,\n} from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { ProjectRoleResolver } from './project-role-resolver';\n\n/** The role these rules judge. */\nconst API_LIB_ROLE = 'api-lib';\n\n/** One violating site: where, what it is, and the edit that replaces it. Data-only. */\nexport class ApiLibSite {\n constructor(\n /** 1-based line of the site's first character. */\n readonly line: number,\n /** The offending source text, trimmed to one line. */\n readonly snippet: string,\n readonly what: string,\n readonly cure: string,\n ) {}\n}\n\n/** One api-library source file, parsed, with the project directory that owns it. Data-only. */\nexport class ApiLibFile {\n constructor(\n /** Workspace-relative. */\n readonly relFile: string,\n readonly source: ts.SourceFile,\n /** Absolute path of the owning project's directory (the one holding project.json). */\n readonly projectDir: string,\n ) {}\n\n /** The 1-based line a node starts on. */\n lineOf(node: ts.Node): number {\n return this.source.getLineAndCharacterOfPosition(node.getStart(this.source)).line + 1;\n }\n\n /** A site at `node`, its text collapsed to one line. */\n site(node: ts.Node, what: string, cure: string): ApiLibSite {\n const text = node.getText(this.source).replace(/\\s+/g, ' ').trim();\n return new ApiLibSite(this.lineOf(node), text, what, cure);\n }\n}\n\n/** A located site, for the failure message. Data-only. */\nclass FoundSite {\n constructor(\n readonly relFile: string,\n readonly site: ApiLibSite,\n ) {}\n}\n\ntype ApiLibConfig = NoInlineImportInApiLibConfig | OneEnumSpellingInApiLibConfig;\n\nexport abstract class ApiLibSourceRule<C extends ApiLibConfig> extends CodeValidator<C> {\n constructor(\n config: C,\n ruleName: string,\n private readonly roleResolver: ProjectRoleResolver,\n private readonly diffScope: DiffScope,\n ) {\n super(config, ruleName, ruleName);\n }\n\n /** Every violating site in one api-library file. */\n protected abstract sitesIn(file: ApiLibFile): ApiLibSite[];\n\n /** The one-sentence WHY printed above the sites. */\n protected abstract why(): string;\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n const mode: ModifiedCodeMode | undefined = this.config.mode;\n if (mode === undefined || mode === 'OFF') return { success: true };\n // NX_BASE / NX_HEAD when nx set them, else the merge-base with main.\n const range = this.diffScope.resolveBase(workspaceRoot);\n const base = range.base;\n if (base === undefined) {\n console.log(`\\n⏭️ Skipping ${this.name} validation (could not detect base branch)\\n`);\n return { success: true };\n }\n const found: FoundSite[] = [];\n for (const relFile of this.diffScope.getChangedFiles(workspaceRoot, base, range.head)) {\n found.push(...this.judge(workspaceRoot, relFile, mode, base, range.head));\n }\n if (found.length === 0) return { success: true };\n throw this.failure(found);\n }\n\n /** The unexempt, in-scope violating sites of one changed file. */\n private judge(\n workspaceRoot: string,\n relFile: string,\n mode: ModifiedCodeMode,\n base: string,\n head: string | undefined,\n ): FoundSite[] {\n if (!this.inScope(workspaceRoot, relFile)) return [];\n const changedLines = mode === 'NEW_AND_MODIFIED_CODE'\n ? this.diffScope.getChangedLineNumbers(this.diffScope.getFileDiff(workspaceRoot, relFile, base, head))\n : undefined;\n if (changedLines !== undefined && changedLines.size === 0) return [];\n const absFile = path.join(workspaceRoot, relFile);\n const text = fs.readFileSync(absFile, 'utf8');\n const lines = text.split('\\n');\n const source = ts.createSourceFile(absFile, text, ts.ScriptTarget.Latest, true);\n const file = new ApiLibFile(relFile, source, this.projectDirOf(workspaceRoot, relFile));\n return this.sitesIn(file)\n .filter((site: ApiLibSite) => changedLines === undefined || changedLines.has(site.line))\n .filter((site: ApiLibSite) => !this.disabled(lines, site.line))\n .map((site: ApiLibSite) => new FoundSite(relFile, site));\n }\n\n /** A non-test `.ts` file, not under `allowedPaths`, owned by a `role:api-lib` project. */\n private inScope(workspaceRoot: string, relFile: string): boolean {\n if (!relFile.endsWith('.ts') || relFile.endsWith('.d.ts')) return false;\n if (/\\.(spec|test)\\.ts$/.test(relFile) || relFile.includes('__tests__/')) return false;\n if (isPathExcluded(relFile, this.config.allowedPaths ?? [])) return false;\n if (!fs.existsSync(path.join(workspaceRoot, relFile))) return false;\n return this.roleResolver.roleOf(workspaceRoot, relFile) === API_LIB_ROLE;\n }\n\n /** `// webpieces-disable <rule> -- <reason>` on the site's line or the line above. */\n private disabled(lines: readonly string[], line: number): boolean {\n return hasDisable(lines[line - 1] ?? '', this.name) || hasDisable(lines[line - 2] ?? '', this.name);\n }\n\n /** The nearest ancestor of `relFile` holding a project.json, absolute. */\n private projectDirOf(workspaceRoot: string, relFile: string): string {\n let dir = path.dirname(path.join(workspaceRoot, relFile));\n while (!fs.existsSync(path.join(dir, 'project.json')) && path.dirname(dir) !== dir) {\n dir = path.dirname(dir);\n }\n return dir;\n }\n\n private failure(found: readonly FoundSite[]): RuleFailError {\n const message =\n `${found.length} site(s) in a role:api-lib project: ${this.why()}\\n` +\n found.map((each: FoundSite) => ` ${each.relFile}:${each.site.line} — ${each.site.what}\\n ${each.site.snippet}`).join('\\n') +\n `\\n Last resort, per site: // webpieces-disable ${this.name} -- <reason>`;\n return new RuleFailError(\n this.name,\n message,\n undefined,\n undefined,\n found.map((each: FoundSite) => new Option(`${each.relFile}:${each.site.line}: ${each.site.cure}`, true)),\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"api-lib-source-rule.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/api-lib-source-rule.ts"],"names":[],"mappings":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,CAAC,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,IAAI,CAAC,CAAC,CAC3G,CAAC;IACN,CAAC;CACJ;AAxGD,4CAwGC","sourcesContent":["/**\n * The shared half of the api-library source rules: the two `role:api-lib` spelling rules (#1023),\n * `no-inline-import-in-api-lib` and `one-enum-spelling-in-api-lib`, and `no-utility-types-in-api-lib`\n * (#1026), which scopes itself by its configured `paths` globs instead of the role tag.\n *\n * Both judge the SOURCE of an api library — the contract every consumer and the OpenAPI / MCP\n * generator read — and both have the same rollout shape: `mode` NEW_AND_MODIFIED_CODE judges only the\n * changed lines (so existing code is grandfathered until someone touches it), NEW_AND_MODIFIED_FILES\n * judges every site in a changed file. This class owns that scoping, the api-lib test, the escape\n * hatches, and the ONE failure spelling: a thrown `RuleFailError` with one `Option` per site, which\n * `RuleReporter` renders. A subclass only says what a violating site IS.\n *\n * Parser-only on purpose (no `ts.Program`): each rule reads the syntax as written, which is exactly\n * what it refuses, and a parse cannot be diverted to a `.d.ts` by module resolution.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as ts from 'typescript';\nimport {\n DiffScope,\n ModifiedCodeMode,\n NoInlineImportInApiLibConfig,\n NoUtilityTypesInApiLibConfig,\n OneEnumSpellingInApiLibConfig,\n Option,\n RuleFailError,\n hasDisable,\n isPathExcluded,\n} from '@webpieces/rules-config';\nimport { CodeValidator, ExecutorResult } from './code-validator';\nimport { ProjectRoleResolver } from './project-role-resolver';\n\n/** The role these rules judge. */\nconst API_LIB_ROLE = 'api-lib';\n\n/** One violating site: where, what it is, and the edit that replaces it. Data-only. */\nexport class ApiLibSite {\n constructor(\n /** 1-based line of the site's first character. */\n readonly line: number,\n /** The offending source text, trimmed to one line. */\n readonly snippet: string,\n readonly what: string,\n readonly cure: string,\n ) {}\n}\n\n/** One api-library source file, parsed, with the project directory that owns it. Data-only. */\nexport class ApiLibFile {\n constructor(\n /** Workspace-relative. */\n readonly relFile: string,\n readonly source: ts.SourceFile,\n /** Absolute path of the owning project's directory (the one holding project.json). */\n readonly projectDir: string,\n ) {}\n\n /** The 1-based line a node starts on. */\n lineOf(node: ts.Node): number {\n return this.source.getLineAndCharacterOfPosition(node.getStart(this.source)).line + 1;\n }\n\n /** A site at `node`, its text collapsed to one line. */\n site(node: ts.Node, what: string, cure: string): ApiLibSite {\n const text = node.getText(this.source).replace(/\\s+/g, ' ').trim();\n return new ApiLibSite(this.lineOf(node), text, what, cure);\n }\n}\n\n/** A located site, for the failure message. Data-only. */\nclass FoundSite {\n constructor(\n readonly relFile: string,\n readonly site: ApiLibSite,\n ) {}\n}\n\ntype ApiLibConfig = NoInlineImportInApiLibConfig | OneEnumSpellingInApiLibConfig | NoUtilityTypesInApiLibConfig;\n\nexport abstract class ApiLibSourceRule<C extends ApiLibConfig> extends CodeValidator<C> {\n constructor(\n config: C,\n ruleName: string,\n private readonly roleResolver: ProjectRoleResolver,\n private readonly diffScope: DiffScope,\n ) {\n super(config, ruleName, ruleName);\n }\n\n /** Every violating site in one api-library file. */\n protected abstract sitesIn(file: ApiLibFile): ApiLibSite[];\n\n /** The one-sentence WHY printed above the sites. */\n protected abstract why(): string;\n\n async run(workspaceRoot: string): Promise<ExecutorResult> {\n const mode: ModifiedCodeMode | undefined = this.config.mode;\n if (mode === undefined || mode === 'OFF') return { success: true };\n // NX_BASE / NX_HEAD when nx set them, else the merge-base with main.\n const range = this.diffScope.resolveBase(workspaceRoot);\n const base = range.base;\n if (base === undefined) {\n console.log(`\\n⏭️ Skipping ${this.name} validation (could not detect base branch)\\n`);\n return { success: true };\n }\n const found: FoundSite[] = [];\n for (const relFile of this.diffScope.getChangedFiles(workspaceRoot, base, range.head)) {\n found.push(...this.judge(workspaceRoot, relFile, mode, base, range.head));\n }\n if (found.length === 0) return { success: true };\n throw this.failure(found);\n }\n\n /** The unexempt, in-scope violating sites of one changed file. */\n private judge(\n workspaceRoot: string,\n relFile: string,\n mode: ModifiedCodeMode,\n base: string,\n head: string | undefined,\n ): FoundSite[] {\n if (!this.inScope(workspaceRoot, relFile)) return [];\n const changedLines = mode === 'NEW_AND_MODIFIED_CODE'\n ? this.diffScope.getChangedLineNumbers(this.diffScope.getFileDiff(workspaceRoot, relFile, base, head))\n : undefined;\n if (changedLines !== undefined && changedLines.size === 0) return [];\n const absFile = path.join(workspaceRoot, relFile);\n const text = fs.readFileSync(absFile, 'utf8');\n const lines = text.split('\\n');\n const source = ts.createSourceFile(absFile, text, ts.ScriptTarget.Latest, true);\n const file = new ApiLibFile(relFile, source, this.projectDirOf(workspaceRoot, relFile));\n return this.sitesIn(file)\n .filter((site: ApiLibSite) => changedLines === undefined || changedLines.has(site.line))\n .filter((site: ApiLibSite) => !this.disabled(lines, site.line))\n .map((site: ApiLibSite) => new FoundSite(relFile, site));\n }\n\n /** A non-test `.ts` file, not under `allowedPaths`, that {@link isApiLibrarySource} claims. */\n private inScope(workspaceRoot: string, relFile: string): boolean {\n if (!relFile.endsWith('.ts') || relFile.endsWith('.d.ts')) return false;\n if (/\\.(spec|test)\\.ts$/.test(relFile) || relFile.includes('__tests__/')) return false;\n if (isPathExcluded(relFile, this.config.allowedPaths ?? [])) return false;\n if (!fs.existsSync(path.join(workspaceRoot, relFile))) return false;\n return this.isApiLibrarySource(workspaceRoot, relFile);\n }\n\n /** Is `relFile` part of an api library? By default: its owning project is tagged `role:api-lib`. */\n protected isApiLibrarySource(workspaceRoot: string, relFile: string): boolean {\n return this.roleResolver.roleOf(workspaceRoot, relFile) === API_LIB_ROLE;\n }\n\n /** How the failure names where the sites are — must agree with {@link isApiLibrarySource}. */\n protected scopeLabel(): string {\n return 'a role:api-lib project';\n }\n\n /** `// webpieces-disable <rule> -- <reason>` on the site's line or the line above. */\n private disabled(lines: readonly string[], line: number): boolean {\n return hasDisable(lines[line - 1] ?? '', this.name) || hasDisable(lines[line - 2] ?? '', this.name);\n }\n\n /** The nearest ancestor of `relFile` holding a project.json, absolute. */\n private projectDirOf(workspaceRoot: string, relFile: string): string {\n let dir = path.dirname(path.join(workspaceRoot, relFile));\n while (!fs.existsSync(path.join(dir, 'project.json')) && path.dirname(dir) !== dir) {\n dir = path.dirname(dir);\n }\n return dir;\n }\n\n private failure(found: readonly FoundSite[]): RuleFailError {\n const message =\n `${found.length} site(s) in ${this.scopeLabel()}: ${this.why()}\\n` +\n found.map((each: FoundSite) => ` ${each.relFile}:${each.site.line} — ${each.site.what}\\n ${each.site.snippet}`).join('\\n') +\n `\\n Last resort, per site: // webpieces-disable ${this.name} -- <reason>`;\n return new RuleFailError(\n this.name,\n message,\n undefined,\n undefined,\n found.map((each: FoundSite) => new Option(`${each.relFile}:${each.site.line}: ${each.site.cure}`, true)),\n );\n }\n}\n"]}
|
|
@@ -36,5 +36,6 @@ exports.CONFIG_BINDINGS = [
|
|
|
36
36
|
[rules_config_1.EnsureWeAreSecureConfig, 'ensure-we-are-secure'],
|
|
37
37
|
[rules_config_1.NoInlineImportInApiLibConfig, 'no-inline-import-in-api-lib'],
|
|
38
38
|
[rules_config_1.OneEnumSpellingInApiLibConfig, 'one-enum-spelling-in-api-lib'],
|
|
39
|
+
[rules_config_1.NoUtilityTypesInApiLibConfig, 'no-utility-types-in-api-lib'],
|
|
39
40
|
];
|
|
40
41
|
//# sourceMappingURL=code-rules-config-table.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"code-rules-config-table.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/code-rules-config-table.ts"],"names":[],"mappings":";;;AAAA,
|
|
1
|
+
{"version":3,"file":"code-rules-config-table.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/code-rules-config-table.ts"],"names":[],"mappings":";;;AAAA,0DA4BiC;AAKjC;;;;;GAKG;AACU,QAAA,eAAe,GAAqE;IAC7F,CAAC,mCAAoB,EAAE,kBAAkB,CAAC;IAC1C,CAAC,iCAAkB,EAAE,gBAAgB,CAAC;IACtC,CAAC,sCAAuB,EAAE,qBAAqB,CAAC;IAChD,CAAC,yCAA0B,EAAE,yBAAyB,CAAC;IACvD,CAAC,iCAAkB,EAAE,gBAAgB,CAAC;IACtC,CAAC,kCAAmB,EAAE,iBAAiB,CAAC;IACxC,CAAC,uCAAwB,EAAE,sBAAsB,CAAC;IAClD,CAAC,oCAAqB,EAAE,kBAAkB,CAAC;IAC3C,CAAC,kCAAmB,EAAE,gBAAgB,CAAC;IACvC,CAAC,sCAAuB,EAAE,qBAAqB,CAAC;IAChD,CAAC,0CAA2B,EAAE,yBAAyB,CAAC;IACxD,CAAC,iDAAkC,EAAE,mCAAmC,CAAC;IACzE,CAAC,qCAAsB,EAAE,qBAAqB,CAAC;IAC/C,CAAC,0DAA2C,EAAE,6CAA6C,CAAC;IAC5F,CAAC,gCAAiB,EAAE,eAAe,CAAC;IACpC,CAAC,4CAA6B,EAAE,6BAA6B,CAAC;IAC9D,CAAC,6CAA8B,EAAE,8BAA8B,CAAC;IAChE,CAAC,2CAA4B,EAAE,2BAA2B,CAAC;IAC3D;QACI,8DAA+C;QAC/C,iDAAiD;KACpD;IACD,CAAC,iCAAkB,EAAE,eAAe,CAAC;IACrC,CAAC,4BAAa,EAAE,UAAU,CAAC;IAC3B,CAAC,sCAAuB,EAAE,sBAAsB,CAAC;IACjD,CAAC,2CAA4B,EAAE,6BAA6B,CAAC;IAC7D,CAAC,4CAA6B,EAAE,8BAA8B,CAAC;IAC/D,CAAC,2CAA4B,EAAE,6BAA6B,CAAC;CAChE,CAAC","sourcesContent":["import {\n BaseRuleConfig,\n WebpiecesRulesConfig,\n MaxMethodLinesConfig,\n MaxFileLinesConfig,\n RequireReturnTypeConfig,\n NoInlineTypeLiteralsConfig,\n NoAnyUnknownConfig,\n NoImplicitAnyConfig,\n PrismaValidateDtosConfig,\n PrismaConverterConfig,\n NoDestructureConfig,\n CatchErrorPatternConfig,\n NoUnmanagedExceptionsConfig,\n AngularNoDirectApiInResolverConfig,\n NoSymbolDiTokensConfig,\n NoClientCreationOutsideServerOrClientConfig,\n NoCustomCssConfig,\n NoStatePathsInTemplatesConfig,\n NoProcessExitOutsideMainConfig,\n NoFunctionOutsideClassConfig,\n InjectAnnotationNotNeededForConcreteClassConfig,\n FrameworkTagConfig,\n RoleTagConfig,\n EnsureWeAreSecureConfig,\n NoInlineImportInApiLibConfig,\n OneEnumSpellingInApiLibConfig,\n NoUtilityTypesInApiLibConfig,\n} from '@webpieces/rules-config';\n\n/** A rule config class usable as an inversify inject-by-type token. */\nexport type ConfigCtor = new () => BaseRuleConfig;\n\n/**\n * The 1:1 table of `[config class, webpieces.config.json rule key]`. The composition root iterates it\n * to bind each rule's config into the container (`bind(ConfigClass).toConstantValue(config[key] ??\n * new ConfigClass())`), so every `@provideSingleton` validator injects its config by type. Data only\n * — the binding loop lives inline in the bin (an inline loop, exempt from no-function-outside-class).\n */\nexport const CONFIG_BINDINGS: ReadonlyArray<readonly [ConfigCtor, keyof WebpiecesRulesConfig]> = [\n [MaxMethodLinesConfig, 'max-method-lines'],\n [MaxFileLinesConfig, 'max-file-lines'],\n [RequireReturnTypeConfig, 'require-return-type'],\n [NoInlineTypeLiteralsConfig, 'no-inline-type-literals'],\n [NoAnyUnknownConfig, 'no-any-unknown'],\n [NoImplicitAnyConfig, 'no-implicit-any'],\n [PrismaValidateDtosConfig, 'prisma-validate-dtos'],\n [PrismaConverterConfig, 'prisma-converter'],\n [NoDestructureConfig, 'no-destructure'],\n [CatchErrorPatternConfig, 'catch-error-pattern'],\n [NoUnmanagedExceptionsConfig, 'no-unmanaged-exceptions'],\n [AngularNoDirectApiInResolverConfig, 'angular-no-direct-api-in-resolver'],\n [NoSymbolDiTokensConfig, 'no-symbol-di-tokens'],\n [NoClientCreationOutsideServerOrClientConfig, 'no-client-creation-outside-server-or-client'],\n [NoCustomCssConfig, 'no-custom-css'],\n [NoStatePathsInTemplatesConfig, 'no-state-paths-in-templates'],\n [NoProcessExitOutsideMainConfig, 'no-process-exit-outside-main'],\n [NoFunctionOutsideClassConfig, 'no-function-outside-class'],\n [\n InjectAnnotationNotNeededForConcreteClassConfig,\n 'inject-annotation-not-needed-for-concrete-class',\n ],\n [FrameworkTagConfig, 'framework-tag'],\n [RoleTagConfig, 'role-tag'],\n [EnsureWeAreSecureConfig, 'ensure-we-are-secure'],\n [NoInlineImportInApiLibConfig, 'no-inline-import-in-api-lib'],\n [OneEnumSpellingInApiLibConfig, 'one-enum-spelling-in-api-lib'],\n [NoUtilityTypesInApiLibConfig, 'no-utility-types-in-api-lib'],\n];\n"]}
|
|
@@ -26,6 +26,7 @@ import { RoleTagValidator } from './validate-role-tag';
|
|
|
26
26
|
import { EnsureWeAreSecureValidator } from './validate-ensure-we-are-secure';
|
|
27
27
|
import { NoInlineImportInApiLibValidator } from './validate-no-inline-import-in-api-lib';
|
|
28
28
|
import { OneEnumSpellingInApiLibValidator } from './validate-one-enum-spelling-in-api-lib';
|
|
29
|
+
import { NoUtilityTypesInApiLibValidator } from './validate-no-utility-types-in-api-lib';
|
|
29
30
|
/**
|
|
30
31
|
* Owns running the code-rules suite. Every built-in validator is injected as a singleton (its config
|
|
31
32
|
* is bound in the container at bootstrap), so this class IS the code-rules DI DAG the design graph
|
|
@@ -61,7 +62,8 @@ export declare class CodeRulesEngine {
|
|
|
61
62
|
private readonly ensureWeAreSecure;
|
|
62
63
|
private readonly noInlineImportInApiLib;
|
|
63
64
|
private readonly oneEnumSpellingInApiLib;
|
|
64
|
-
|
|
65
|
+
private readonly noUtilityTypesInApiLib;
|
|
66
|
+
constructor(workspace: WorkspaceRoot, reporter: RuleReporter, matchRules: MatchRulesHolder, matchChecker: MatchRulesChecker, maxMethodLines: MaxMethodLinesValidator, maxFileLines: MaxFileLinesValidator, requireReturnType: RequireReturnTypeValidator, noInlineTypeLiterals: NoInlineTypeLiteralsValidator, noAnyUnknown: NoAnyUnknownValidator, noImplicitAny: NoImplicitAnyValidator, prismaValidateDtos: PrismaValidateDtosValidator, prismaConverter: PrismaConverterValidator, noDestructure: NoDestructureValidator, catchErrorPattern: CatchErrorPatternValidator, noUnmanagedExceptions: NoUnmanagedExceptionsValidator, noDirectApiResolver: NoDirectApiResolverValidator, noSymbolDiTokens: NoSymbolDiTokensValidator, noClientCreationOutsideServerOrClient: NoClientCreationOutsideServerOrClientValidator, noCustomCss: NoCustomCssValidator, noStatePathsInTemplates: NoStatePathsInTemplatesValidator, noProcessExitOutsideMain: NoProcessExitOutsideMainValidator, noFunctionOutsideClass: NoFunctionOutsideClassValidator, injectAnnotationNotNeeded: InjectAnnotationNotNeededForConcreteClassValidator, frameworkTag: FrameworkTagValidator, roleTag: RoleTagValidator, ensureWeAreSecure: EnsureWeAreSecureValidator, noInlineImportInApiLib: NoInlineImportInApiLibValidator, oneEnumSpellingInApiLib: OneEnumSpellingInApiLibValidator, noUtilityTypesInApiLib: NoUtilityTypesInApiLibValidator);
|
|
65
67
|
/** The injected built-in validators, in run order. */
|
|
66
68
|
private builtIns;
|
|
67
69
|
/**
|
package/src/code-rules-engine.js
CHANGED
|
@@ -31,6 +31,7 @@ const validate_role_tag_1 = require("./validate-role-tag");
|
|
|
31
31
|
const validate_ensure_we_are_secure_1 = require("./validate-ensure-we-are-secure");
|
|
32
32
|
const validate_no_inline_import_in_api_lib_1 = require("./validate-no-inline-import-in-api-lib");
|
|
33
33
|
const validate_one_enum_spelling_in_api_lib_1 = require("./validate-one-enum-spelling-in-api-lib");
|
|
34
|
+
const validate_no_utility_types_in_api_lib_1 = require("./validate-no-utility-types-in-api-lib");
|
|
34
35
|
/**
|
|
35
36
|
* Owns running the code-rules suite. Every built-in validator is injected as a singleton (its config
|
|
36
37
|
* is bound in the container at bootstrap), so this class IS the code-rules DI DAG the design graph
|
|
@@ -66,8 +67,9 @@ let CodeRulesEngine = class CodeRulesEngine {
|
|
|
66
67
|
ensureWeAreSecure;
|
|
67
68
|
noInlineImportInApiLib;
|
|
68
69
|
oneEnumSpellingInApiLib;
|
|
70
|
+
noUtilityTypesInApiLib;
|
|
69
71
|
// webpieces-disable max-lines-new-methods -- the built-in validator set is flat; each is one injected field
|
|
70
|
-
constructor(workspace, reporter, matchRules, matchChecker, maxMethodLines, maxFileLines, requireReturnType, noInlineTypeLiterals, noAnyUnknown, noImplicitAny, prismaValidateDtos, prismaConverter, noDestructure, catchErrorPattern, noUnmanagedExceptions, noDirectApiResolver, noSymbolDiTokens, noClientCreationOutsideServerOrClient, noCustomCss, noStatePathsInTemplates, noProcessExitOutsideMain, noFunctionOutsideClass, injectAnnotationNotNeeded, frameworkTag, roleTag, ensureWeAreSecure, noInlineImportInApiLib, oneEnumSpellingInApiLib) {
|
|
72
|
+
constructor(workspace, reporter, matchRules, matchChecker, maxMethodLines, maxFileLines, requireReturnType, noInlineTypeLiterals, noAnyUnknown, noImplicitAny, prismaValidateDtos, prismaConverter, noDestructure, catchErrorPattern, noUnmanagedExceptions, noDirectApiResolver, noSymbolDiTokens, noClientCreationOutsideServerOrClient, noCustomCss, noStatePathsInTemplates, noProcessExitOutsideMain, noFunctionOutsideClass, injectAnnotationNotNeeded, frameworkTag, roleTag, ensureWeAreSecure, noInlineImportInApiLib, oneEnumSpellingInApiLib, noUtilityTypesInApiLib) {
|
|
71
73
|
this.workspace = workspace;
|
|
72
74
|
this.reporter = reporter;
|
|
73
75
|
this.matchRules = matchRules;
|
|
@@ -96,6 +98,7 @@ let CodeRulesEngine = class CodeRulesEngine {
|
|
|
96
98
|
this.ensureWeAreSecure = ensureWeAreSecure;
|
|
97
99
|
this.noInlineImportInApiLib = noInlineImportInApiLib;
|
|
98
100
|
this.oneEnumSpellingInApiLib = oneEnumSpellingInApiLib;
|
|
101
|
+
this.noUtilityTypesInApiLib = noUtilityTypesInApiLib;
|
|
99
102
|
}
|
|
100
103
|
/** The injected built-in validators, in run order. */
|
|
101
104
|
builtIns() {
|
|
@@ -124,6 +127,7 @@ let CodeRulesEngine = class CodeRulesEngine {
|
|
|
124
127
|
this.ensureWeAreSecure,
|
|
125
128
|
this.noInlineImportInApiLib,
|
|
126
129
|
this.oneEnumSpellingInApiLib,
|
|
130
|
+
this.noUtilityTypesInApiLib,
|
|
127
131
|
];
|
|
128
132
|
}
|
|
129
133
|
/**
|
|
@@ -194,6 +198,7 @@ exports.CodeRulesEngine = CodeRulesEngine = tslib_1.__decorate([
|
|
|
194
198
|
validate_role_tag_1.RoleTagValidator,
|
|
195
199
|
validate_ensure_we_are_secure_1.EnsureWeAreSecureValidator,
|
|
196
200
|
validate_no_inline_import_in_api_lib_1.NoInlineImportInApiLibValidator,
|
|
197
|
-
validate_one_enum_spelling_in_api_lib_1.OneEnumSpellingInApiLibValidator
|
|
201
|
+
validate_one_enum_spelling_in_api_lib_1.OneEnumSpellingInApiLibValidator,
|
|
202
|
+
validate_no_utility_types_in_api_lib_1.NoUtilityTypesInApiLibValidator])
|
|
198
203
|
], CodeRulesEngine);
|
|
199
204
|
//# sourceMappingURL=code-rules-engine.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"code-rules-engine.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/code-rules-engine.ts"],"names":[],"mappings":";;;;AACA,yCAA2D;AAE3D,qDAA0E;AAC1E,mDAA+C;AAC/C,6DAAuE;AACvE,iEAA2D;AAC3D,2EAAsE;AACtE,uEAAkE;AAClE,mEAAqE;AACrE,yEAA2E;AAC3E,uEAAkE;AAClE,yEAAoE;AACpE,mDAA8D;AAC9D,6EAAwE;AACxE,uEAAmE;AACnE,iFAA4E;AAC5E,yFAAoF;AACpF,uFAAiF;AACjF,iFAA2E;AAC3E,iIAAwH;AACxH,qEAAgE;AAChE,iGAA0F;AAC1F,mGAA4F;AAC5F,6FAAuF;AACvF,yIAAgI;AAChI,qEAAiE;AACjE,2DAAuD;AACvD,mFAA6E;AAC7E,iGAAyF;AACzF,mGAA2F;AAE3F;;;;;GAKG;AAEI,IAAM,eAAe,GAArB,MAAM,eAAe;IAGH;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA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,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIL,kCAAa;QACd,4BAAY;QACV,qCAAgB;QACd,wCAAiB;QACf,mDAAuB;QACzB,+CAAqB;QAChB,kDAA0B;QACvB,wDAA6B;QACrC,+CAAqB;QACpB,iDAAsB;QACjB,2CAA2B;QAC9B,qDAAwB;QAC1B,gDAAsB;QAClB,yDAA0B;QACtB,iEAA8B;QAChC,8DAA4B;QAC/B,wDAAyB;QACJ,qGAA8C;QACxE,6CAAoB;QACR,uEAAgC;QAC/B,yEAAiC;QACnC,oEAA+B;QAC5B,6GAAkD;QAC/D,8CAAqB;QAC1B,oCAAgB;QACN,0DAA0B;QACrB,sEAA+B;QAC9B,wEAAgC;GA9BrE,eAAe,CAwG3B","sourcesContent":["import { BaseRuleConfig } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { CodeValidator, ExecutorResult, RuleRun } from './code-validator';\nimport { RuleReporter } from './rule-reporter';\nimport { WorkspaceRoot, MatchRulesHolder } from './code-rules-context';\nimport { MatchRulesChecker } from './validate-match-rules';\nimport { MaxMethodLinesValidator } from './validate-modified-methods';\nimport { MaxFileLinesValidator } from './validate-modified-files';\nimport { RequireReturnTypeValidator } from './validate-return-types';\nimport { NoInlineTypeLiteralsValidator } from './validate-no-inline-types';\nimport { NoAnyUnknownValidator } from './validate-no-any-unknown';\nimport { NoImplicitAnyValidator } from './validate-no-implicit-any';\nimport { PrismaValidateDtosValidator } from './validate-dtos';\nimport { PrismaConverterValidator } from './validate-prisma-converters';\nimport { NoDestructureValidator } from './validate-no-destructure';\nimport { CatchErrorPatternValidator } from './validate-catch-error-pattern';\nimport { NoUnmanagedExceptionsValidator } from './validate-no-unmanaged-exceptions';\nimport { NoDirectApiResolverValidator } from './validate-no-direct-api-resolver';\nimport { NoSymbolDiTokensValidator } from './validate-no-symbol-di-tokens';\nimport { NoClientCreationOutsideServerOrClientValidator } from './validate-no-client-creation-outside-server-or-client';\nimport { NoCustomCssValidator } from './validate-no-custom-css';\nimport { NoStatePathsInTemplatesValidator } from './validate-no-state-paths-in-templates';\nimport { NoProcessExitOutsideMainValidator } from './validate-no-process-exit-outside-main';\nimport { NoFunctionOutsideClassValidator } from './validate-no-function-outside-class';\nimport { InjectAnnotationNotNeededForConcreteClassValidator } from './validate-inject-annotation-not-needed-for-concrete-class';\nimport { FrameworkTagValidator } from './validate-framework-tag';\nimport { RoleTagValidator } from './validate-role-tag';\nimport { EnsureWeAreSecureValidator } from './validate-ensure-we-are-secure';\nimport { NoInlineImportInApiLibValidator } from './validate-no-inline-import-in-api-lib';\nimport { OneEnumSpellingInApiLibValidator } from './validate-one-enum-spelling-in-api-lib';\n\n/**\n * Owns running the code-rules suite. Every built-in validator is injected as a singleton (its config\n * is bound in the container at bootstrap), so this class IS the code-rules DI DAG the design graph\n * draws. The per-entry match-rules validators are the one exception — they are config-per-instance,\n * so they are built from the injected {@link MatchRulesHolder}.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class CodeRulesEngine {\n // webpieces-disable max-lines-new-methods -- the built-in validator set is flat; each is one injected field\n constructor(\n private readonly workspace: WorkspaceRoot,\n private readonly reporter: RuleReporter,\n private readonly matchRules: MatchRulesHolder,\n private readonly matchChecker: MatchRulesChecker,\n private readonly maxMethodLines: MaxMethodLinesValidator,\n private readonly maxFileLines: MaxFileLinesValidator,\n private readonly requireReturnType: RequireReturnTypeValidator,\n private readonly noInlineTypeLiterals: NoInlineTypeLiteralsValidator,\n private readonly noAnyUnknown: NoAnyUnknownValidator,\n private readonly noImplicitAny: NoImplicitAnyValidator,\n private readonly prismaValidateDtos: PrismaValidateDtosValidator,\n private readonly prismaConverter: PrismaConverterValidator,\n private readonly noDestructure: NoDestructureValidator,\n private readonly catchErrorPattern: CatchErrorPatternValidator,\n private readonly noUnmanagedExceptions: NoUnmanagedExceptionsValidator,\n private readonly noDirectApiResolver: NoDirectApiResolverValidator,\n private readonly noSymbolDiTokens: NoSymbolDiTokensValidator,\n private readonly noClientCreationOutsideServerOrClient: NoClientCreationOutsideServerOrClientValidator,\n private readonly noCustomCss: NoCustomCssValidator,\n private readonly noStatePathsInTemplates: NoStatePathsInTemplatesValidator,\n private readonly noProcessExitOutsideMain: NoProcessExitOutsideMainValidator,\n private readonly noFunctionOutsideClass: NoFunctionOutsideClassValidator,\n private readonly injectAnnotationNotNeeded: InjectAnnotationNotNeededForConcreteClassValidator,\n private readonly frameworkTag: FrameworkTagValidator,\n private readonly roleTag: RoleTagValidator,\n private readonly ensureWeAreSecure: EnsureWeAreSecureValidator,\n private readonly noInlineImportInApiLib: NoInlineImportInApiLibValidator,\n private readonly oneEnumSpellingInApiLib: OneEnumSpellingInApiLibValidator,\n ) {}\n\n /** The injected built-in validators, in run order. */\n private builtIns(): CodeValidator<BaseRuleConfig>[] {\n return [\n this.maxMethodLines,\n this.maxFileLines,\n this.requireReturnType,\n this.noInlineTypeLiterals,\n this.noAnyUnknown,\n this.noImplicitAny,\n this.prismaValidateDtos,\n this.prismaConverter,\n this.noDestructure,\n this.catchErrorPattern,\n this.noUnmanagedExceptions,\n this.noDirectApiResolver,\n this.noSymbolDiTokens,\n this.noClientCreationOutsideServerOrClient,\n this.noCustomCss,\n this.noStatePathsInTemplates,\n this.noProcessExitOutsideMain,\n this.noFunctionOutsideClass,\n this.injectAnnotationNotNeeded,\n this.frameworkTag,\n this.roleTag,\n this.ensureWeAreSecure,\n this.noInlineImportInApiLib,\n this.oneEnumSpellingInApiLib,\n ];\n }\n\n /**\n * Every ACTIVE run: an injected built-in validator whose `shouldRun()` is true, or an injected\n * match-rule check per configured entry that is active. Built as {@link RuleRun} value objects\n * (name + thunk) so NO DAG member is `new`-ed — the validators and the checker are injected.\n */\n private activeRuns(root: string): RuleRun[] {\n const runs: RuleRun[] = [];\n for (const v of this.builtIns()) {\n if (v.shouldRun()) runs.push(new RuleRun(v.name, () => v.run(root)));\n }\n for (const mr of this.matchRules.rules) {\n if (this.matchChecker.shouldRun(mr))\n runs.push(new RuleRun(mr.name, () => this.matchChecker.runForConfig(mr, root)));\n }\n return runs;\n }\n\n /**\n * Run all configured code validators against the workspace. A validator runs only when\n * `shouldRun()` is true (mode not OFF and no branch/epoch escape hatch). Per-run isolation lives\n * in {@link RuleReporter} so one validator can never abort the rest.\n */\n async run(): Promise<ExecutorResult> {\n const runs = this.activeRuns(this.workspace.path);\n if (runs.length === 0) {\n console.log('\\n⏭️ Skipping all code validations (all modes: OFF)\\n');\n return { success: true };\n }\n\n console.log('\\n📏 Running Code Validations\\n');\n console.log(` Active rules: ${runs.map((r: RuleRun) => r.name).join(', ')}`);\n console.log('');\n\n const result = await this.reporter.runValidators(runs);\n console.log(\n result.success\n ? '\\n✅ All code validations passed\\n'\n : '\\n❌ Some code validations failed\\n',\n );\n return result;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"code-rules-engine.js","sourceRoot":"","sources":["../../../../../packages/tooling/code-rules/src/code-rules-engine.ts"],"names":[],"mappings":";;;;AACA,yCAA2D;AAE3D,qDAA0E;AAC1E,mDAA+C;AAC/C,6DAAuE;AACvE,iEAA2D;AAC3D,2EAAsE;AACtE,uEAAkE;AAClE,mEAAqE;AACrE,yEAA2E;AAC3E,uEAAkE;AAClE,yEAAoE;AACpE,mDAA8D;AAC9D,6EAAwE;AACxE,uEAAmE;AACnE,iFAA4E;AAC5E,yFAAoF;AACpF,uFAAiF;AACjF,iFAA2E;AAC3E,iIAAwH;AACxH,qEAAgE;AAChE,iGAA0F;AAC1F,mGAA4F;AAC5F,6FAAuF;AACvF,yIAAgI;AAChI,qEAAiE;AACjE,2DAAuD;AACvD,mFAA6E;AAC7E,iGAAyF;AACzF,mGAA2F;AAC3F,iGAAyF;AAEzF;;;;;GAKG;AAEI,IAAM,eAAe,GAArB,MAAM,eAAe;IAGH;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA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AA1GY,0CAAe;0BAAf,eAAe;IAD3B,IAAA,sBAAU,EAAC,8BAAkB,CAAC,SAAS,CAAC;6CAIL,kCAAa;QACd,4BAAY;QACV,qCAAgB;QACd,wCAAiB;QACf,mDAAuB;QACzB,+CAAqB;QAChB,kDAA0B;QACvB,wDAA6B;QACrC,+CAAqB;QACpB,iDAAsB;QACjB,2CAA2B;QAC9B,qDAAwB;QAC1B,gDAAsB;QAClB,yDAA0B;QACtB,iEAA8B;QAChC,8DAA4B;QAC/B,wDAAyB;QACJ,qGAA8C;QACxE,6CAAoB;QACR,uEAAgC;QAC/B,yEAAiC;QACnC,oEAA+B;QAC5B,6GAAkD;QAC/D,8CAAqB;QAC1B,oCAAgB;QACN,0DAA0B;QACrB,sEAA+B;QAC9B,wEAAgC;QACjC,sEAA+B;GA/BnE,eAAe,CA0G3B","sourcesContent":["import { BaseRuleConfig } from '@webpieces/rules-config';\nimport { injectable, bindingScopeValues } from 'inversify';\n\nimport { CodeValidator, ExecutorResult, RuleRun } from './code-validator';\nimport { RuleReporter } from './rule-reporter';\nimport { WorkspaceRoot, MatchRulesHolder } from './code-rules-context';\nimport { MatchRulesChecker } from './validate-match-rules';\nimport { MaxMethodLinesValidator } from './validate-modified-methods';\nimport { MaxFileLinesValidator } from './validate-modified-files';\nimport { RequireReturnTypeValidator } from './validate-return-types';\nimport { NoInlineTypeLiteralsValidator } from './validate-no-inline-types';\nimport { NoAnyUnknownValidator } from './validate-no-any-unknown';\nimport { NoImplicitAnyValidator } from './validate-no-implicit-any';\nimport { PrismaValidateDtosValidator } from './validate-dtos';\nimport { PrismaConverterValidator } from './validate-prisma-converters';\nimport { NoDestructureValidator } from './validate-no-destructure';\nimport { CatchErrorPatternValidator } from './validate-catch-error-pattern';\nimport { NoUnmanagedExceptionsValidator } from './validate-no-unmanaged-exceptions';\nimport { NoDirectApiResolverValidator } from './validate-no-direct-api-resolver';\nimport { NoSymbolDiTokensValidator } from './validate-no-symbol-di-tokens';\nimport { NoClientCreationOutsideServerOrClientValidator } from './validate-no-client-creation-outside-server-or-client';\nimport { NoCustomCssValidator } from './validate-no-custom-css';\nimport { NoStatePathsInTemplatesValidator } from './validate-no-state-paths-in-templates';\nimport { NoProcessExitOutsideMainValidator } from './validate-no-process-exit-outside-main';\nimport { NoFunctionOutsideClassValidator } from './validate-no-function-outside-class';\nimport { InjectAnnotationNotNeededForConcreteClassValidator } from './validate-inject-annotation-not-needed-for-concrete-class';\nimport { FrameworkTagValidator } from './validate-framework-tag';\nimport { RoleTagValidator } from './validate-role-tag';\nimport { EnsureWeAreSecureValidator } from './validate-ensure-we-are-secure';\nimport { NoInlineImportInApiLibValidator } from './validate-no-inline-import-in-api-lib';\nimport { OneEnumSpellingInApiLibValidator } from './validate-one-enum-spelling-in-api-lib';\nimport { NoUtilityTypesInApiLibValidator } from './validate-no-utility-types-in-api-lib';\n\n/**\n * Owns running the code-rules suite. Every built-in validator is injected as a singleton (its config\n * is bound in the container at bootstrap), so this class IS the code-rules DI DAG the design graph\n * draws. The per-entry match-rules validators are the one exception — they are config-per-instance,\n * so they are built from the injected {@link MatchRulesHolder}.\n */\n@injectable(bindingScopeValues.Singleton)\nexport class CodeRulesEngine {\n // webpieces-disable max-lines-new-methods -- the built-in validator set is flat; each is one injected field\n constructor(\n private readonly workspace: WorkspaceRoot,\n private readonly reporter: RuleReporter,\n private readonly matchRules: MatchRulesHolder,\n private readonly matchChecker: MatchRulesChecker,\n private readonly maxMethodLines: MaxMethodLinesValidator,\n private readonly maxFileLines: MaxFileLinesValidator,\n private readonly requireReturnType: RequireReturnTypeValidator,\n private readonly noInlineTypeLiterals: NoInlineTypeLiteralsValidator,\n private readonly noAnyUnknown: NoAnyUnknownValidator,\n private readonly noImplicitAny: NoImplicitAnyValidator,\n private readonly prismaValidateDtos: PrismaValidateDtosValidator,\n private readonly prismaConverter: PrismaConverterValidator,\n private readonly noDestructure: NoDestructureValidator,\n private readonly catchErrorPattern: CatchErrorPatternValidator,\n private readonly noUnmanagedExceptions: NoUnmanagedExceptionsValidator,\n private readonly noDirectApiResolver: NoDirectApiResolverValidator,\n private readonly noSymbolDiTokens: NoSymbolDiTokensValidator,\n private readonly noClientCreationOutsideServerOrClient: NoClientCreationOutsideServerOrClientValidator,\n private readonly noCustomCss: NoCustomCssValidator,\n private readonly noStatePathsInTemplates: NoStatePathsInTemplatesValidator,\n private readonly noProcessExitOutsideMain: NoProcessExitOutsideMainValidator,\n private readonly noFunctionOutsideClass: NoFunctionOutsideClassValidator,\n private readonly injectAnnotationNotNeeded: InjectAnnotationNotNeededForConcreteClassValidator,\n private readonly frameworkTag: FrameworkTagValidator,\n private readonly roleTag: RoleTagValidator,\n private readonly ensureWeAreSecure: EnsureWeAreSecureValidator,\n private readonly noInlineImportInApiLib: NoInlineImportInApiLibValidator,\n private readonly oneEnumSpellingInApiLib: OneEnumSpellingInApiLibValidator,\n private readonly noUtilityTypesInApiLib: NoUtilityTypesInApiLibValidator,\n ) {}\n\n /** The injected built-in validators, in run order. */\n private builtIns(): CodeValidator<BaseRuleConfig>[] {\n return [\n this.maxMethodLines,\n this.maxFileLines,\n this.requireReturnType,\n this.noInlineTypeLiterals,\n this.noAnyUnknown,\n this.noImplicitAny,\n this.prismaValidateDtos,\n this.prismaConverter,\n this.noDestructure,\n this.catchErrorPattern,\n this.noUnmanagedExceptions,\n this.noDirectApiResolver,\n this.noSymbolDiTokens,\n this.noClientCreationOutsideServerOrClient,\n this.noCustomCss,\n this.noStatePathsInTemplates,\n this.noProcessExitOutsideMain,\n this.noFunctionOutsideClass,\n this.injectAnnotationNotNeeded,\n this.frameworkTag,\n this.roleTag,\n this.ensureWeAreSecure,\n this.noInlineImportInApiLib,\n this.oneEnumSpellingInApiLib,\n this.noUtilityTypesInApiLib,\n ];\n }\n\n /**\n * Every ACTIVE run: an injected built-in validator whose `shouldRun()` is true, or an injected\n * match-rule check per configured entry that is active. Built as {@link RuleRun} value objects\n * (name + thunk) so NO DAG member is `new`-ed — the validators and the checker are injected.\n */\n private activeRuns(root: string): RuleRun[] {\n const runs: RuleRun[] = [];\n for (const v of this.builtIns()) {\n if (v.shouldRun()) runs.push(new RuleRun(v.name, () => v.run(root)));\n }\n for (const mr of this.matchRules.rules) {\n if (this.matchChecker.shouldRun(mr))\n runs.push(new RuleRun(mr.name, () => this.matchChecker.runForConfig(mr, root)));\n }\n return runs;\n }\n\n /**\n * Run all configured code validators against the workspace. A validator runs only when\n * `shouldRun()` is true (mode not OFF and no branch/epoch escape hatch). Per-run isolation lives\n * in {@link RuleReporter} so one validator can never abort the rest.\n */\n async run(): Promise<ExecutorResult> {\n const runs = this.activeRuns(this.workspace.path);\n if (runs.length === 0) {\n console.log('\\n⏭️ Skipping all code validations (all modes: OFF)\\n');\n return { success: true };\n }\n\n console.log('\\n📏 Running Code Validations\\n');\n console.log(` Active rules: ${runs.map((r: RuleRun) => r.name).join(', ')}`);\n console.log('');\n\n const result = await this.reporter.runValidators(runs);\n console.log(\n result.success\n ? '\\n✅ All code validations passed\\n'\n : '\\n❌ Some code validations failed\\n',\n );\n return result;\n }\n}\n"]}
|
package/src/index.d.ts
CHANGED
|
@@ -23,6 +23,7 @@ export { EnsureWeAreSecureValidator, SecurityContractViolation, auditSecurityCon
|
|
|
23
23
|
export { ApiLibFile, ApiLibSite } from './api-lib-source-rule';
|
|
24
24
|
export { NoInlineImportInApiLibValidator, InlineImportScanner } from './validate-no-inline-import-in-api-lib';
|
|
25
25
|
export { OneEnumSpellingInApiLibValidator, EnumSpellingScanner } from './validate-one-enum-spelling-in-api-lib';
|
|
26
|
+
export { NoUtilityTypesInApiLibValidator, UtilityTypeScanner } from './validate-no-utility-types-in-api-lib';
|
|
26
27
|
export { ApiLibEnumIndex } from './api-lib-enum-index';
|
|
27
28
|
export { EnumText } from './api-lib-enum-text';
|
|
28
29
|
export { PrismaValidateDtosValidator } from './validate-dtos';
|
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.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.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; } });
|
|
@@ -62,6 +62,9 @@ Object.defineProperty(exports, "InlineImportScanner", { enumerable: true, get: f
|
|
|
62
62
|
var validate_one_enum_spelling_in_api_lib_1 = require("./validate-one-enum-spelling-in-api-lib");
|
|
63
63
|
Object.defineProperty(exports, "OneEnumSpellingInApiLibValidator", { enumerable: true, get: function () { return validate_one_enum_spelling_in_api_lib_1.OneEnumSpellingInApiLibValidator; } });
|
|
64
64
|
Object.defineProperty(exports, "EnumSpellingScanner", { enumerable: true, get: function () { return validate_one_enum_spelling_in_api_lib_1.EnumSpellingScanner; } });
|
|
65
|
+
var validate_no_utility_types_in_api_lib_1 = require("./validate-no-utility-types-in-api-lib");
|
|
66
|
+
Object.defineProperty(exports, "NoUtilityTypesInApiLibValidator", { enumerable: true, get: function () { return validate_no_utility_types_in_api_lib_1.NoUtilityTypesInApiLibValidator; } });
|
|
67
|
+
Object.defineProperty(exports, "UtilityTypeScanner", { enumerable: true, get: function () { return validate_no_utility_types_in_api_lib_1.UtilityTypeScanner; } });
|
|
65
68
|
var api_lib_enum_index_1 = require("./api-lib-enum-index");
|
|
66
69
|
Object.defineProperty(exports, "ApiLibEnumIndex", { enumerable: true, get: function () { return api_lib_enum_index_1.ApiLibEnumIndex; } });
|
|
67
70
|
var api_lib_enum_text_1 = require("./api-lib-enum-text");
|
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,+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;AAAxE,+IAAA,4BAA4B,OAAA;AACrC,+EAA2E;AAAlE,yIAAA,yBAAyB,OAAA;AAClC,+HAAwH;AAA/G,sLAAA,8CAA8C,OAAA;AACvD,+FAIgD;AAH5C,wJAAA,gCAAgC,OAAA;AAChC,oIAAA,YAAY,OAAA;AACZ,0IAAA,kBAAkB,OAAA;AAEtB,iEAA8D;AAArD,4HAAA,mBAAmB,OAAA;AAC5B,iGAA4F;AAAnF,0JAAA,iCAAiC,OAAA;AAC1C,2FAAuF;AAA9E,qJAAA,+BAA+B,OAAA;AACxC,uIAGoE;AAFhE,8LAAA,kDAAkD,OAAA;AAClD,uKAAA,2BAA2B,OAAA;AAE/B,mEAAiE;AAAxD,+HAAA,qBAAqB,OAAA;AAC9B,yDAAuD;AAA9C,qHAAA,gBAAgB,OAAA;AACzB,iFAKyC;AAJrC,2IAAA,0BAA0B,OAAA;AAC1B,0IAAA,yBAAyB,OAAA;AACzB,uIAAA,sBAAsB,OAAA;AACtB,gJAAA,+BAA+B,OAAA;AAEnC,6DAA+D;AAAtD,iHAAA,UAAU,OAAA;AAAE,iHAAA,UAAU,OAAA;AAC/B,+FAA8G;AAArG,uJAAA,+BAA+B,OAAA;AAAE,2IAAA,mBAAmB,OAAA;AAC7D,iGAAgH;AAAvG,yJAAA,gCAAgC,OAAA;AAAE,4IAAA,mBAAmB,OAAA;AAC9D,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 { 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,0IAA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AAO,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"]}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `no-utility-types-in-api-lib` (#1026) — an API contract writes its fields out.
|
|
3
|
+
*
|
|
4
|
+
* In every `.ts` file under the configured `paths` (e.g. `libraries/apis/**`) this refuses the
|
|
5
|
+
* utility types that turn a DTO's field list, or a set of keys, into a type-level computation:
|
|
6
|
+
*
|
|
7
|
+
* export interface LessonPassageDto extends Omit<LessonPassageReservationDto, OptionalField> { … }
|
|
8
|
+
* draft?: Partial<LessonDto>;
|
|
9
|
+
* export type Summary = Pick<LessonDto, 'id' | 'title'>;
|
|
10
|
+
* export type Kind = Exclude<AllKinds, 'legacy'>;
|
|
11
|
+
*
|
|
12
|
+
* — `Omit`, `Pick`, `Partial`, `Required`, `Exclude` and `Extract`, in an `extends` / `implements`
|
|
13
|
+
* clause, a field, a type alias or a generic argument.
|
|
14
|
+
*
|
|
15
|
+
* Why: an api library is the contract every client, server and document generator reads. A utility
|
|
16
|
+
* type makes a reader open a second file and subtract (or add) names in their head to learn which
|
|
17
|
+
* fields a DTO carries; it cannot become a DTO class (`class X extends Omit<…>` does not compile — a
|
|
18
|
+
* utility type has no runtime value); and a key union that only exists to feed `Omit` collides with
|
|
19
|
+
* `one-enum-spelling-in-api-lib`, whose enum cure removes nothing from an `Omit`. The whole family is
|
|
20
|
+
* refused, not `Omit` alone, because banning one just moves the computation into its sibling
|
|
21
|
+
* (`Pick<T, Exclude<keyof T, K>>` is `Omit<T, K>`). `Record`, `Readonly` and `Array` stay allowed:
|
|
22
|
+
* they do not hide which fields a DTO carries.
|
|
23
|
+
*
|
|
24
|
+
* The cure is to write the fields out — a shared base interface both DTOs extend, each adding its own
|
|
25
|
+
* required or optional fields, or a flat interface / class listing every field. The wire JSON is
|
|
26
|
+
* unchanged either way.
|
|
27
|
+
*/
|
|
28
|
+
import { DiffScope, NoUtilityTypesInApiLibConfig } from '@webpieces/rules-config';
|
|
29
|
+
import { ApiLibFile, ApiLibSite, ApiLibSourceRule } from './api-lib-source-rule';
|
|
30
|
+
import { ProjectRoleResolver } from './project-role-resolver';
|
|
31
|
+
/** Finds every refused utility-type reference in one parsed file. */
|
|
32
|
+
export declare class UtilityTypeScanner {
|
|
33
|
+
/** The refused utility types, each with what it computes. */
|
|
34
|
+
static readonly REFUSED: ReadonlyMap<string, string>;
|
|
35
|
+
scan(file: ApiLibFile): ApiLibSite[];
|
|
36
|
+
/** The utility's name when `node` is a refused reference: `Omit<…>` as a type, or in a heritage clause. */
|
|
37
|
+
private refusedNameOf;
|
|
38
|
+
/**
|
|
39
|
+
* Names the file declares or imports itself — a local `type Omit = …` or an imported `Pick` class
|
|
40
|
+
* is not the global utility type, so it is not refused.
|
|
41
|
+
*/
|
|
42
|
+
private locallyDeclaredNames;
|
|
43
|
+
private siteFor;
|
|
44
|
+
private typeArgumentsOf;
|
|
45
|
+
private cureFor;
|
|
46
|
+
/** `(on interface X)` for a heritage clause, `(in X.field)` for a member, `(in type X)` for an alias. */
|
|
47
|
+
private owner;
|
|
48
|
+
private declaredName;
|
|
49
|
+
}
|
|
50
|
+
export declare class NoUtilityTypesInApiLibValidator extends ApiLibSourceRule<NoUtilityTypesInApiLibConfig> {
|
|
51
|
+
private readonly scanner;
|
|
52
|
+
constructor(config: NoUtilityTypesInApiLibConfig, roleResolver: ProjectRoleResolver, diffScope: DiffScope);
|
|
53
|
+
protected sitesIn(file: ApiLibFile): ApiLibSite[];
|
|
54
|
+
/** Scoped by the configured `paths` globs, not the role tag — an empty list judges nothing. */
|
|
55
|
+
protected isApiLibrarySource(_workspaceRoot: string, relFile: string): boolean;
|
|
56
|
+
protected scopeLabel(): string;
|
|
57
|
+
protected why(): string;
|
|
58
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* `no-utility-types-in-api-lib` (#1026) — an API contract writes its fields out.
|
|
4
|
+
*
|
|
5
|
+
* In every `.ts` file under the configured `paths` (e.g. `libraries/apis/**`) this refuses the
|
|
6
|
+
* utility types that turn a DTO's field list, or a set of keys, into a type-level computation:
|
|
7
|
+
*
|
|
8
|
+
* export interface LessonPassageDto extends Omit<LessonPassageReservationDto, OptionalField> { … }
|
|
9
|
+
* draft?: Partial<LessonDto>;
|
|
10
|
+
* export type Summary = Pick<LessonDto, 'id' | 'title'>;
|
|
11
|
+
* export type Kind = Exclude<AllKinds, 'legacy'>;
|
|
12
|
+
*
|
|
13
|
+
* — `Omit`, `Pick`, `Partial`, `Required`, `Exclude` and `Extract`, in an `extends` / `implements`
|
|
14
|
+
* clause, a field, a type alias or a generic argument.
|
|
15
|
+
*
|
|
16
|
+
* Why: an api library is the contract every client, server and document generator reads. A utility
|
|
17
|
+
* type makes a reader open a second file and subtract (or add) names in their head to learn which
|
|
18
|
+
* fields a DTO carries; it cannot become a DTO class (`class X extends Omit<…>` does not compile — a
|
|
19
|
+
* utility type has no runtime value); and a key union that only exists to feed `Omit` collides with
|
|
20
|
+
* `one-enum-spelling-in-api-lib`, whose enum cure removes nothing from an `Omit`. The whole family is
|
|
21
|
+
* refused, not `Omit` alone, because banning one just moves the computation into its sibling
|
|
22
|
+
* (`Pick<T, Exclude<keyof T, K>>` is `Omit<T, K>`). `Record`, `Readonly` and `Array` stay allowed:
|
|
23
|
+
* they do not hide which fields a DTO carries.
|
|
24
|
+
*
|
|
25
|
+
* The cure is to write the fields out — a shared base interface both DTOs extend, each adding its own
|
|
26
|
+
* required or optional fields, or a flat interface / class listing every field. The wire JSON is
|
|
27
|
+
* unchanged either way.
|
|
28
|
+
*/
|
|
29
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
30
|
+
exports.NoUtilityTypesInApiLibValidator = exports.UtilityTypeScanner = void 0;
|
|
31
|
+
const tslib_1 = require("tslib");
|
|
32
|
+
const rules_config_1 = require("@webpieces/rules-config");
|
|
33
|
+
const inversify_1 = require("inversify");
|
|
34
|
+
const ts = tslib_1.__importStar(require("typescript"));
|
|
35
|
+
const api_lib_source_rule_1 = require("./api-lib-source-rule");
|
|
36
|
+
const project_role_resolver_1 = require("./project-role-resolver");
|
|
37
|
+
/** Finds every refused utility-type reference in one parsed file. */
|
|
38
|
+
class UtilityTypeScanner {
|
|
39
|
+
/** The refused utility types, each with what it computes. */
|
|
40
|
+
static REFUSED = new Map([
|
|
41
|
+
['Omit', 'a DTO\'s field list computed by SUBTRACTING keys from another type'],
|
|
42
|
+
['Pick', 'a DTO\'s field list computed by SELECTING keys of another type'],
|
|
43
|
+
['Partial', 'a DTO\'s field list computed by making every field of another type optional'],
|
|
44
|
+
['Required', 'a DTO\'s field list computed by making every field of another type required'],
|
|
45
|
+
['Exclude', 'a set of keys or values computed by SUBTRACTING from another union'],
|
|
46
|
+
['Extract', 'a set of keys or values computed by SELECTING from another union'],
|
|
47
|
+
]);
|
|
48
|
+
scan(file) {
|
|
49
|
+
const shadowed = this.locallyDeclaredNames(file.source);
|
|
50
|
+
const sites = [];
|
|
51
|
+
const visit = (node) => {
|
|
52
|
+
const name = this.refusedNameOf(node, shadowed);
|
|
53
|
+
if (name !== undefined)
|
|
54
|
+
sites.push(this.siteFor(file, node, name));
|
|
55
|
+
ts.forEachChild(node, visit);
|
|
56
|
+
};
|
|
57
|
+
visit(file.source);
|
|
58
|
+
return sites;
|
|
59
|
+
}
|
|
60
|
+
/** The utility's name when `node` is a refused reference: `Omit<…>` as a type, or in a heritage clause. */
|
|
61
|
+
refusedNameOf(node, shadowed) {
|
|
62
|
+
let name;
|
|
63
|
+
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName))
|
|
64
|
+
name = node.typeName.text;
|
|
65
|
+
else if (ts.isExpressionWithTypeArguments(node) && ts.isIdentifier(node.expression))
|
|
66
|
+
name = node.expression.text;
|
|
67
|
+
if (name === undefined || !UtilityTypeScanner.REFUSED.has(name) || shadowed.has(name))
|
|
68
|
+
return undefined;
|
|
69
|
+
return name;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Names the file declares or imports itself — a local `type Omit = …` or an imported `Pick` class
|
|
73
|
+
* is not the global utility type, so it is not refused.
|
|
74
|
+
*/
|
|
75
|
+
locallyDeclaredNames(source) {
|
|
76
|
+
const names = new Set();
|
|
77
|
+
for (const statement of source.statements) {
|
|
78
|
+
if ((ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement) ||
|
|
79
|
+
ts.isClassDeclaration(statement) || ts.isEnumDeclaration(statement)) && statement.name !== undefined) {
|
|
80
|
+
names.add(statement.name.text);
|
|
81
|
+
}
|
|
82
|
+
const bindings = ts.isImportDeclaration(statement) ? statement.importClause?.namedBindings : undefined;
|
|
83
|
+
if (bindings !== undefined && ts.isNamedImports(bindings)) {
|
|
84
|
+
for (const element of bindings.elements)
|
|
85
|
+
names.add(element.name.text);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return names;
|
|
89
|
+
}
|
|
90
|
+
siteFor(file, node, name) {
|
|
91
|
+
const args = this.typeArgumentsOf(node).map((arg) => arg.getText(file.source).replace(/\s+/g, ' '));
|
|
92
|
+
const what = `\`${name}<…>\` — ${UtilityTypeScanner.REFUSED.get(name)}; an API writes its fields out`;
|
|
93
|
+
return file.site(node, what, `${this.cureFor(name, args[0] ?? 'T', args[1] ?? 'K')} ${this.owner(file, node)}`.trim());
|
|
94
|
+
}
|
|
95
|
+
typeArgumentsOf(node) {
|
|
96
|
+
if (ts.isTypeReferenceNode(node) || ts.isExpressionWithTypeArguments(node))
|
|
97
|
+
return node.typeArguments ?? [];
|
|
98
|
+
return [];
|
|
99
|
+
}
|
|
100
|
+
cureFor(name, target, keys) {
|
|
101
|
+
const wire = 'The wire JSON is unchanged.';
|
|
102
|
+
switch (name) {
|
|
103
|
+
case 'Omit':
|
|
104
|
+
return `write the fields out instead of \`Omit<${target}, ${keys}>\`: move the fields both types share into a ` +
|
|
105
|
+
`base interface that ${target} and this type both extend, each adding its own required or optional ` +
|
|
106
|
+
`fields — or list every field of ${target} except ${keys} in a flat interface or class. ${wire}`;
|
|
107
|
+
case 'Pick':
|
|
108
|
+
return `write the fields out instead of \`Pick<${target}, ${keys}>\`: put the picked fields (${keys}) in a ` +
|
|
109
|
+
`base interface that ${target} extends and use it here — or list them in a flat interface or class. ${wire}`;
|
|
110
|
+
case 'Partial':
|
|
111
|
+
return `write the fields out instead of \`Partial<${target}>\`: declare an interface or class listing every ` +
|
|
112
|
+
`field of ${target} as optional (\`field?: X\`). ${wire}`;
|
|
113
|
+
case 'Required':
|
|
114
|
+
return `write the fields out instead of \`Required<${target}>\`: declare an interface or class listing every ` +
|
|
115
|
+
`field of ${target} as required. ${wire}`;
|
|
116
|
+
default:
|
|
117
|
+
return `write the set out instead of \`${name}<${target}, ${keys}>\`: for keys of a DTO, write that DTO's ` +
|
|
118
|
+
`fields out; for values, declare the string enum holding exactly the members meant ` +
|
|
119
|
+
`(one-enum-spelling-in-api-lib), or a union of its members. ${wire}`;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/** `(on interface X)` for a heritage clause, `(in X.field)` for a member, `(in type X)` for an alias. */
|
|
123
|
+
owner(file, node) {
|
|
124
|
+
let current = node.parent;
|
|
125
|
+
let member;
|
|
126
|
+
while (current !== undefined && current !== file.source) {
|
|
127
|
+
if ((ts.isPropertySignature(current) || ts.isPropertyDeclaration(current)) && member === undefined) {
|
|
128
|
+
member = current.name.getText(file.source);
|
|
129
|
+
}
|
|
130
|
+
const declared = this.declaredName(current);
|
|
131
|
+
if (declared !== undefined) {
|
|
132
|
+
if (ts.isHeritageClause(node.parent))
|
|
133
|
+
return `(on ${declared})`;
|
|
134
|
+
return member === undefined ? `(in ${declared})` : `(in ${declared}.${member})`;
|
|
135
|
+
}
|
|
136
|
+
current = current.parent;
|
|
137
|
+
}
|
|
138
|
+
return '';
|
|
139
|
+
}
|
|
140
|
+
declaredName(node) {
|
|
141
|
+
if (ts.isInterfaceDeclaration(node))
|
|
142
|
+
return `interface ${node.name.text}`;
|
|
143
|
+
if (ts.isClassDeclaration(node) && node.name !== undefined)
|
|
144
|
+
return `class ${node.name.text}`;
|
|
145
|
+
if (ts.isTypeAliasDeclaration(node))
|
|
146
|
+
return `type ${node.name.text}`;
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
exports.UtilityTypeScanner = UtilityTypeScanner;
|
|
151
|
+
let NoUtilityTypesInApiLibValidator = class NoUtilityTypesInApiLibValidator extends api_lib_source_rule_1.ApiLibSourceRule {
|
|
152
|
+
scanner = new UtilityTypeScanner();
|
|
153
|
+
constructor(config, roleResolver, diffScope) {
|
|
154
|
+
super(config, rules_config_1.RULE_NAMES.NO_UTILITY_TYPES_IN_API_LIB, roleResolver, diffScope);
|
|
155
|
+
}
|
|
156
|
+
sitesIn(file) {
|
|
157
|
+
return this.scanner.scan(file);
|
|
158
|
+
}
|
|
159
|
+
/** Scoped by the configured `paths` globs, not the role tag — an empty list judges nothing. */
|
|
160
|
+
isApiLibrarySource(_workspaceRoot, relFile) {
|
|
161
|
+
return (0, rules_config_1.matchesAnyGlob)(relFile, this.config.paths);
|
|
162
|
+
}
|
|
163
|
+
scopeLabel() {
|
|
164
|
+
return `an API contract library (paths: ${this.config.paths.join(', ')})`;
|
|
165
|
+
}
|
|
166
|
+
why() {
|
|
167
|
+
return 'an API writes its fields out — Omit / Pick / Partial / Required / Exclude / Extract make every reader ' +
|
|
168
|
+
'of the contract compute its field list from another file, and none of them can become a DTO class.';
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
exports.NoUtilityTypesInApiLibValidator = NoUtilityTypesInApiLibValidator;
|
|
172
|
+
exports.NoUtilityTypesInApiLibValidator = NoUtilityTypesInApiLibValidator = tslib_1.__decorate([
|
|
173
|
+
(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
|
+
], NoUtilityTypesInApiLibValidator);
|
|
176
|
+
//# sourceMappingURL=validate-no-utility-types-in-api-lib.js.map
|
|
@@ -0,0 +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,SAAS,EAAE,6EAA6E,CAAC;QAC1F,CAAC,UAAU,EAAE,6EAA6E,CAAC;QAC3F,CAAC,SAAS,EAAE,oEAAoE,CAAC;QACjF,CAAC,SAAS,EAAE,kEAAkE,CAAC;KAClF,CAAC,CAAC;IAEH,IAAI,CAAC,IAAgB;QACjB,MAAM,QAAQ,GAAG,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACxD,MAAM,KAAK,GAAiB,EAAE,CAAC;QAC/B,MAAM,KAAK,GAAG,CAAC,IAAa,EAAQ,EAAE;YAClC,MAAM,IAAI,GAAG,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;YAChD,IAAI,IAA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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"]}
|