@konvert7/klint 0.3.0 → 0.5.0

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.
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { BUILT_IN_PLUGINS } from "../plugins/index";
3
3
  import { BUILT_IN_RULES } from "../rules/index";
4
+ import type { KlintRule, RuleMeta } from "./types";
4
5
 
5
6
  const builtInRuleNames = Object.keys(BUILT_IN_RULES) as [string, ...string[]];
6
7
  const builtInPluginNames = Object.keys(BUILT_IN_PLUGINS) as [string, ...string[]];
@@ -12,18 +13,25 @@ const allKnownRuleNames = [...new Set([...builtInRuleNames, ...pluginRuleNames])
12
13
  ...string[],
13
14
  ];
14
15
 
16
+ /** Look up a rule's implementation across BUILT_IN_RULES and plugin implementations. */
17
+ function findRule(name: string): KlintRule | undefined {
18
+ if (BUILT_IN_RULES[name]) return BUILT_IN_RULES[name];
19
+ for (const plugin of Object.values(BUILT_IN_PLUGINS)) {
20
+ if (plugin.implementations[name]) return plugin.implementations[name];
21
+ }
22
+ return undefined;
23
+ }
24
+
25
+ function metaFor(name: string): RuleMeta | undefined {
26
+ return findRule(name)?.meta;
27
+ }
28
+
15
29
  const SeveritySchema = z
16
30
  .enum(["error", "warn", "off"])
17
31
  .describe(
18
32
  'Rule severity. "error" exits with code 2; "warn" reports but exits 0; "off" silences.'
19
33
  );
20
34
 
21
- const RuleNameSchema = z
22
- .union([z.enum(allKnownRuleNames), z.string()])
23
- .describe(
24
- "Built-in or plugin rule name (with autocomplete) or a custom rule name defined in klint.rules.ts."
25
- );
26
-
27
35
  const RuleOptionsSchema = z
