eslint-plugin-kerfjs 5.0.0-beta.131 → 5.0.0-beta.134

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/README.md CHANGED
@@ -13,7 +13,7 @@ This plugin sits alongside two other defense layers shipped by [`kerfjs`](https:
13
13
  | Opt-in dev-warns (`KERF_DEV_WARN_*`) | Hard Rules 4 (rebuilt listeners), 7 (untracked signals), 8 (narrow set) | Runtime |
14
14
  | **This plugin** | Hard Rules 2, 5, 6, 10, 12 — AST-shaped antipatterns; plus rename-safety / `raw()`-audit nudges and a project-hygiene check for the bundled AI-assistant configs | **Edit time** |
15
15
 
16
- The core syntax rules analyze the AST without TypeScript parser services. `ai-assistant-configs` reads the filesystem, and the optional UI rules also resolve catalog and profile artifacts. Consumers configure their own parser; no `@typescript-eslint/parser` _service_ is required.
16
+ The core syntax rules analyze the AST without TypeScript parser services. `ai-assistant-configs` reads the filesystem, and the optional UI rules also resolve catalog and profile artifacts. Consumers configure their own parser. The optional `prefer-signal-leaf` suggestion uses an existing TypeScript parser service.
17
17
 
18
18
  ## Install
19
19
 
@@ -77,7 +77,7 @@ settings: {
77
77
  }
78
78
  ```
79
79
 
80
- For deterministic generated configs, the same settings accept parsed `catalog`, `selectionCatalog`, and `profile` objects. File-based precedence is package defaults, then workspace profile, then root-to-leaf directory profiles. The rules load `application-ui-profile-sync.cjs` from the installed `@kerfjs/ui` package by default because ESLint rule creation is synchronous; `profileContractPath` is only needed when artifacts are vendored, and then its directory must also hold `application-ui-diagnostic-ids-v1.json` and `component-class-owners.cjs` (the class-to-component rule `KUI-L103` shares with `@kerfjs/ui`'s generated component pages) from the same `@kerfjs/ui` release. Every raw layer is schema- and catalog-reference-validated before merge, so a child cannot hide malformed or stale parent policy. Exceptions use exact `KUI-L*` diagnostic ids and repository-relative file or directory targets.
80
+ For deterministic generated configs, the same settings accept parsed `catalog`, `selectionCatalog`, and `profile` objects. File-based precedence is package defaults, then workspace profile, then root-to-leaf directory profiles. The rules load `application-ui-profile-sync.cjs` from the installed `@kerfjs/ui` package by default because ESLint rule creation is synchronous; `profileContractPath` is only needed when artifacts are vendored, and then its directory must also hold `application-ui-diagnostic-ids-v1.json` and `choice-wiring-mode.cjs` plus `component-class-owners.cjs` (the class-to-component rule `KUI-L103` shares with `@kerfjs/ui`'s generated component pages) from the same `@kerfjs/ui` release. Every raw layer is schema- and catalog-reference-validated before merge, so a child cannot hide malformed or stale parent policy. Exceptions use exact `KUI-L*` diagnostic ids and repository-relative file or directory targets.
81
81
 
82
82
  When linting a nested workspace package, set `workspaceRoot` to the repository root. Installed `@kerfjs/ui` assets still resolve from ESLint's package `cwd`, while profile discovery and exception targets use the workspace root.
83
83
 
@@ -118,10 +118,10 @@ Use flat config (`eslint.config.js`), shown above. The `legacy-recommended` expo
118
118
  | [`require-delegate-disposer`](docs/rules/require-delegate-disposer.md) | 5 — capture `delegate()` disposers when scope < page | `warn` |
119
119
  | [`no-nested-mount`](docs/rules/no-nested-mount.md) | 6 — one `mount()` per root | `error` |
120
120
  | [`prefer-module-jsx-augmentation`](docs/rules/prefer-module-jsx-augmentation.md) | 12 — augment `kerfjs/jsx-runtime`, not global | `error` |
121
+ | [`prefer-signal-leaf`](docs/rules/prefer-signal-leaf.md) | — (typed editor suggestion for a mounted DOM leaf) | off |
121
122
  | [`prefer-attr-selector`](docs/rules/prefer-attr-selector.md) | — (rename-safety nudge for `delegate()` selectors) | `warn` |
122
123
  | [`no-raw-with-dynamic-arg`](docs/rules/no-raw-with-dynamic-arg.md) | — (XSS audit trail) | `warn` |
123
124
  | [`ai-assistant-configs`](docs/rules/ai-assistant-configs.md) | — (project hygiene) | `warn` |
124
- | [`no-generated-view-edits`](docs/rules/no-generated-view-edits.md) | — (generated Kerf UI view modules are read-only) | `error` |
125
125
  | [`ui-public-boundaries`](docs/rules/ui-public-boundaries.md) | — (cataloged classes/tokens; component anatomy on app elements) | `error` |
126
126
  | [`ui-component-ownership`](docs/rules/ui-component-ownership.md) | — (configure components, never override them) | `error` |
127
127
  | [`ui-composition`](docs/rules/ui-composition.md) | — (cataloged parents and zones) | `error` |
@@ -0,0 +1,43 @@
1
+ # `kerfjs/prefer-signal-leaf`
2
+
3
+ An editor suggestion can move a dependency from a Kerf mount render to one DOM text node or attribute. If a signal is the render's only dependency, subsequent writes update the bound node without running the render again.
4
+
5
+ ```tsx
6
+ import { mount, signal } from "kerfjs";
7
+
8
+ const label = signal("Ready");
9
+ mount(root, () => <span>{label.value}</span>);
10
+ // Editor suggestion: <span>{label}</span>
11
+ ```
12
+
13
+ ## Enabling the rule
14
+
15
+ Add a flat-config entry to the project's existing ESLint configuration. Install `@typescript-eslint/parser` and its supported TypeScript peer. The rule uses the TypeScript program supplied by the parser. All Kerf presets leave it off.
16
+
17
+ ```js
18
+ import kerfjs from "eslint-plugin-kerfjs";
19
+ import parser from "@typescript-eslint/parser";
20
+
21
+ export default [
22
+ {
23
+ files: ["**/*.tsx"],
24
+ languageOptions: { parser, parserOptions: { projectService: true } },
25
+ plugins: { kerfjs },
26
+ rules: { "kerfjs/prefer-signal-leaf": "warn" },
27
+ },
28
+ ];
29
+ ```
30
+
31
+ The file's TypeScript project needs strict null checks, automatic JSX (`react-jsx` or `react-jsxdev`), and `jsxImportSource: "kerfjs"`. An untyped file receives no suggestions. Files with JSX pragmas are skipped.
32
+
33
+ ## Which reads qualify?
34
+
35
+ - A direct text child containing just `name.value` with a string or number payload, or `title={name.value}` with a string payload.
36
+ - `name` is a stable `const` outside the render, initialized by a named `signal` or `computed` import from `kerfjs`. Aliases work. A similarly shaped object, a getter, or a nullable or erased signal type gives insufficient evidence.
37
+ - The element is returned directly by an inline callback passed to the imported Kerf `mount`. Its JSX ancestors are fragments or ordinary `div`, `span`, `small`, `em`, or `strong` elements. The narrow list avoids raw-text, form, SVG, parser-sensitive and custom-element contexts. Spreads, content editing and explicit morph ownership can change who controls a node, so those hosts and their descendants are skipped.
38
+
39
+ Reads used for branching, formatting, custom component props, and list rows need a separate decision about who should subscribe. A signal carrying `SafeHtml` can render markup when read in JSX, whereas a direct text binding would stringify its value.
40
+
41
+ ## Reviewing the suggestion
42
+
43
+ Review work elsewhere in the mount that relies on a rerender, including effects of calling other functions. Apply the suggestion when the text or title should update independently. Code that observes child-node boundaries, parser normalization of control characters, or mount invocation counts can observe the change. ESLint offers the edit in the editor and leaves the file alone under `--fix`. The runtime `valueOnlyRerender` warning observes actual renders and can surface patterns outside this rule's static checks.
@@ -2,7 +2,7 @@
2
2
 
3
3
  Enforces composition facts published by the versioned UI catalog. `KUI-L201` reports a catalog component under a known, disallowed direct parent. `KUI-L202` reports a statically visible zone child—including an intrinsic or unknown JSX element—that is not one of the zone's cataloged `accepts` entries. `KUI-L203` reports a statically provable zone cardinality violation. `KUI-L204` reports a direct child that brings its own content-item inset into a parent configured to expect inset-free content. `KUI-L205` reports a control or link written inside a component whose root is one. A zone participates only when it declares an explicit `jsx.prop` binding, including `children`; the rule never guesses that a zone id is a JSX prop. Toolbar, Pane, TabBar, TabBarItem, feedback, search, and layout validation is therefore catalog-driven rather than duplicated in rule-local component cases.
4
4
 
5
- The parent check is intentionally conservative about the child: it runs only for a child that resolves to a cataloged entry (or a declared wrapper's roots) whose parents are `listed`. Its direct JSX parent may be any element the rule can see: a cataloged component, a declared wrapper (which counts as each of its roots), an intrinsic element such as `<div>`, or an unresolved component, and any parent that is not a listed parent reports `KUI-L201`. Bound zone checks understand aliases, namespace imports, fragments, arrays, and conditional/logical branches, but expressions whose content cannot be resolved statically remain runtime and accessibility work. Accepted concepts that do not identify a catalog entry remain machine-readable guidance while the rule enforces their statically provable cardinality only. No autofix is offered because wrapping or moving UI changes structure and behavior.
5
+ The parent check is intentionally conservative about the child: it runs only for a child that resolves to a cataloged entry (or a declared wrapper's roots) whose parents are `listed`. Its direct JSX parent may be any element the rule can see: a cataloged component, a declared wrapper (which counts as each of its roots), an intrinsic element such as `<div>`, or an unresolved component, and any parent that is not a listed parent reports `KUI-L201`. A listed parent may also name one prop of a component (`@kerfjs/ui:surface-scaffold#headerActions`): the child is accepted there only when it is written inside that prop, not in the component's body or another prop. Bound zone checks understand aliases, namespace imports, fragments, arrays, and conditional/logical branches, but expressions whose content cannot be resolved statically remain runtime and accessibility work. Accepted concepts that do not identify a catalog entry remain machine-readable guidance while the rule enforces their statically provable cardinality only. No autofix is offered because wrapping or moving UI changes structure and behavior.
6
6
  Toolbar zones accept `KerfUiContent`, so the zone rule allows direct JSX
7
7
  controls and custom components there. Their own parent contracts still apply,
8
8
  including when a direct child is supplied through a zone prop.
@@ -68,8 +68,7 @@ import { Badge, Button, ListItem } from '@kerfjs/ui';
68
68
  A `whenProps` rule counts a prop as written when the attribute is present,
69
69
  whatever expression supplies it, unless its value is a literal `false` or
70
70
  `null`. A component defined elsewhere, or a prop supplied through a spread, is
71
- not visible to the rule. `validateView` reports the same placement in a view
72
- document as `KUI-V014`, from the same rules.
71
+ not visible to the rule.
73
72
 
74
73
  ## Application and third-party wrappers
75
74
 
package/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import aiAssistantConfigs from './lib/rules/ai-assistant-configs.js';
2
- import noGeneratedViewEdits from './lib/rules/no-generated-view-edits.js';
3
2
  import noInlineJsxEventHandlers from './lib/rules/no-inline-jsx-event-handlers.js';
4
3
  import noNestedMount from './lib/rules/no-nested-mount.js';
5
4
  import noRawWithDynamicArg from './lib/rules/no-raw-with-dynamic-arg.js';
6
5
  import preferAttrSelector from './lib/rules/prefer-attr-selector.js';
7
6
  import preferModuleJsxAugmentation from './lib/rules/prefer-module-jsx-augmentation.js';
7
+ import preferSignalLeaf from './lib/rules/prefer-signal-leaf.js';
8
8
  import requireDataKeyInEach from './lib/rules/require-data-key-in-each.js';
9
9
  import requireDelegateDisposer from './lib/rules/require-delegate-disposer.js';
10
10
  import uiComponentOwnership from './lib/rules/ui-component-ownership.js';
@@ -16,16 +16,16 @@ import uiPublicBoundaries from './lib/rules/ui-public-boundaries.js';
16
16
  import uiWiring from './lib/rules/ui-wiring.js';
17
17
 
18
18
  const plugin = {
19
- meta: { name: 'eslint-plugin-kerfjs', version: '5.0.0-beta.131' },
19
+ meta: { name: 'eslint-plugin-kerfjs', version: '5.0.0-beta.134' },
20
20
  rules: {
21
21
  'no-inline-jsx-event-handlers': noInlineJsxEventHandlers,
22
- 'no-generated-view-edits': noGeneratedViewEdits,
23
22
  'no-raw-with-dynamic-arg': noRawWithDynamicArg,
24
23
  'require-data-key-in-each': requireDataKeyInEach,
25
24
  'require-delegate-disposer': requireDelegateDisposer,
26
25
  'no-nested-mount': noNestedMount,
27
26
  'prefer-module-jsx-augmentation': preferModuleJsxAugmentation,
28
27
  'prefer-attr-selector': preferAttrSelector,
28
+ 'prefer-signal-leaf': preferSignalLeaf,
29
29
  'ai-assistant-configs': aiAssistantConfigs,
30
30
  'ui-component-ownership': uiComponentOwnership,
31
31
  'ui-composition': uiComposition,
@@ -46,9 +46,6 @@ const plugin = {
46
46
  // would block too many legitimate uses without eslint-disable comments.
47
47
  // `prefer-attr-selector` is `warn` — the literal-selector form is still
48
48
  // correct at runtime; this rule nudges toward the rename-safe pattern.
49
- // `no-generated-view-edits` is `error` — it only inspects files carrying a
50
- // kerf-ui-view header (or sitting beside a `.kui.json`), and an edited
51
- // generated module is always a defect: regeneration silently discards it.
52
49
  // `require-delegate-disposer` is `warn` — the discarded-disposer form is
53
50
  // still correct at runtime for page-lifetime roots, and downstream code
54
51
  // that's been around since before the rule shipped needs a deprecation
@@ -62,7 +59,6 @@ const recommendedRules = {
62
59
  'kerfjs/prefer-module-jsx-augmentation': 'error',
63
60
  'kerfjs/prefer-attr-selector': 'warn',
64
61
  'kerfjs/ai-assistant-configs': 'warn',
65
- 'kerfjs/no-generated-view-edits': 'error',
66
62
  };
67
63
 
68
64
  // Flat config (ESLint v9+) — consumers add this object to their config array.
@@ -0,0 +1,206 @@
1
+ // Only hosts that parse in ordinary HTML flow and have no form/editing state.
2
+ const hosts = new Set(['div', 'span', 'small', 'em', 'strong']);
3
+ const ownershipAttributes = new Set([
4
+ 'contenteditable',
5
+ 'data-morph-skip',
6
+ 'data-morph-skip-children',
7
+ 'data-morph-preserve',
8
+ 'is',
9
+ 'xmlns',
10
+ 'children',
11
+ 'data-kfb',
12
+ 'data-kfbrow',
13
+ ]);
14
+
15
+ function definition(source, identifier) {
16
+ for (let scope = source.getScope(identifier); scope; scope = scope.upper) {
17
+ const variable = scope.set.get(identifier.name);
18
+ if (variable) return variable.defs.length === 1 ? variable.defs[0] : null;
19
+ }
20
+ return null;
21
+ }
22
+
23
+ function importedName(source, node) {
24
+ if (node.type !== 'Identifier') return null;
25
+ const def = definition(source, node);
26
+ if (
27
+ def?.type !== 'ImportBinding' ||
28
+ def.parent.source.value !== 'kerfjs' ||
29
+ def.node.type !== 'ImportSpecifier' ||
30
+ def.node.importKind === 'type' ||
31
+ def.parent.importKind === 'type'
32
+ )
33
+ return null;
34
+ return def.node.imported.name;
35
+ }
36
+
37
+ function ordinaryHost(element) {
38
+ const opening = element.openingElement;
39
+ if (opening.name.type !== 'JSXIdentifier' || !hosts.has(opening.name.name))
40
+ return false;
41
+ const seen = new Set();
42
+ for (const attribute of opening.attributes) {
43
+ if (
44
+ attribute.type !== 'JSXAttribute' ||
45
+ attribute.name.type !== 'JSXIdentifier'
46
+ )
47
+ return false;
48
+ const name = attribute.name.name.toLowerCase();
49
+ if (ownershipAttributes.has(name) || seen.has(name)) return false;
50
+ seen.add(name);
51
+ }
52
+ return true;
53
+ }
54
+
55
+ // Follow only direct JSX children to the inline callback return. A wrapper
56
+ // component, slot, helper call, or nested callback can change hole ownership.
57
+ function mountCallback(element, source) {
58
+ let node = element;
59
+ while (node.type === 'JSXElement' || node.type === 'JSXFragment') {
60
+ if (node.type === 'JSXElement' && !ordinaryHost(node)) return null;
61
+ node = node.parent;
62
+ }
63
+ if (node.type === 'ReturnStatement' && node.parent.type === 'BlockStatement')
64
+ node = node.parent.parent;
65
+ if (
66
+ node.type !== 'ArrowFunctionExpression' &&
67
+ node.type !== 'FunctionExpression'
68
+ )
69
+ return null;
70
+ const call = node.parent;
71
+ return call.type === 'CallExpression' &&
72
+ call.arguments[1] === node &&
73
+ importedName(source, call.callee) === 'mount'
74
+ ? node
75
+ : null;
76
+ }
77
+
78
+ function isScalar(checker, type, allowNumber) {
79
+ if (type.isUnion())
80
+ return type.types.every((member) => isScalar(checker, member, allowNumber));
81
+ const base = checker.getBaseTypeOfLiteralType(type);
82
+ return (
83
+ base === checker.getStringType() ||
84
+ (allowNumber && base === checker.getNumberType())
85
+ );
86
+ }
87
+
88
+ export default {
89
+ meta: {
90
+ type: 'suggestion',
91
+ docs: {
92
+ description:
93
+ 'Suggest binding a stable Kerf signal in a mounted scalar JSX leaf.',
94
+ },
95
+ schema: [],
96
+ hasSuggestions: true,
97
+ messages: {
98
+ leaf: 'This value read subscribes the mount render. Binding the signal updates just this hole; check whether other render work relies on those rerenders.',
99
+ bind: 'Pass the signal itself to the native JSX hole.',
100
+ },
101
+ },
102
+ create(context) {
103
+ const source = context.sourceCode;
104
+ const services = source.parserServices;
105
+ const program = services?.program;
106
+ if (!program || !services.esTreeNodeToTSNodeMap) return {};
107
+ const opts = program.getCompilerOptions();
108
+ // TypeScript JsxEmit.ReactJSX (4) and ReactJSXDev (5). Consume the parser's
109
+ // Program without loading TypeScript as a dependency in untyped consumers.
110
+ if (
111
+ (opts.jsx !== 4 && opts.jsx !== 5) ||
112
+ opts.jsxImportSource !== 'kerfjs' ||
113
+ !(opts.strictNullChecks ?? opts.strict)
114
+ )
115
+ return {};
116
+ if (
117
+ source
118
+ .getAllComments()
119
+ .some((comment) =>
120
+ /@jsx(?:ImportSource|Runtime|Frag)?\b/.test(comment.value),
121
+ )
122
+ )
123
+ return {};
124
+
125
+ return {
126
+ JSXExpressionContainer(container) {
127
+ const member = container.expression;
128
+ if (
129
+ member.type !== 'MemberExpression' ||
130
+ member.optional ||
131
+ member.computed ||
132
+ member.object.type !== 'Identifier' ||
133
+ member.property.name !== 'value' ||
134
+ source.getCommentsInside(member).length
135
+ )
136
+ return;
137
+ const parent = container.parent;
138
+ const text = parent.type === 'JSXElement';
139
+ if (
140
+ !text &&
141
+ !(parent.type === 'JSXAttribute' && parent.name.name === 'title')
142
+ )
143
+ return;
144
+ const owner = mountCallback(
145
+ text ? parent : parent.parent.parent,
146
+ source,
147
+ );
148
+ if (!owner) return;
149
+
150
+ const def = definition(source, member.object);
151
+ if (
152
+ def?.type !== 'Variable' ||
153
+ def.parent.kind !== 'const' ||
154
+ def.node.id.type !== 'Identifier' ||
155
+ (def.node.range[0] >= owner.range[0] &&
156
+ def.node.range[1] <= owner.range[1])
157
+ )
158
+ return;
159
+ const init = def.node.init;
160
+ if (
161
+ init?.type !== 'CallExpression' ||
162
+ !['signal', 'computed'].includes(importedName(source, init.callee))
163
+ )
164
+ return;
165
+ const checker = program.getTypeChecker();
166
+ const tsNode = (node) => services.esTreeNodeToTSNodeMap.get(node);
167
+ const signature = checker.getResolvedSignature(tsNode(init));
168
+ const annotation = def.node.id.typeAnnotation;
169
+ const receiver = annotation
170
+ ? checker.getTypeFromTypeNode(tsNode(annotation.typeAnnotation))
171
+ : checker.getTypeAtLocation(tsNode(member.object));
172
+ const value = checker.getPropertyOfType(receiver, 'value');
173
+ if (
174
+ !signature ||
175
+ !value ||
176
+ !isScalar(
177
+ checker,
178
+ checker.getTypeOfSymbolAtLocation(value, tsNode(init)),
179
+ text,
180
+ )
181
+ )
182
+ return;
183
+ // An annotation such as { value: string } loses the signal type even
184
+ // though the initializer was a real signal. Its proposed JSX must typecheck.
185
+ if (
186
+ !checker.isTypeAssignableTo(
187
+ receiver,
188
+ checker.getReturnTypeOfSignature(signature),
189
+ )
190
+ )
191
+ return;
192
+ context.report({
193
+ node: member,
194
+ messageId: 'leaf',
195
+ suggest: [
196
+ {
197
+ messageId: 'bind',
198
+ fix: (fixer) =>
199
+ fixer.replaceText(member, source.getText(member.object)),
200
+ },
201
+ ],
202
+ });
203
+ },
204
+ };
205
+ },
206
+ };
@@ -112,6 +112,8 @@ function zoneShape(node, registry, contract) {
112
112
  return { min: 0, max: Number.POSITIVE_INFINITY, items: [] };
113
113
  }
114
114
 
115
+ // The element that directly contains `node`, and the prop it arrives through
116
+ // when it is written inside an attribute (`headerActions={<Group />}`).
115
117
  function directParentKey(node, registry, contract) {
116
118
  let parent = node.parent?.parent;
117
119
  while (
@@ -119,12 +121,23 @@ function directParentKey(node, registry, contract) {
119
121
  ['JSXExpressionContainer', 'JSXFragment'].includes(parent.type)
120
122
  )
121
123
  parent = parent.parent;
122
- if (parent?.type === 'JSXAttribute') parent = parent.parent?.parent;
124
+ let prop;
125
+ if (parent?.type === 'JSXAttribute') {
126
+ prop = parent.name.name;
127
+ parent = parent.parent?.parent;
128
+ }
123
129
  return parent?.type === 'JSXElement'
124
- ? { key: jsxKey(parent.openingElement.name, registry, contract) }
130
+ ? { key: jsxKey(parent.openingElement.name, registry, contract), prop }
125
131
  : undefined;
126
132
  }
127
133
 
134
+ // A listed parent names a catalog key, or a key and one prop
135
+ // (`@kerfjs/ui:surface-scaffold#headerActions`) that accepts the child only
136
+ // through that prop (KF-SMTCPZ).
137
+ const acceptsParent = (entries, root, prop) =>
138
+ entries.includes(root) ||
139
+ (prop !== undefined && entries.includes(`${root}#${prop}`));
140
+
128
141
  // A prop's statically written value: `{ known: true, value }`, where a bare
129
142
  // boolean prop is `true` and an absent one is `undefined`, or
130
143
  // `{ known: false }` when a spread or an expression could supply it.
@@ -181,8 +194,8 @@ const rootsOf = (key, contract) =>
181
194
  contract.entries.get(key)?.rendersAs ?? [key];
182
195
 
183
196
  // Whether an element renders a native control or link as its root (`root`)
184
- // or inside it (`contains`), from its entry's `content` rules (KF-VTFKX8, the
185
- // JSX side of validateView's KUI-V014). An export with rules of its own uses
197
+ // or inside it (`contains`), from its entry's `content` rules (KF-VTFKX8). An
198
+ // export with rules of its own uses
186
199
  // them; a `whenProps` rule needs one of its props written, and a literal
187
200
  // `false` or `null` does not count.
188
201
  function interactiveOf(openingElement, registry, contract) {
@@ -331,7 +344,7 @@ export default {
331
344
  const violation = constrained.find(
332
345
  ({ entry: placedEntry }) =>
333
346
  !rootsOf(parent.key, contract).every((root) =>
334
- placedEntry.parents.entries.includes(root),
347
+ acceptsParent(placedEntry.parents.entries, root, parent.prop),
335
348
  ),
336
349
  );
337
350
  if (violation)
@@ -58,54 +58,21 @@ function entryModules(entryFile, currentFile, currentText) {
58
58
  return modules;
59
59
  }
60
60
 
61
- // Only the listbox mode needs wireChoiceChips. Static radio and toggle groups
62
- // use native inputs; an expression whose value is unknown still needs wiring.
63
- function choiceChipsNeedsWiring(attributes) {
64
- const multiple = attributes.find(
65
- (attribute) => attribute.name?.name === 'multiple',
66
- );
67
- if (!multiple) return false;
68
- if (!multiple.value) return true;
69
- if (multiple.value.type === 'Literal')
70
- return multiple.value.value !== 'toggle';
71
- const expression = multiple.value.expression;
72
- if (expression?.type === 'Literal')
73
- return expression.value !== 'toggle' && expression.value !== false;
74
- return true;
75
- }
76
-
77
- function sourceChoiceChipsNeedsWiring(source, name) {
78
- const opening = new RegExp(`<${name}(?=[\\s/>])`, 'g');
79
- for (const match of source.matchAll(opening)) {
80
- let braces = 0;
81
- let quote;
82
- let end = match.index + match[0].length;
83
- for (; end < source.length; end++) {
84
- const char = source[end];
85
- if (quote) {
86
- if (char === '\\') end++;
87
- else if (char === quote) quote = undefined;
88
- } else if (char === '"' || char === "'" || char === '`') quote = char;
89
- else if (char === '{') braces++;
90
- else if (char === '}') braces--;
91
- else if (char === '>' && braces === 0) break;
92
- }
93
- if (end === source.length) continue;
94
- const attributes = source.slice(match.index + match[0].length, end);
95
- const multiple = attributes.match(
96
- /(?:^|\s)multiple(?:\s*=\s*(?:\{\s*([^}]*)\s*\}|(["'])(.*?)\2))?(?=\s|\/|$)/,
97
- );
98
- if (!multiple) continue;
99
- if (
100
- multiple[3] === 'toggle' ||
101
- multiple[1]?.trim() === "'toggle'" ||
102
- multiple[1]?.trim() === '"toggle"' ||
103
- multiple[1]?.trim() === 'false'
104
- )
105
- continue;
106
- return true;
107
- }
108
- return false;
61
+ function literalAttributes(attributes) {
62
+ return attributes.map((attribute) => {
63
+ if (attribute.type === 'JSXSpreadAttribute') return ['...', null];
64
+ const value = attribute.value;
65
+ const expression =
66
+ value?.type === 'JSXExpressionContainer' ? value.expression : value;
67
+ return [
68
+ attribute.name.name,
69
+ value == null
70
+ ? true
71
+ : expression?.type === 'Literal'
72
+ ? expression.value
73
+ : null,
74
+ ];
75
+ });
109
76
  }
110
77
 
111
78
  // The entry graph is read from disk because ESLint visits one source file at a
@@ -138,7 +105,7 @@ function moduleUses(source, file, contract) {
138
105
  key &&
139
106
  new RegExp(`<${local}(?=[\\s/>])`).test(source) &&
140
107
  (key !== '@kerfjs/ui:choice-chips' ||
141
- sourceChoiceChipsNeedsWiring(source, local))
108
+ contract.choiceWiring.choiceUses(source, local))
142
109
  )
143
110
  uses.add(key);
144
111
  }
@@ -154,7 +121,7 @@ function moduleUses(source, file, contract) {
154
121
  key &&
155
122
  new RegExp(`<${namespace}\\.${name}(?=[\\s/>])`).test(source) &&
156
123
  (key !== '@kerfjs/ui:choice-chips' ||
157
- sourceChoiceChipsNeedsWiring(source, `${namespace}\\.${name}`))
124
+ contract.choiceWiring.choiceUses(source, `${namespace}.${name}`))
158
125
  )
159
126
  uses.add(key);
160
127
  }
@@ -314,7 +281,8 @@ export default {
314
281
  key &&
315
282
  !used.has(key) &&
316
283
  (key !== '@kerfjs/ui:choice-chips' ||
317
- choiceChipsNeedsWiring(node.attributes))
284
+ contract.choiceWiring.choiceMode(literalAttributes(node.attributes))
285
+ .required !== false)
318
286
  )
319
287
  used.set(key, node.name);
320
288
  },
@@ -385,6 +385,9 @@ export function loadUiContract(context) {
385
385
  publicTokens: new Set(
386
386
  catalog.entries.flatMap((entry) => entry.boundaries.publicTokens),
387
387
  ),
388
+ choiceWiring: loadCommonJs(
389
+ resolve(dirname(profileContractPath), 'choice-wiring-mode.cjs'),
390
+ ),
388
391
  error: undefined,
389
392
  };
390
393
  cache.set(key, { stamps, value });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-kerfjs",
3
- "version": "5.0.0-beta.131",
3
+ "version": "5.0.0-beta.134",
4
4
  "description": "ESLint rules that enforce kerf's hard rules — catches AI-shaped bugs at edit time.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1,42 +0,0 @@
1
- # `kerfjs/no-generated-view-edits`
2
-
3
- Disallow hand edits to generated Kerf UI view modules (`*.view.ts`, `*.view.js`, `*.view.d.ts`).
4
-
5
- A Kerf UI view document (`*.kui.json`) is the source of truth for a screen's composition. `kerf-ui-view generate` turns it into a read-only module that your application imports. You put state, handlers, slots, and wiring in **your own** files; editing the generated module would be lost on the next regeneration and would hide the contract changes the TypeScript compiler is meant to report.
6
-
7
- The generator records a digest of the module body in its header. This rule recomputes it, so it needs no access to the document:
8
-
9
- - **`edited`**: the body no longer matches the header's body digest, or the
10
- recorded `kui-contract` line no longer matches the contract digest.
11
- - **`header`**: the `kui-view` / `kui-contract` header lines are damaged.
12
- - **`missing`**: a `*.view.ts` sits beside a `.kui.json` document but is not a generated module.
13
-
14
- Line-ending conversion (CRLF checkouts) is ignored. A `*.view.ts` with no document beside it is not checked, so unrelated files that happen to use the suffix stay unaffected.
15
-
16
- ## ❌ Incorrect
17
-
18
- ```ts
19
- // inbox.view.ts — GENERATED by kerf-ui-view from inbox.kui.json — do not edit.
20
- // …
21
- export function renderInbox(inputs: InboxInputs, slots: InboxSlots): SafeHtml {
22
- return Pane({ background: myOverride /* ← reported: hand edit */ });
23
- }
24
- ```
25
-
26
- ## ✅ Correct
27
-
28
- ```ts
29
- // inbox.ts — application-owned
30
- import { renderInbox, wireInbox } from './inbox.view.js';
31
-
32
- mount(root, () =>
33
- renderInbox({ title: 'Inbox', items: items.value }, { detail }),
34
- );
35
- wireInbox(root, { compose: openComposer, 'open-item': ({ key }) => select(key) });
36
- ```
37
-
38
- To change the layout, edit `inbox.kui.json` (in the editor or by hand) and run `kerf-ui-view generate`. To make a value configurable, promote the prop to a document param; the generated module then exposes it as an input.
39
-
40
- Generated modules are formatted by the generator, so add `**/*.view.ts` (and `.view.js` / `.view.d.ts`) to `.prettierignore` as well.
41
-
42
- See [`docs/26-ui-editor.md`](../../../docs/26-ui-editor.md) in the kerf repository.
@@ -1,81 +0,0 @@
1
- import { existsSync } from 'node:fs';
2
-
3
- // Generated Kerf UI view modules (docs/26-ui-editor.md §5.2) are read-only:
4
- // application code integrates through their exports and never edits them.
5
- // The generator records a digest of the module body in its header; this rule
6
- // recomputes it, so a hand edit (or a half-applied regeneration) is reported
7
- // without access to the source document.
8
-
9
- const STAMP =
10
- /^\/\/ kui-view: \d+ contract (kui1:[0-9a-f]{16}) source kui1:[0-9a-f]{16} body (kui1:[0-9a-f]{16})$/;
11
- const GENERATED = '// GENERATED by kerf-ui-view';
12
- const HEADER_LINES = 3;
13
- const VIEW_FILE = /\.view\.(?:d\.ts|ts|js)$/;
14
- const MASK = 0xffffffffffffffffn;
15
-
16
- /**
17
- * `kui1:` + 16 hex digits of the 64-bit FNV-1a hash of `text`'s UTF-8 bytes —
18
- * the same digest `@kerfjs/ui/view`'s `viewDigest` computes (pinned by a
19
- * parity test), duplicated so the plugin needs no runtime dependency on it.
20
- */
21
- export function viewDigest(text) {
22
- let hash = 0xcbf29ce484222325n;
23
- for (const byte of new TextEncoder().encode(text)) {
24
- hash ^= BigInt(byte);
25
- hash = (hash * 0x100000001b3n) & MASK;
26
- }
27
- return `kui1:${hash.toString(16).padStart(16, '0')}`;
28
- }
29
-
30
- /** The `.kui.json` document a generated module's path would come from. */
31
- const documentFor = (filename) => filename.replace(VIEW_FILE, '.kui.json');
32
-
33
- export default {
34
- meta: {
35
- type: 'problem',
36
- docs: {
37
- description:
38
- 'Disallow hand edits to generated Kerf UI view modules (*.view.ts).',
39
- url: 'https://github.com/brianwestphal/kerf/blob/main/eslint-plugin/docs/rules/no-generated-view-edits.md',
40
- },
41
- schema: [],
42
- messages: {
43
- edited:
44
- 'This generated view module was edited by hand (its body no longer matches its kerf-ui-view header). Regenerate it with `kerf-ui-view generate`; put behavior, overrides, and wiring in your own files that import it.',
45
- header:
46
- 'This generated view module has a damaged kerf-ui-view header. Regenerate it with `kerf-ui-view generate` instead of editing it.',
47
- missing:
48
- 'A module beside a `.kui.json` view document must be the generated one. Run `kerf-ui-view generate` rather than writing it by hand.',
49
- },
50
- },
51
- create(context) {
52
- const filename = context.filename ?? context.getFilename();
53
- const sourceCode = context.sourceCode ?? context.getSourceCode();
54
- return {
55
- Program(node) {
56
- // Git checkouts may convert line endings; the digest covers LF text.
57
- const lines = sourceCode.text.replace(/\r\n/g, '\n').split('\n');
58
- if (!lines[0]?.startsWith(GENERATED)) {
59
- if (VIEW_FILE.test(filename) && existsSync(documentFor(filename))) {
60
- context.report({ node, messageId: 'missing' });
61
- }
62
- return;
63
- }
64
- const stamp = STAMP.exec(lines[1] ?? '');
65
- const contract = /^\/\/ kui-contract: (.*)$/.exec(lines[2] ?? '');
66
- if (!stamp || !contract) {
67
- context.report({ node, messageId: 'header' });
68
- return;
69
- }
70
- // The body digest covers the code; the contract digest covers the
71
- // recorded contract line (its canonical JSON).
72
- if (
73
- viewDigest(lines.slice(HEADER_LINES).join('\n')) !== stamp[2] ||
74
- viewDigest(contract[1]) !== stamp[1]
75
- ) {
76
- context.report({ node, messageId: 'edited' });
77
- }
78
- },
79
- };
80
- },
81
- };