architecture-harness 0.9.0 → 0.10.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "architecture-harness",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "type": "module",
5
5
  "description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
6
6
  "license": "MIT",
@@ -76,6 +76,7 @@
76
76
  "@typescript-eslint/eslint-plugin": "^8",
77
77
  "@typescript-eslint/parser": "^8",
78
78
  "eslint-plugin-boundaries": "^5",
79
- "eslint-plugin-sonarjs": "^3"
79
+ "eslint-plugin-sonarjs": "^3",
80
+ "typescript": "^5"
80
81
  }
81
82
  }
package/src/cli/check.mjs CHANGED
@@ -30,7 +30,8 @@ import { checkAdrFormat } from "../gates/adr-format.mjs";
30
30
  import { checkConfigFloor } from "../gates/config-floor.mjs";
31
31
  import { defaults } from "../config.mjs";
32
32
  import { rules as lintRules } from "../eslint/index.mjs";
33
- import { enabled } from "../config.mjs";
33
+ import { enabled, readerEntries, thresholds } from "../config.mjs";
34
+ import { checkRegistryReaders } from "../gates/registry-readers.mjs";
34
35
  import { repoFiles } from "./repo-files.mjs";
35
36
 
36
37
  // Each skip is tested on "/" + the relative path, so it reads a path the way it read a full one.
@@ -454,6 +455,14 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
454
455
  problems.push(...(await agreements(config)));
455
456
  }
456
457
 