28
36
  .object({
29
37
  severity: SeveritySchema.optional(),
@@ -39,6 +47,165 @@ const RuleOptionsSchema = z
39
47
  'Rule options object. Omit severity to default to "error". Add include to scope the rule to specific files.'
40
48
  );
41
49
 
50
+ const RuleValueSchema = z.union([SeveritySchema, RuleOptionsSchema]);
51
+
52
+ // ─── arch ─────────────────────────────────────────────────────────────
53
+
54
+ const ArchSeveritySchema = z
55
+ .enum(["error", "warn"])
56
+ .describe(
57
+ 'Severity for the arch rule. "error" exits with code 2; "warn" reports but exits 0. (arch rules cannot be "off" — remove the entry instead.)'
58
+ );
59
+
60
+ const StringOrStringArray = z
61
+ .union([z.string(), z.array(z.string())])
62
+ .describe(
63
+ "Either a single layer name / glob pattern or an array of them. Layer names defined in `arch.layers` are resolved to their glob lists."
64
+ );
65
+
66
+ const ArchLayersSchema = z
67
+ .record(z.string(), z.array(z.string()))
68
+ .describe(
69
+ "Named architectural zones. Keys are arbitrary layer names; values are glob patterns matching the files in that layer. Other arch rules reference these names instead of repeating globs."
70
+ )
71
+ .meta({
72
+ examples: [
73
+ 'layers:\n core: ["src/hooks/lib/**", "src/tools/**"]\n skills: ["assets/skills/**"]\n dao: ["src/dao/**"]',
74
+ ],
75
+ });
76
+
77
+ const ArchImportRuleSchema = z
78
+ .object({
79
+ from: StringOrStringArray.describe(
80
+ "Source — a layer name or glob(s) for the files this rule applies to. Imports originating in `from` are checked against `deny`/`allow`."
81
+ ),
82
+ deny: StringOrStringArray.optional().describe(
83
+ "Layer name(s) or glob(s) the source is not allowed to import from. Mutually exclusive in spirit with `allow` (use one or the other)."
84
+ ),
85
+ allow: StringOrStringArray.optional().describe(
86
+ "Allowlist of layer name(s) / glob(s) the source may import from. Anything not matching `allow` is denied."
87
+ ),
88
+ "type-only": z
89
+ .literal("allow")
90
+ .optional()
91
+ .describe(
92
+ 'When set to "allow", `import type` statements that would otherwise be denied are permitted. Useful for type-only references across layers.'
93
+ ),
94
+ message: z
95
+ .string()
96
+ .optional()
97
+ .describe(
98
+ "Custom error message reported when the rule is violated. Shown in the agent's event stream alongside file:line."
99
+ ),
100
+ severity: ArchSeveritySchema.optional(),
101
+ })
102
+ .strict()
103
+ .describe(
104
+ "An import-boundary rule. Restricts which layers a source can or cannot import from."
105
+ )
106
+ .meta({
107
+ examples: [
108
+ 'arch:\n imports:\n - from: skills\n deny: core\n message: "Skills must be self-contained and portable"\n severity: warn',
109
+ 'arch:\n imports:\n - from: ["src/dao/**"]\n allow: ["src/dao/**", "src/prisma/**", "src/types/**"]',
110
+ ],
111
+ });
112
+
113
+ const ArchForbiddenRuleSchema = z
114
+ .object({
115
+ pattern: z
116
+ .string()
117
+ .describe(
118
+ "Literal substring to search for in source. No regex — exact substring match (e.g. `console.log(`)."
119
+ ),
120
+ in: StringOrStringArray.describe(
121
+ "Layer name(s) or glob(s) the pattern is forbidden in. Files outside the scope are not checked."
122
+ ),
123
+ message: z
124
+ .string()
125
+ .describe(
126
+ "Required error message explaining why the pattern is forbidden. Shown to the agent so it can fix the call site."
127
+ ),
128
+ severity: ArchSeveritySchema.optional(),
129
+ })
130
+ .strict()
131
+ .describe(
132
+ "A forbidden-pattern rule. Blocks literal substrings (console.log, process.exit, raw SDK fetches, etc.) inside specific layers."
133
+ )
134
+ .meta({
135
+ examples: [
136
+ 'arch:\n forbidden:\n - pattern: "console.log("\n in: core\n message: "Leaks into the agent event stream"',
137
+ ],
138
+ });
139
+
140
+ const ArchSingletonRuleSchema = z
141
+ .object({
142
+ pattern: z
143
+ .string()
144
+ .describe(
145
+ "Literal substring whose appearance is allowed only at one location. Exact substring match (e.g. `process.env.API_KEY`)."
146
+ ),
147
+ only: z
148
+ .string()
149
+ .describe(
150
+ "The single file path where this pattern is allowed. Every other occurrence becomes a violation."
151
+ ),
152
+ in: StringOrStringArray.optional().describe(
153
+ "Optional scope. Limit the scan to these layers/globs; defaults to all files in `include`."
154
+ ),
155
+ message: z
156
+ .string()
157
+ .describe(
158
+ "Required error message explaining why the pattern must stay singleton (security boundary, module-of-record, etc.)."
159
+ ),
160
+ severity: ArchSeveritySchema.optional(),
161
+ })
162
+ .strict()
163
+ .describe(
164
+ "A singleton-location rule. Pins a pattern to exactly one file — the only honest way to enforce a module of record."
165
+ )
166
+ .meta({
167
+ examples: [
168
+ 'arch:\n singleton:\n - pattern: "process.env.API_KEY"\n only: "src/lib/auth.ts"\n message: "API key access must funnel through the auth module."',
169
+ ],
170
+ });
171
+
172
+ const ArchSchema = z
173
+ .object({
174
+ layers: ArchLayersSchema.optional(),
175
+ imports: z
176
+ .array(ArchImportRuleSchema)
177
+ .optional()
178
+ .describe(
179
+ "Import-boundary rules. The dependency graph your README claims you have."
180
+ ),
181
+ forbidden: z
182
+ .array(ArchForbiddenRuleSchema)
183
+ .optional()
184
+ .describe("Forbidden-pattern rules. Block literal strings scoped to a layer."),
185
+ singleton: z
186
+ .array(ArchSingletonRuleSchema)
187
+ .optional()
188
+ .describe(
189
+ "Singleton-location rules. Pin a pattern to one file; every other touch is a violation."
190
+ ),
191
+ })
192
+ .strict()
193
+ .describe(
194
+ "Architecture-as-Code constraints — layers, import boundaries, forbidden patterns, singleton locations. Enforced by the arch engine alongside the rule set."
195
+ );
196
+
197
+ function buildRulesSchema() {
198
+ const shape: Record<string, z.ZodType> = {};
199
+ for (const name of allKnownRuleNames) {
200
+ const meta = metaFor(name);
201
+ let entry: z.ZodType = RuleValueSchema.optional();
202
+ if (meta?.description) entry = entry.describe(meta.description);
203
+ if (meta?.examples?.length) entry = entry.meta({ examples: meta.examples });
204
+ shape[name] = entry;
205
+ }
206
+ return z.object(shape).catchall(RuleValueSchema);
207
+ }
208
+
42
209
  export const KlintConfigSchema = z
43
210
  .object({
44
211
  $schema: z
@@ -65,18 +232,12 @@ export const KlintConfigSchema = z
65
232
  .describe(
66
233
  'Named rule bundles to enable. Each plugin applies a default set of rules at "error" severity. Individual rules from the bundle can be overridden or silenced via the rules map. Available: "sonar".'
67
234
  ),
68
- rules: z
69
- .record(RuleNameSchema, z.union([SeveritySchema, RuleOptionsSchema]))
70
- .optional()
71
- .describe(
72
- 'Map of rule name → severity or options. Example: { "no-floating-promise": "error", "no-sync-in-async": { "severity": "warn", "include": ["src/hooks/**"] } }. Run `klint --help` for the full rule list.'
73
- ),
74
- arch: z
75
- .unknown()
235
+ rules: buildRulesSchema()
76
236
  .optional()
77
237
  .describe(
78
- "Architecture as Code constraints — layers, import boundaries, forbidden patterns, singleton locations. Parsed by the arch engine (Phase 2)."
238
+ 'Map of rule name → severity or options. Example: { "no-floating-promise": "error", "no-sync-in-async": { "severity": "warn", "include": ["src/hooks/**"] } }.'
79
239
  ),
240
+ arch: ArchSchema.optional(),
80
241
  })
81
242
  .strict()
82
243
  .describe(
package/core/types.ts CHANGED
@@ -33,8 +33,16 @@ export interface RuleContext {
33
33
  /** Violation as emitted by a rule — rule name and severity are stamped by the runner. */
34
34
  export type RawViolation = Omit<Violation, "rule" | "severity">;
35
35
 
36
+ export interface RuleMeta {
37
+ /** One- or two-line description of what the rule catches. */
38
+ description: string;
39
+ /** Concrete YAML config snippets showing usage. Rendered as code blocks in docs. */
40
+ examples?: string[];
41
+ }
42
+
36
43
  export interface KlintRule {
37
44
  check: (ctx: RuleContext, violations: RawViolation[]) => void;
45
+ meta?: RuleMeta;
38
46
  }
39
47
 
40
48
  /** A named bundle of rules with their default severities and implementations. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@konvert7/klint",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Architecture-as-Code linter for TypeScript. Enforce layer boundaries, import rules, and singleton patterns in YAML.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -39,6 +39,7 @@
39
39
  "check-write": "biome check --write",
40
40
  "knip": "knip-bun",
41
41
  "klint": "bun cli.ts",
42
+ "schema": "bun tools/generate-schema.ts",
42
43
  "lint-staged": "lint-staged",
43
44
  "prepare": "bun .husky/install.mjs"
44
45
  },
@@ -7,6 +7,11 @@ import { defineRule } from "../core/types";
7
7
  const PREDICATE_METHODS = new Set(["filter", "some", "every", "find", "findIndex"]);
8
8
 
9
9
  export const noAsyncPredicate = defineRule({
10
+ meta: {
11
+ description:
12
+ "Flags `async` functions passed to `.filter`/`.some`/`.every`/`.find`/`.findIndex`. Array methods coerce the returned promise to truthy, so every element appears to match.",
13
+ examples: ["no-async-predicate: error"],
14
+ },
10
15
  check({ files, root }, violations) {
11
16
  const program = createProgram(files, root);
12
17
  const checker = program.getTypeChecker();
@@ -4,6 +4,11 @@ import { walkAst } from "../core/ast";
4
4
  import type { KlintRule } from "../core/types";
5
5
 
6
6
  export const noConsecutiveArrayPush: KlintRule = {
7
+ meta: {
8
+ description:
9
+ "Flags consecutive `arr.push(x); arr.push(y);` calls — combine into `arr.push(x, y)` or `arr.push(...items)`.",
10
+ examples: ["no-consecutive-array-push: warn"],
11
+ },
7
12
  check({ files, root, fileContents }, violations) {
8
13
  for (const file of files) {
9
14
  const content = fileContents.get(file) ?? "";
@@ -5,6 +5,11 @@ import type { RawViolation } from "../core/types";
5
5
  import { defineRule } from "../core/types";
6
6
 
7
7
  export const noDateEquality = defineRule({
8
+ meta: {
9
+ description:
10
+ "Flags `Date` comparisons with `==`/`===`/`!=`/`!==` — these compare object identity, not the time value. Use `.getTime()` instead.",
11
+ examples: ["no-date-equality: error"],
12
+ },
8
13
  check({ files, root }, violations) {
9
14
  const program = createProgram(files, root);
10
15
  const checker = program.getTypeChecker();
@@ -5,6 +5,11 @@ import type { RawViolation } from "../core/types";
5
5
  import { defineRule } from "../core/types";
6
6
 
7
7
  export const noFloatingPromise = defineRule({
8
+ meta: {
9
+ description:
10
+ "Flags Promise-returning expressions that aren't awaited or `.catch()`-handled — silent failures and unpredictable execution order.",
11
+ examples: ["no-floating-promise: error"],
12
+ },
8
13
  check({ files, root }, violations) {
9
14
  const program = createProgram(files, root);
10
15
  const checker = program.getTypeChecker();
@@ -5,6 +5,11 @@ import type { RawViolation } from "../core/types";
5
5
  import { defineRule } from "../core/types";
6
6
 
7
7
  export const noMisusedPromises = defineRule({
8
+ meta: {
9
+ description:
10
+ "Flags Promises passed where the type expects a non-thenable (e.g. an `if` condition, a `void` callback). The Promise's truthiness — not its resolved value — drives the branch.",
11
+ examples: ["no-misused-promises: error"],
12
+ },
8
13
  check({ files, root }, violations) {
9
14
  const program = createProgram(files, root);
10
15
  const checker = program.getTypeChecker();
@@ -4,6 +4,11 @@ import { walkAst } from "../core/ast";
4
4
  import type { KlintRule } from "../core/types";
5
5
 
6
6
  export const noNestedTemplateLiterals: KlintRule = {
7
+ meta: {
8
+ description:
9
+ "Flags template literals nested inside template literals — almost always unreadable; extract to a variable.",
10
+ examples: ["no-nested-template-literals: warn"],
11
+ },
7
12
  check({ files, root, fileContents }, violations) {
8
13
  for (const file of files) {
9
14
  const content = fileContents.get(file) ?? "";
@@ -22,6 +22,11 @@ const SAFE_SYMBOL_NAMES = new Set([
22
22
  ]);
23
23
 
24
24
  export const noObjectInTemplate = defineRule({
25
+ meta: {
26
+ description:
27
+ "Flags non-primitive objects interpolated into template literals — produces `[object Object]` unless `toString()` is overridden.",
28
+ examples: ["no-object-in-template: error"],
29
+ },
25
30
  check({ files, root }, violations) {
26
31
  const program = createProgram(files, root);
27
32
  const checker = program.getTypeChecker();
@@ -5,6 +5,11 @@ import type { RawViolation } from "../core/types";
5
5
  import { defineRule } from "../core/types";
6
6
 
7
7
  export const noOptionalChainOnNonNullable = defineRule({
8
+ meta: {
9
+ description:
10
+ "Flags `?.` on receivers whose static type cannot be `null` or `undefined`. The optional chain is dead code and obscures the real shape.",
11
+ examples: ["no-optional-chain-on-non-nullable: warn"],
12
+ },
8
13
  check({ files, root }, violations) {
9
14
  const program = createProgram(files, root);
10
15
  const checker = program.getTypeChecker();
@@ -63,6 +63,11 @@ function parseCharClasses(pattern: string): CharClass[] {
63
63
  }
64
64
 
65
65
  export const noSingleCharClass: KlintRule = {
66
+ meta: {
67
+ description:
68
+ "Flags single-character character classes in regex (e.g. `/[a]/`) — drop the brackets; the regex matches the same.",
69
+ examples: ["sonar/no-single-char-class: warn"],
70
+ },
66
71
  check({ files, root, fileContents }, violations) {
67
72
  for (const file of files) {
68
73
  const content = fileContents.get(file) ?? "";
@@ -4,6 +4,11 @@ import { walkAst } from "../core/ast";
4
4
  import type { KlintRule } from "../core/types";
5
5
 
6
6
  export const noStringMatch: KlintRule = {
7
+ meta: {
8
+ description:
9
+ "Flags `String#match` — prefer `.matchAll()` for iteration or `.test()` for boolean checks. `.match()` returns different shapes depending on the `/g` flag.",
10
+ examples: ["no-string-match: error"],
11
+ },
7
12
  check({ files, root, fileContents }, violations) {
8
13
  for (const file of files) {
9
14
  const content = fileContents.get(file) ?? "";
@@ -4,6 +4,14 @@ import { nearestFunctionIsAsync, walkAst } from "../core/ast";
4
4
  import type { KlintRule } from "../core/types";
5
5
 
6
6
  export const noSyncInAsync: KlintRule = {
7
+ meta: {
8
+ description:
9
+ "Flags synchronous I/O (`readFileSync`, `execSync`, etc.) inside async functions — blocks the event loop when an async equivalent is available.",
10
+ examples: [
11
+ "no-sync-in-async: error",
12
+ 'no-sync-in-async:\n severity: warn\n include: ["src/server/**"]',
13
+ ],
14
+ },
7
15
  check({ files, root, fileContents }, violations) {
8
16
  for (const file of files) {
9
17
  const content = fileContents.get(file) ?? "";
@@ -4,6 +4,11 @@ import { isInsideTry, walkAst } from "../core/ast";
4
4
  import type { KlintRule } from "../core/types";
5
5
 
6
6
  export const noUnguardedJsonParse: KlintRule = {
7
+ meta: {
8
+ description:
9
+ "Flags `JSON.parse()` calls that aren't wrapped in try/catch — malformed input crashes the process.",
10
+ examples: ["no-unguarded-json-parse: error"],
11
+ },
7
12
  check({ files, root, fileContents }, violations) {
8
13
  for (const file of files) {
9
14
  const content = fileContents.get(file) ?? "";
@@ -4,6 +4,11 @@ import { walkAst } from "../core/ast";
4
4
  import type { KlintRule } from "../core/types";
5
5
 
6
6
  export const preferAt: KlintRule = {
7
+ meta: {
8
+ description:
9
+ "Flags negative-index access via `arr[arr.length - 1]` — `.at(-1)` reads cleaner for last-element access.",
10
+ examples: ["sonar/prefer-at: warn"],
11
+ },
7
12
  check({ files, root, fileContents }, violations) {
8
13
  for (const file of files) {
9
14
  const content = fileContents.get(file) ?? "";
@@ -4,6 +4,11 @@ import { walkAst } from "../core/ast";
4
4
  import type { KlintRule } from "../core/types";
5
5
 
6
6
  export const preferNullishCoalescingAssign: KlintRule = {
7
+ meta: {
8
+ description:
9
+ "Flags `x = x ?? y` patterns — `x ??= y` is the dedicated nullish assignment operator.",
10
+ examples: ["sonar/prefer-nullish-coalescing-assign: warn"],
11
+ },
7
12
  check({ files, root, fileContents }, violations) {
8
13
  for (const file of files) {
9
14
  const content = fileContents.get(file) ?? "";
@@ -4,6 +4,11 @@ import { walkAst } from "../core/ast";
4
4
  import type { KlintRule } from "../core/types";
5
5
 
6
6
  export const preferStringRawRegexp: KlintRule = {
7
+ meta: {
8
+ description:
9
+ "Flags regex literals built from escape-heavy string concatenation — `String.raw` drops the double backslashes.",
10
+ examples: ["sonar/prefer-string-raw-regexp: warn"],
11
+ },
7
12
  check({ files, root, fileContents }, violations) {
8
13
  for (const file of files) {
9
14
  const content = fileContents.get(file) ?? "";
@@ -4,6 +4,11 @@ import { walkAst } from "../core/ast";
4
4
  import type { KlintRule } from "../core/types";
5
5
 
6
6
  export const preferStringRaw: KlintRule = {
7
+ meta: {
8
+ description:
9
+ "Flags string literals with multiple backslash escapes — `String.raw` is more readable (Windows paths, regex source, etc.).",
10
+ examples: ["sonar/prefer-string-raw: warn"],
11
+ },
7
12
  check({ files, root, fileContents }, violations) {
8
13
  for (const file of files) {
9
14
  const content = fileContents.get(file) ?? "";
@@ -4,6 +4,11 @@ import { walkAst } from "../core/ast";
4
4
  import type { KlintRule } from "../core/types";
5
5
 
6
6
  export const preferStringReplaceall: KlintRule = {
7
+ meta: {
8
+ description:
9
+ "Flags `.replace(/x/g, y)` on strings — `.replaceAll('x', y)` is clearer and faster for all-occurrence replacements.",
10
+ examples: ["sonar/prefer-string-replaceall: error"],
11
+ },
7
12
  check({ files, root, fileContents }, violations) {
8
13
  for (const file of files) {
9
14
  const content = fileContents.get(file) ?? "";
@@ -3,27 +3,10 @@ import { writeFileSync } from "node:fs";
3
3
  import { resolve } from "node:path";
4
4
  import { stringify as toYaml } from "yaml";
5
5
  import { KlintConfigSchema } from "../core/config.schema";
6
- import { BUILT_IN_PLUGINS } from "../plugins/index";
7
- import { BUILT_IN_RULES } from "../rules/index";
8
-
9
- const allKnownRuleNames = [
10
- ...Object.keys(BUILT_IN_RULES),
11
- ...Object.values(BUILT_IN_PLUGINS).flatMap((p) => Object.keys(p.rules)),
12
- ];
13
6
 
14
7
  const raw = KlintConfigSchema.toJSONSchema() as Record<string, unknown>;
15
8
 
16
- // VS Code reads `properties` for key autocomplete, not `propertyNames`.
17
- // Expand known rule names into explicit property entries so editors suggest them.
18
- // `additionalProperties` stays to allow custom rule names without validation errors.
19
- const rulesSchema = (raw.properties as Record<string, Record<string, unknown>>).rules;
20
- const valueSchema = rulesSchema.additionalProperties;
21
- rulesSchema.properties = Object.fromEntries(
22
- allKnownRuleNames.map((name) => [name, valueSchema])
23
- );
24
- delete rulesSchema.propertyNames;
25
-
26
- // Remove the 2020-12 $schema key; set Draft-07 for broad editor compatibility
9
+ // Set Draft-07 (broad editor compatibility) instead of 2020-12.
27
10
  delete raw.$schema;
28
11
 
29
12
  const schema = {
@@ -32,10 +15,10 @@ const schema = {
32
15
  ...raw,
33
16
  };
34
17
 
35
- const jsonOutPath = resolve(import.meta.dir, "../../klint.schema.json");
18
+ const jsonOutPath = resolve(import.meta.dir, "../klint.schema.json");
36
19
  writeFileSync(jsonOutPath, `${JSON.stringify(schema, null, 2)}\n`);
37
20
  process.stdout.write(`Generated ${jsonOutPath}\n`);
38
21
 
39
- const yamlOutPath = resolve(import.meta.dir, "../../klint.schema.yaml");
22
+ const yamlOutPath = resolve(import.meta.dir, "../klint.schema.yaml");
40
23
  writeFileSync(yamlOutPath, toYaml(schema, { lineWidth: 120 }));
41
24
  process.stdout.write(`Generated ${yamlOutPath}\n`);