458
+ if (enabled(config.gates, "registry-readers")) {
459
+ const entries = readerEntries(thresholds(config));
460
+ const readers = [...new Set(entries.flatMap((entry) => entry.readers))];
461
+ const sources = new Map(await Promise.all(readers.map(async (reader) => [reader, await read(path.join(config.root, reader))])));
462
+ problems.push(...checkRegistryReaders(entries, sources));
463
+ if (readers.length > 0) lines.push(`OK readers ${readers.length} registry reader(s), each present and naming its entry`);
464
+ }
465
+
457
466
  if (enabled(config.gates, "sql-identifiers") || enabled(config.gates, "tenant-predicate")) {
458
467
  problems.push(...(await sqlAgreement(config, tree, taken)));
459
468
  lines.push("OK sql every column is declared, every statement and shared insert carries the tenant");
package/src/config.mjs CHANGED
@@ -241,6 +241,13 @@ export const defaults = {
241
241
  // racing against a cancellation, and observing a rejection nobody is waiting for any more.
242
242
  promise: { allow: [] },
243
243
 
244
+ // Enter and Escape in text entry wait for the IME. `components` are a repository's own text
245
+ // inputs. `guards` name the one guard function; empty accepts an inline isComposing or keyCode check.
246
+ ime: { components: [], guards: [] },
247
+
248
+ // Files a person reviewed that may call sql.raw. Each one is a decision, so the list stays short.
249
+ sqlRaw: { allow: [] },
250
+
244
251
  anatomy: {
245
252
  // Bounded vertical slices.
246
253
  slice: {
@@ -264,6 +271,7 @@ export const defaults = {
264
271
  "eight-blocks": true,
265
272
  citations: true,
266
273
  "registry-agreement": true,
274
+ "registry-readers": true,
267
275
  "sql-identifiers": true,
268
276
  "tenant-predicate": true,
269
277
  "claimed-requirements": true,
@@ -306,6 +314,9 @@ export const defaults = {
306
314
  "tenant-scoped-table": true,
307
315
  "signal-last-param": true,
308
316
  "no-raw-fetch": true,
317
+ "no-sql-raw": true,
318
+ "ime-safe-key": true,
319
+ "registry-literal": true,
309
320
  "durable-idempotency-key": true,
310
321
  "no-supersession-trail": true,
311
322
  },
@@ -376,6 +387,16 @@ export function thresholds(config) {
376
387
  return createRequire(import.meta.url)(file).gates ?? {};
377
388
  }
378
389
 
390
+ /**
391
+ * Registry entries that say who may hold their number. `names` are identifier patterns, each a
392
+ * regular expression matched against the whole identifier, case-insensitive. `readers` are paths.
393
+ */
394
+ export function readerEntries(registry) {
395
+ return Object.entries(registry)
396
+ .filter(([, entry]) => entry.names?.length > 0 || entry.readers?.length > 0)
397
+ .map(([key, entry]) => ({ key, names: entry.names ?? [], readers: entry.readers ?? [] }));
398
+ }
399
+
379
400
  export function enabled(map, id) {
380
401
  return map[id] !== false;
381
402
  }
@@ -4,6 +4,7 @@ export const gateDescriptions = Object.freeze({
4
4
  "eight-blocks": "A feature keeps the anatomy it declares, and no block or slice is empty",
5
5
  citations: "Every cited id and doc path resolves, and nothing references another repository",
6
6
  "registry-agreement": "A value written twice agrees with the registry that owns it",
7
+ "registry-readers": "Every reader a registry entry names exists and names the entry",
7
8
  "sql-identifiers": "A query names a column a migration declares, and only its own feature's tables",
8
9
  "tenant-predicate": "Every statement on a business table filters on the tenant",
9
10
  "claimed-requirements": "A requirement a route claims names the test that proves it",
@@ -1,6 +1,8 @@
1
1
  import durableIdempotencyKey from "./rules/durable-idempotency-key.mjs";
2
2
  import externalServiceOnlyInAdapter from "./rules/external-service-only-in-adapter.mjs";
3
+ import imeSafeKey from "./rules/ime-safe-key.mjs";
3
4
  import noCrossFeatureInternals from "./rules/no-cross-feature-internals.mjs";
5
+ import registryLiteral from "./rules/registry-literal.mjs";
4
6
  import noCommentParagraph from "./rules/no-comment-paragraph.mjs";
5
7
  import nameThePattern from "./rules/name-the-pattern.mjs";
6
8
  import noPromiseThen from "./rules/no-promise-then.mjs";
@@ -8,6 +10,7 @@ import noNumberInComment from "./rules/no-number-in-comment.mjs";
8
10
  import noOffsetPagination from "./rules/no-offset-pagination.mjs";
9
11
  import noOrchestrationInTrigger from "./rules/no-orchestration-in-trigger.mjs";
10
12
  import noRawFetch from "./rules/no-raw-fetch.mjs";
13
+ import noSqlRaw from "./rules/no-sql-raw.mjs";
11
14
  import noStatusLiteral from "./rules/no-status-literal.mjs";
12
15
  import noSupersessionTrail from "./rules/no-supersession-trail.mjs";
13
16
  import scopedRepository from "./rules/scoped-repository.mjs";
@@ -18,7 +21,9 @@ import tenantScopedTable from "./rules/tenant-scoped-table.mjs";
18
21
  export const rules = {
19
22
  "durable-idempotency-key": durableIdempotencyKey,
20
23
  "external-service-only-in-adapter": externalServiceOnlyInAdapter,
24
+ "ime-safe-key": imeSafeKey,
21
25
  "no-cross-feature-internals": noCrossFeatureInternals,
26
+ "registry-literal": registryLiteral,
22
27
  "no-comment-paragraph": noCommentParagraph,
23
28
  "name-the-pattern": nameThePattern,
24
29
  "no-promise-then": noPromiseThen,
@@ -26,6 +31,7 @@ export const rules = {
26
31
  "no-offset-pagination": noOffsetPagination,
27
32
  "no-orchestration-in-trigger": noOrchestrationInTrigger,
28
33
  "no-raw-fetch": noRawFetch,
34
+ "no-sql-raw": noSqlRaw,
29
35
  "no-status-literal": noStatusLiteral,
30
36
  "no-supersession-trail": noSupersessionTrail,
31
37
  "scoped-repository": scopedRepository,
@@ -2,11 +2,14 @@
2
2
  // Thresholds are imported, never restated — quality-thresholds.json is their one home.
3
3
 
4
4
  import qc from "./index.mjs";
5
- import { enabled, load, thresholds } from "../config.mjs";
5
+ import { enabled, load, readerEntries, thresholds } from "../config.mjs";
6
6
 
7
7
  /** Options each rule needs, derived from one config so a name is written once. */
8
- function ruleOptions(config) {
8
+ function ruleOptions(config, registry) {
9
9
  return {
10
+ "no-sql-raw": { allow: config.sqlRaw.allow },
11
+ "ime-safe-key": { components: config.ime.components, guards: config.ime.guards },
12
+ "registry-literal": { entries: readerEntries(registry).filter((entry) => entry.names.length > 0) },
10
13
  "no-comment-paragraph": {
11
14
  doc: config.enforcement ?? "docs/enforcement.md",
12
15
  decisions: config.docs.decisions,
@@ -48,8 +51,8 @@ function ruleOptions(config) {
48
51
  };
49
52
  }
50
53
 
51
- function entries(config, names) {
52
- const options = ruleOptions(config);
54
+ function entries(config, names, registry = {}) {
55
+ const options = ruleOptions(config, registry);
53
56
  const out = {};
54
57
  for (const name of names) {
55
58
  if (!enabled(config.rules, name)) continue;
@@ -75,13 +78,16 @@ const UNIVERSAL = [
75
78
  // Not a layered-architecture concern like the SERVER rules below — a worker or a
76
79
  // composition root outside backend/src needs this exactly as much as backend/src does.
77
80
  "external-service-only-in-adapter",
81
+ // A worker or a script builds a query and holds a number as much as a feature does.
82
+ "no-sql-raw",
83
+ "registry-literal",
78
84
  ];
79
85
 
80
86
  /** Rules that only make sense where the server's storage and ports live. */
81
87
  const SERVER = ["storage-only-in-resource", "tenant-scoped-table", "signal-last-param"];
82
88
 
83
89
  /** Rules that only make sense in the browser. */
84
- const CLIENT = ["no-raw-fetch", "storage-only-in-resource"];
90
+ const CLIENT = ["no-raw-fetch", "storage-only-in-resource", "ime-safe-key"];
85
91
 
86
92
  /**
87
93
  * The architecture as a flat config. Spread it, then append your own blocks.
@@ -96,13 +102,22 @@ export function preset(options = {}) {
96
102
  const max = (id) => gates[id]?.value;
97
103
  const { tseslint, boundaries, sonarjs } = options.plugins ?? {};
98
104
 
99
- const blocks = [{ ignores: config.ignores }];
105
+ // No file carries its own exemption: a rule is switched off in config, where a reviewer sees it.
106
+ const blocks = [{ ignores: config.ignores }, { linterOptions: { noInlineConfig: true, reportUnusedDisableDirectives: "error" } }];
100
107
 
101
108
  const base = {
102
109
  files: ["**/*.{ts,tsx,mjs}"],
103
110
  plugins: { qc, ...(tseslint ? { "@typescript-eslint": tseslint } : {}), ...(sonarjs ? { sonarjs } : {}) },
104
111
  rules: {
105
- ...(tseslint ? { "@typescript-eslint/no-explicit-any": "error" } : {}),
112
+ ...(tseslint
113
+ ? {
114
+ "@typescript-eslint/no-explicit-any": "error",
115
+ "@typescript-eslint/ban-ts-comment": [
116
+ "error",
117
+ { "ts-ignore": true, "ts-nocheck": true, "ts-check": false, "ts-expect-error": "allow-with-description" },
118
+ ],
119
+ }
120
+ : {}),
106
121
  ...(sonarjs
107
122
  ? {
108
123
  "sonarjs/no-identical-functions": "error",
@@ -116,7 +131,7 @@ export function preset(options = {}) {
116
131
  ? { "max-lines-per-function": ["error", { max: max("funclength"), skipBlankLines: true, skipComments: true }] }
117
132
  : {}),
118
133
  ...(max("nesting") ? { "max-depth": ["error", max("nesting")] } : {}),
119
- ...entries(config, UNIVERSAL),
134
+ ...entries(config, UNIVERSAL, gates),
120
135
  },
121
136
  };
122
137
  if (options.languageOptions) base.languageOptions = options.languageOptions;
@@ -1,5 +1,11 @@
1
1
  import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
+ import { mkdtempSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import { Linter } from "eslint";
7
+ import tseslint from "@typescript-eslint/eslint-plugin";
8
+ import tsparser from "@typescript-eslint/parser";
3
9
  import { defaults, merge } from "../config.mjs";
4
10
  import { rules as allRules } from "./index.mjs";
5
11
  import { preset } from "./preset.mjs";
@@ -80,6 +86,62 @@ test("a repository with no layers still gets the browser rules", () => {
80
86
  assert.ok(client.rules["qc/no-raw-fetch"]);
81
87
  });
82
88
 
89
+ /** One file through the whole preset, the way a consumer's `eslint .` sees it. */
90
+ function lint(code, filename, override = {}) {
91
+ const blocks = preset({
92
+ config: config(override),
93
+ plugins: { tseslint },
94
+ languageOptions: { parser: tsparser, ecmaVersion: 2023, sourceType: "module" },
95
+ });
96
+ return new Linter({ configType: "flat" }).verify(code, blocks, filename);
97
+ }
98
+
99
+ const RESOURCE = "backend/src/features/pins/resource.ts";
100
+ const MIGRATE = "backend/src/infrastructure/db/migrate.ts";
101
+ const byRule = (messages, ruleId) => messages.filter((m) => m.ruleId === ruleId);
102
+
103
+ test("a registry entry with names reaches qc/registry-literal, and one without stays out", () => {
104
+ const root = mkdtempSync(path.join(tmpdir(), "qc-preset-"));
105
+ const holdpress = { value: 400, names: ["HOLD_\\w*MS"], readers: ["frontend/src/platform/gesture-thresholds.ts"] };
106
+ writeFileSync(path.join(root, "quality-thresholds.json"), JSON.stringify({ gates: { holdpress, coverage: { value: 70 } } }));
107
+ const setting = emitted(preset({ config: { ...config(), root } })).get("qc/registry-literal");
108
+ assert.deepEqual(setting[1].entries, [{ key: "holdpress", names: holdpress.names, readers: holdpress.readers }]);
109
+ });
110
+
111
+ test("the ime config reaches qc/ime-safe-key", () => {
112
+ const setting = emitted(preset({ config: config({ ime: { guards: ["isImeComposing"] } }) })).get("qc/ime-safe-key");
113
+ assert.deepEqual(setting[1], { components: [], guards: ["isImeComposing"] });
114
+ });
115
+
116
+ test("the preset refuses an inline config comment in every file", () => {
117
+ const block = preset({ config: config() }).find((b) => b.linterOptions);
118
+ assert.ok(block, "no linterOptions block emitted");
119
+ assert.equal(block.files, undefined, "linterOptions must reach every file");
120
+ assert.deepEqual(block.linterOptions, { noInlineConfig: true, reportUnusedDisableDirectives: "error" });
121
+ });
122
+
123
+ test("an inline disable comment does not silence a rule", () => {
124
+ const messages = lint("// eslint-disable-next-line qc/no-sql-raw\nawait db.execute(sql.raw(text));\n", RESOURCE);
125
+ assert.equal(byRule(messages, "qc/no-sql-raw").length, 1, "the disable comment silenced the rule");
126
+ const directive = messages.find((m) => m.ruleId === null && /noInlineConfig/.test(m.message));
127
+ assert.ok(directive, "the ignored disable comment is not reported");
128
+ });
129
+
130
+ test("sql.raw fails, and sqlRaw.allow lets one reviewed file through", () => {
131
+ const code = "await db.execute(sql.raw(ddl));\n";
132
+ assert.equal(byRule(lint(code, RESOURCE), "qc/no-sql-raw")[0]?.severity, 2);
133
+ assert.equal(byRule(lint(code, MIGRATE, { sqlRaw: { allow: [MIGRATE] } }), "qc/no-sql-raw").length, 0);
134
+ assert.equal(byRule(lint(code, RESOURCE, { sqlRaw: { allow: [MIGRATE] } }), "qc/no-sql-raw").length, 1);
135
+ });
136
+
137
+ test("ts-ignore and ts-nocheck fail; ts-expect-error passes only with a description", () => {
138
+ const banned = (code) => byRule(lint(code, RESOURCE), "@typescript-eslint/ban-ts-comment").length;
139
+ assert.equal(banned("// @ts-ignore\nconst a = 1;\n"), 1);
140
+ assert.equal(banned("// @ts-nocheck\nconst a = 1;\n"), 1);
141
+ assert.equal(banned("// @ts-expect-error\nconst a = 1;\n"), 1);
142
+ assert.equal(banned("// @ts-expect-error: the vendor type omits this field\nconst a = 1;\n"), 0);
143
+ });
144
+
83
145
  test("the frontendLayers block is emitted when configured and boundaries plugin is supplied", () => {
84
146
  const feConfig = config({
85
147
  frontendLayers: {
@@ -0,0 +1,179 @@
1
+ // Enter and Escape in text entry wait for the IME, or a half-typed conversion is submitted. docs/ui.md.
2
+
3
+ import { optionsOf, schemaOf } from "../options.mjs";
4
+
5
+ const HANDLERS = new Set(["onKeyDown", "onKeyUp"]);
6
+ const ACTION_KEYS = new Set(["Enter", "Escape"]);
7
+ const EQUALITY = new Set(["===", "==", "!==", "!="]);
8
+ const FUNCTIONS = new Set(["ArrowFunctionExpression", "FunctionExpression", "FunctionDeclaration"]);
9
+ // An input of these types takes no typed text, so no IME composes into it.
10
+ const NON_TEXT_TYPES = new Set(["button", "checkbox", "color", "file", "hidden", "image", "radio", "range", "reset", "submit"]);
11
+ const IME_KEY_CODE = 229;
12
+
13
+ function tagName(name) {
14
+ if (name.type === "JSXIdentifier") return name.name;
15
+ if (name.type === "JSXMemberExpression") return `${tagName(name.object)}.${name.property.name}`;
16
+ return null;
17
+ }
18
+
19
+ /** undefined when absent, the literal when static, null when computed at runtime. */
20
+ function attributeValue(element, name) {
21
+ const attr = element.attributes.find((a) => a.type === "JSXAttribute" && a.name.name === name);
22
+ if (!attr) return undefined;
23
+ if (attr.value === null) return true;
24
+ if (attr.value.type === "Literal") return attr.value.value;
25
+ const expression = attr.value.expression;
26
+ return expression?.type === "Literal" ? expression.value : null;
27
+ }
28
+
29
+ function isTextEntry(element, components) {
30
+ const editable = attributeValue(element, "contentEditable");
31
+ if (editable !== undefined && editable !== false && editable !== "false") return true;
32
+ const name = tagName(element.name);
33
+ if (name === "textarea" || components.has(name)) return true;
34
+ if (name !== "input") return false;
35
+ const type = attributeValue(element, "type");
36
+ return typeof type !== "string" || !NON_TEXT_TYPES.has(type);
37
+ }
38
+
39
+ /** `useCallback(fn, deps)` and any wrapper like it: the handler is the first function argument. */
40
+ function unwrap(node) {
41
+ if (node?.type === "CallExpression") return node.arguments.find((arg) => FUNCTIONS.has(arg.type)) ?? null;
42
+ return node && FUNCTIONS.has(node.type) ? node : null;
43
+ }
44
+
45
+ function resolve(sourceCode, expression) {
46
+ if (expression.type !== "Identifier") return unwrap(expression);
47
+ for (let scope = sourceCode.getScope(expression); scope; scope = scope.upper) {
48
+ const variable = scope.set.get(expression.name);
49
+ if (!variable) continue;
50
+ // Branch on the definition kind: for a parameter, `def.node` is the enclosing function, not the handler.
51
+ const def = variable.defs[0];
52
+ if (def?.type === "FunctionName") return def.node;
53
+ return def?.type === "Variable" ? unwrap(def.node.init) : null;
54
+ }
55
+ return null;
56
+ }
57
+
58
+ function propertyName(node) {
59
+ return node.type === "MemberExpression" && !node.computed ? node.property.name : null;
60
+ }
61
+
62
+ function isKey(node) {
63
+ return propertyName(node) === "key" || (node.type === "Identifier" && node.name === "key");
64
+ }
65
+
66
+ function isActionKey(node) {
67
+ return node.type === "Literal" && ACTION_KEYS.has(node.value);
68
+ }
69
+
70
+ function isKeyCheck(node) {
71
+ if (node.type !== "BinaryExpression" || !EQUALITY.has(node.operator)) return false;
72
+ return (isKey(node.left) && isActionKey(node.right)) || (isKey(node.right) && isActionKey(node.left));
73
+ }
74
+
75
+ function isInlineGuard(node) {
76
+ if (propertyName(node) === "isComposing") return true;
77
+ if (node.type !== "BinaryExpression" || !EQUALITY.has(node.operator)) return false;
78
+ const sides = [node.left, node.right];
79
+ return sides.some((side) => propertyName(side) === "keyCode") && sides.some((side) => side.type === "Literal" && side.value === IME_KEY_CODE);
80
+ }
81
+
82
+ function walk(node, keys, visit) {
83
+ visit(node);
84
+ for (const key of keys[node.type] ?? []) {
85
+ const child = node[key];
86
+ for (const item of Array.isArray(child) ? child : [child]) {
87
+ if (item && typeof item.type === "string" && !FUNCTIONS.has(item.type)) walk(item, keys, visit);
88
+ }
89
+ }
90
+ }
91
+
92
+ function contains(outer, inner) {
93
+ return outer.range[0] <= inner.range[0] && inner.range[1] <= outer.range[1];
94
+ }
95
+
96
+ function exitsEarly(statement) {
97
+ if (statement.type === "ReturnStatement") return true;
98
+ return statement.type === "BlockStatement" && statement.body.at(-1)?.type === "ReturnStatement";
99
+ }
100
+
101
+ /** What one handler does with Enter and Escape, and what guards it. */
102
+ function survey(handler, keys, isGuard) {
103
+ const found = { checks: [], inline: [], guards: [] };
104
+ walk(handler.body, keys, (node) => {
105
+ if (isKeyCheck(node)) found.checks.push(node);
106
+ if (node.type === "SwitchStatement" && isKey(node.discriminant)) {
107
+ for (const branch of node.cases) if (branch.test && isActionKey(branch.test)) found.checks.push(branch.test);
108
+ }
109
+ if (isInlineGuard(node)) found.inline.push(node);
110
+ if (node.type === "IfStatement" && exitsEarly(node.consequent)) {
111
+ let guarded = false;
112
+ walk(node.test, keys, (inner) => (guarded ||= isGuard(inner)));
113
+ if (guarded) found.guards.push(node);
114
+ }
115
+ });
116
+ return found;
117
+ }
118
+
119
+ /** The first statement the branch runs when the check holds. */
120
+ function branchHead(check) {
121
+ let node = check;
122
+ while (node.parent && !FUNCTIONS.has(node.parent.type)) {
123
+ const parent = node.parent;
124
+ if (parent.type === "SwitchCase" && parent.test === node) return parent.consequent[0];
125
+ if (parent.type === "IfStatement" && parent.test === node) {
126
+ return parent.consequent.type === "BlockStatement" ? parent.consequent.body[0] : parent.consequent;
127
+ }
128
+ node = parent;
129
+ }
130
+ return undefined;
131
+ }
132
+
133
+ function isGuarded(check, guards) {
134
+ const head = branchHead(check);
135
+ return guards.some((guard) => guard === head || (guard.range[1] <= check.range[0] && contains(guard.parent, check)));
136
+ }
137
+
138
+ export default {
139
+ meta: {
140
+ type: "problem",
141
+ docs: { description: "Enter and Escape in text entry act only after an early return on the IME guard" },
142
+ schema: schemaOf({
143
+ components: { type: "array", items: { type: "string" } },
144
+ guards: { type: "array", items: { type: "string" } },
145
+ }),
146
+ messages: {
147
+ unguarded: "Enter and Escape in text entry must wait for the IME: return early on {{guard}} before this branch.",
148
+ inline: "An inline IME check is a second mechanism, and isComposing alone misses keyCode 229: call {{guard}}.",
149
+ },
150
+ },
151
+ create(context) {
152
+ const options = optionsOf(context);
153
+ const components = new Set(options.components ?? []);
154
+ const guards = new Set(options.guards ?? []);
155
+ const guard = guards.size > 0 ? [...guards].join(" or ") : "isComposing or keyCode 229";
156
+ const isGuard =
157
+ guards.size > 0
158
+ ? (node) => node.type === "CallExpression" && guards.has(node.callee.name ?? propertyName(node.callee))
159
+ : isInlineGuard;
160
+ const sourceCode = context.sourceCode;
161
+ const reported = new Set();
162
+ function report(node, messageId) {
163
+ if (reported.has(node)) return;
164
+ reported.add(node);
165
+ context.report({ node, messageId, data: { guard } });
166
+ }
167
+ return {
168
+ JSXAttribute(node) {
169
+ if (!HANDLERS.has(node.name.name) || node.value?.type !== "JSXExpressionContainer") return;
170
+ if (!isTextEntry(node.parent, components)) return;
171
+ const handler = resolve(sourceCode, node.value.expression);
172
+ if (!handler) return;
173
+ const found = survey(handler, sourceCode.visitorKeys, isGuard);
174
+ for (const check of found.checks) if (!isGuarded(check, found.guards)) report(check, "unguarded");
175
+ if (guards.size > 0) for (const check of found.inline) report(check, "inline");
176
+ },
177
+ };
178
+ },
179
+ };
@@ -0,0 +1,30 @@
1
+ // A query binds its values. sql.raw splices text into the statement unescaped. docs/architecture.md.
2
+
3
+ import { filenameOf, optionsOf, pathSuffix, schemaOf } from "../options.mjs";
4
+
5
+ function isRaw(node) {
6
+ if (node.object.type !== "Identifier" || node.object.name !== "sql") return false;
7
+ const property = node.property;
8
+ if (!node.computed) return property.type === "Identifier" && property.name === "raw";
9
+ return property.type === "Literal" && property.value === "raw";
10
+ }
11
+
12
+ export default {
13
+ meta: {
14
+ type: "problem",
15
+ docs: { description: "a query binds its values; sql.raw is refused outside a reviewed file" },
16
+ schema: schemaOf({ allow: { type: "array", items: { type: "string" } } }),
17
+ messages: {
18
+ raw: "sql.raw splices text into the statement unescaped: bind the value, or list this file in sqlRaw.allow after a review.",
19
+ },
20
+ },
21
+ create(context) {
22
+ const filename = filenameOf(context);
23
+ if ((optionsOf(context).allow ?? []).some((path) => pathSuffix(path).test(filename))) return {};
24
+ return {
25
+ MemberExpression(node) {
26
+ if (isRaw(node)) context.report({ node, messageId: "raw" });
27
+ },
28
+ };
29
+ },
30
+ };
@@ -0,0 +1,66 @@
1
+ // A number the registry owns has one home. Only the readers an entry names may hold it in code.
2
+
3
+ import { filenameOf, optionsOf, pathSuffix, schemaOf } from "../options.mjs";
4
+
5
+ const strings = { type: "array", items: { type: "string" } };
6
+
7
+ function isNumber(node) {
8
+ if (!node) return false;
9
+ if (node.type === "Literal") return typeof node.value === "number";
10
+ if (node.type === "UnaryExpression") return node.operator === "-" && isNumber(node.argument);
11
+ if (node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression") return isNumber(node.expression);
12
+ return false;
13
+ }
14
+
15
+ function keyName(key) {
16
+ if (key.type === "Identifier") return key.name;
17
+ return key.type === "Literal" && typeof key.value === "string" ? key.value : null;
18
+ }
19
+
20
+ export default {
21
+ meta: {
22
+ type: "problem",
23
+ docs: { description: "a number the registry owns is held only by the readers its entry names" },
24
+ schema: schemaOf({
25
+ entries: {
26
+ type: "array",
27
+ items: {
28
+ type: "object",
29
+ properties: { key: { type: "string" }, names: strings, readers: strings },
30
+ required: ["key", "names"],
31
+ additionalProperties: false,
32
+ },
33
+ },
34
+ }),
35
+ messages: {
36
+ restated: "'{{name}}' restates the registry entry '{{key}}': import the number from {{readers}}.",
37
+ unread: "'{{name}}' restates the registry entry '{{key}}', which names no reader: read the number from the registry.",
38
+ },
39
+ },
40
+ create(context) {
41
+ const filename = filenameOf(context);
42
+ const entries = (optionsOf(context).entries ?? [])
43
+ .map((entry) => ({ ...entry, readers: entry.readers ?? [] }))
44
+ .filter((entry) => !entry.readers.some((reader) => pathSuffix(reader).test(filename)))
45
+ .map((entry) => ({ ...entry, patterns: entry.names.map((name) => new RegExp(`^(?:${name})$`, "i")) }));
46
+ if (entries.length === 0) return {};
47
+ function check(node, name, value) {
48
+ if (!name || !isNumber(value)) return;
49
+ const entry = entries.find((candidate) => candidate.patterns.some((pattern) => pattern.test(name)));
50
+ if (!entry) return;
51
+ const data = { name, key: entry.key, readers: entry.readers.join(", ") };
52
+ context.report({ node, messageId: entry.readers.length > 0 ? "restated" : "unread", data });
53
+ }
54
+ return {
55
+ VariableDeclarator(node) {
56
+ if (node.id.type === "Identifier") check(node, node.id.name, node.init);
57
+ },
58
+ Property(node) {
59
+ if (!node.computed) check(node, keyName(node.key), node.value);
60
+ },
61
+ PropertyDefinition(node) {
62
+ if (!node.computed) check(node, keyName(node.key), node.value);
63
+ },
64
+ };
65
+ },
66
+ };
@@ -625,3 +625,154 @@ tester.run("name-the-pattern", rules["name-the-pattern"], {
625
625
  },
626
626
  ],
627
627
  });
628
+
629
+ const MIGRATE = "backend/src/infrastructure/db/migrate.ts";
630
+
631
+ console.log("→", "no-sql-raw");
632
+ tester.run("no-sql-raw", rules["no-sql-raw"], {
633
+ valid: [
634
+ { code: "await db.execute(sql`select 1 where id = ${id}`);", filename: "backend/src/features/pins/resource.ts" },
635
+ { code: "await db.execute(sql.raw(ddl));", filename: MIGRATE, options: [{ allow: [MIGRATE] }] },
636
+ { code: "await db.execute(sql.raw(ddl));", filename: "C:\\repo\\backend\\src\\infrastructure\\db\\migrate.ts", options: [{ allow: [MIGRATE] }] },
637
+ { code: "const text = other.raw(value);", filename: "backend/src/features/pins/resource.ts" },
638
+ ],
639
+ invalid: [
640
+ { code: "await db.execute(sql.raw(text));", filename: "backend/src/features/pins/resource.ts", errors: [{ messageId: "raw" }] },
641
+ { code: "const splice = sql.raw;", filename: "backend/src/features/pins/resource.ts", errors: [{ messageId: "raw" }] },
642
+ { code: 'sql["raw"](text);', filename: "backend/src/features/pins/resource.ts", errors: [{ messageId: "raw" }] },
643
+ {
644
+ code: "await db.execute(sql.raw(ddl));",
645
+ filename: "backend/src/features/pins/resource.ts",
646
+ options: [{ allow: [MIGRATE] }],
647
+ errors: [{ messageId: "raw" }],
648
+ },
649
+ ],
650
+ });
651
+
652
+ const jsx = new RuleTester({
653
+ languageOptions: { ecmaVersion: 2023, sourceType: "module", parserOptions: { ecmaFeatures: { jsx: true } } },
654
+ });
655
+ const GUARDED = [{ guards: ["isImeComposing"] }];
656
+ const unguarded = { messageId: "unguarded" };
657
+ const inline = { messageId: "inline" };
658
+
659
+ console.log("→", "ime-safe-key");
660
+ jsx.run("ime-safe-key", rules["ime-safe-key"], {
661
+ valid: [
662
+ {
663
+ code: '<textarea onKeyDown={(e) => { if (isImeComposing(e.nativeEvent)) return; if (e.key === "Enter") submit(); }} />;',
664
+ options: GUARDED,
665
+ },
666
+ { code: '<input onKeyDown={(e) => { if (e.nativeEvent.isComposing) return; if (e.key === "Enter") submit(); }} />;' },
667
+ { code: '<input onKeyDown={(e) => { if (e.keyCode === 229) return; if (e.key === "Escape") close(); }} />;' },
668
+ {
669
+ // A handler passed in as a prop is not resolvable here, so the component's own body is never judged as the handler.
670
+ code:
671
+ "function Field({ onKey, key }) {\n" +
672
+ ' if (key === "Enter") track();\n' +
673
+ " return <input onKeyDown={onKey} />;\n" +
674
+ "}",
675
+ options: GUARDED,
676
+ },
677
+ {
678
+ code: '<input onKeyDown={(e) => { if (e.key === "Enter") { if (isImeComposing(e.nativeEvent)) return; submit(); } }} />;',
679
+ options: GUARDED,
680
+ },
681
+ {
682
+ code:
683
+ 'const onKey = useCallback((e) => { if (isImeComposing(e.nativeEvent)) return; if (e.key === "Enter") send(); }, []);\n' +
684
+ "const field = <input onKeyDown={onKey} />;",
685
+ options: GUARDED,
686
+ },
687
+ // A row, a button or a list item reacts to Enter or Space; it is not text entry.
688
+ { code: '<div role="row" tabIndex={0} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") open(); }} />;' },
689
+ { code: '<li onKeyDown={(e) => { if (e.key === "Enter") open(); }} />;' },
690
+ { code: '<FolderRow onKeyDown={(e) => { if (e.key === "Enter") open(); }} />;', options: [{ components: ["Input"] }] },
691
+ { code: 'const onKey = (e) => { if (e.key === "Enter") open(); };\nconst row = <div onKeyDown={onKey} />;' },
692
+ { code: '<div contentEditable={false} onKeyDown={(e) => { if (e.key === "Enter") open(); }} />;' },
693
+ { code: '<input type="checkbox" onKeyDown={(e) => { if (e.key === "Enter") toggle(); }} />;' },
694
+ { code: '<input onKeyDown={(e) => { if (e.key === "Tab") next(); }} />;' },
695
+ ],
696
+ invalid: [
697
+ {
698
+ // The drawing-comment-dialog case: Enter submits a half-typed kana conversion.
699
+ code: '<textarea onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); submit(); } }} />;',
700
+ errors: [unguarded],
701
+ },
702
+ { code: '<input onKeyUp={(e) => { if (e.key === "Escape") cancel(); }} />;', errors: [unguarded] },
703
+ { code: '<div contentEditable onKeyDown={(e) => { if (e.key === "Enter") commit(); }} />;', errors: [unguarded] },
704
+ {
705
+ code: '<Input onKeyDown={(e) => { if (e.key === "Enter") commit(); }} />;',
706
+ options: [{ components: ["Input"] }],
707
+ errors: [unguarded],
708
+ },
709
+ {
710
+ // The drawing-grid-calibration case: a handler defined outside the JSX, with an inline check.
711
+ code:
712
+ 'const onKeyDown = (e) => { if (e.key === "Enter" && !e.nativeEvent.isComposing) confirm(); };\n' +
713
+ "const field = <Input onKeyDown={onKeyDown} />;",
714
+ options: [{ components: ["Input"], guards: ["isImeComposing"] }],
715
+ errors: [unguarded, inline],
716
+ },
717
+ {
718
+ code: 'function onKey(e) { if (e.key === "Escape") close(); }\nconst field = <textarea onKeyDown={onKey} />;',
719
+ errors: [unguarded],
720
+ },
721
+ {
722
+ code: '<input onKeyDown={(e) => { if (e.keyCode === 229) return; if (e.key === "Enter") send(); }} />;',
723
+ options: GUARDED,
724
+ errors: [inline, unguarded],
725
+ },
726
+ {
727
+ code: '<input onKeyDown={(e) => { if (e.nativeEvent.isComposing) return; if (e.key === "Enter") send(); }} />;',
728
+ options: GUARDED,
729
+ errors: [inline, unguarded],
730
+ },
731
+ { code: '<input onKeyDown={(e) => { switch (e.key) { case "Enter": send(); break; } }} />;', errors: [unguarded] },
732
+ {
733
+ code: '<input onKeyDown={(e) => { if (e.key === "Enter") send(); if (isImeComposing(e)) return; }} />;',
734
+ options: GUARDED,
735
+ errors: [unguarded],
736
+ },
737
+ {
738
+ // The guard must return early; a conjoined check is a second shape for one job.
739
+ code: '<input onKeyDown={(e) => { if (e.key === "Escape" && !isImeComposing(e.nativeEvent)) close(); }} />;',
740
+ options: GUARDED,
741
+ errors: [unguarded],
742
+ },
743
+ { code: '<input onKeyDown={({ key }) => { if (key === "Enter") send(); }} />;', errors: [unguarded] },
744
+ ],
745
+ });
746
+
747
+ const READER = "frontend/src/platform/gesture-thresholds.ts";
748
+ const HOLD = [{ entries: [{ key: "holdpress", names: ["HOLD_\\w*MS", "\\w*_HOLD_MS"], readers: [READER] }] }];
749
+
750
+ console.log("→", "registry-literal");
751
+ tester.run("registry-literal", rules["registry-literal"], {
752
+ valid: [
753
+ { code: "export const HOLD_DURATION_MS = 400;", filename: READER, options: HOLD },
754
+ { code: "export const HOLD_DURATION_MS = 400;", filename: "C:\\repo\\frontend\\src\\platform\\gesture-thresholds.ts", options: HOLD },
755
+ { code: "const SEARCH_SETTLE_MS = 250;", filename: "frontend/src/features/search/box.ts", options: HOLD },
756
+ { code: "const HOLD_DURATION_MS = registry.gates.holdpress.value;", filename: "frontend/src/features/pins/drag.ts", options: HOLD },
757
+ // A pattern matches the whole identifier: THRESHOLD_MS holds "HOLD_MS" but is not a hold.
758
+ { code: "const THRESHOLD_MS = 4;", filename: "frontend/src/features/pins/drag.ts", options: HOLD },
759
+ { code: "const HOLD_DURATION_MS = 400;", filename: "frontend/src/features/pins/drag.ts" },
760
+ ],
761
+ invalid: [
762
+ {
763
+ code: "const HOLD_DURATION_MS = 400;",
764
+ filename: "frontend/src/features/pins/drag.ts",
765
+ options: HOLD,
766
+ errors: [{ messageId: "restated", data: { name: "HOLD_DURATION_MS", key: "holdpress", readers: READER } }],
767
+ },
768
+ { code: "const NAME_HOLD_MS = 900;", filename: "frontend/src/features/pins/drag.ts", options: HOLD, errors: [{ messageId: "restated" }] },
769
+ { code: "const GESTURE = { HOLD_DURATION_MS: 400 };", filename: "frontend/src/features/pins/drag.ts", options: HOLD, errors: [{ messageId: "restated" }] },
770
+ { code: "class Grip { static HOLD_DURATION_MS = 400; }", filename: "frontend/src/features/pins/drag.ts", options: HOLD, errors: [{ messageId: "restated" }] },
771
+ {
772
+ code: "const PIN_DRAG_THRESHOLD_PX = 4;",
773
+ filename: "frontend/src/features/pins/drag.ts",
774
+ options: [{ entries: [{ key: "dragslop", names: ["\\w*DRAG\\w*_PX"], readers: [] }] }],
775
+ errors: [{ messageId: "unread", data: { name: "PIN_DRAG_THRESHOLD_PX", key: "dragslop" } }],
776
+ },
777
+ ],
778
+ });
@@ -0,0 +1,24 @@
1
+ // A registry entry's reader list stays true: each reader exists, and each one names the entry.
2
+
3
+ import { escape } from "../eslint/options.mjs";
4
+
5
+ /**
6
+ * @param {{key: string, readers: string[]}[]} entries registry entries, from readerEntries()
7
+ * @param {Map<string, string|null>} sources reader path to its text, null when the file is absent
8
+ */
9
+ export function checkRegistryReaders(entries, sources) {
10
+ const problems = [];
11
+ for (const { key, readers } of entries) {
12
+ // The key as a string or as the accessor's property: "holdpress" and gates.holdpress both hold it.
13
+ const named = new RegExp(`\\b${escape(key)}\\b`);
14
+ for (const reader of readers) {
15
+ const source = sources.get(reader) ?? null;
16
+ if (source === null) {
17
+ problems.push({ path: reader, rule: "missing-reader", detail: `registry entry '${key}' names this reader, and the file does not exist` });
18
+ } else if (!named.test(source)) {
19
+ problems.push({ path: reader, rule: "silent-reader", detail: `registry entry '${key}' names this reader, and the file never names '${key}'` });
20
+ }
21
+ }
22
+ }
23
+ return problems;
24
+ }
@@ -0,0 +1,35 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { checkRegistryReaders } from "./registry-readers.mjs";
4
+
5
+ const READER = "frontend/src/platform/gesture-thresholds.ts";
6
+ const entries = [{ key: "holdpress", names: ["HOLD_\\w*MS"], readers: [READER] }];
7
+
8
+ test("a reader that reads the entry through the registry accessor passes", () => {
9
+ const sources = new Map([[READER, "export const HOLD_PRESS_MS = registry.gates.holdpress.value;"]]);
10
+ assert.deepEqual(checkRegistryReaders(entries, sources), []);
11
+ });
12
+
13
+ test("a reader that names the entry key as a string passes", () => {
14
+ const sources = new Map([[READER, 'export const HOLD_PRESS_MS = threshold("holdpress");']]);
15
+ assert.deepEqual(checkRegistryReaders(entries, sources), []);
16
+ });
17
+
18
+ test("a missing reader fails the gate", () => {
19
+ const problems = checkRegistryReaders(entries, new Map([[READER, null]]));
20
+ assert.equal(problems.length, 1);
21
+ assert.equal(problems[0].rule, "missing-reader");
22
+ assert.equal(problems[0].path, READER);
23
+ assert.match(problems[0].detail, /holdpress/);
24
+ });
25
+
26
+ test("a reader that never names the entry key fails the gate", () => {
27
+ const sources = new Map([[READER, "export const HOLD_PRESS_MS = registry.gates.holdpressure.value;"]]);
28
+ const problems = checkRegistryReaders(entries, sources);
29
+ assert.equal(problems.length, 1);
30
+ assert.equal(problems[0].rule, "silent-reader");
31
+ });
32
+
33
+ test("an entry with no readers has nothing to check", () => {
34
+ assert.deepEqual(checkRegistryReaders([{ key: "dragslop", names: ["\\w*_PX"], readers: [] }], new Map()), []);
35
+ });
@@ -4,6 +4,7 @@
4
4
  "policy": {
5
5
  "loosening": "Raising a limit or lowering coverage needs the same review as a spec change: the diff on this file is the record. A per-file override belongs in the config that needs it, with a comment naming why, never here.",
6
6
  "match": "A threshold has no distinctive spelling the way a version number does, so each gate lists the phrases a page or a config would use when stating it. scripts/check.mjs reports a digit beside one of them as a literal. Add a phrase when a new wording appears; the phrases are the whole reason the literal check can exist.",
7
+ "readers": "An entry that code reads can carry `names`, regular expressions for the identifiers that would restate it, each matched against the whole identifier and case-insensitive, and `readers`, the paths that may hold its number. qc/registry-literal reports a matching literal anywhere else, and the registry-readers gate fails a reader that is missing or never names the entry.",
7
8
  "notThresholds": "A performance budget is not a quality gate. Latency, memory and render budgets live in docs/performance.md, because they are measured per surface rather than enforced repository-wide."
8
9
  },
9
10
  "gates": {