what-core 0.14.0 → 0.15.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.
Files changed (145) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +64 -38
  3. package/a11y.d.ts +128 -0
  4. package/data.d.ts +294 -0
  5. package/dist/a11y.js +510 -0
  6. package/dist/a11y.min.js +413 -0
  7. package/dist/actions.js +158 -0
  8. package/dist/actions.min.js +112 -0
  9. package/dist/animation.js +481 -0
  10. package/dist/animation.min.js +295 -0
  11. package/dist/async.js +180 -0
  12. package/dist/async.min.js +134 -0
  13. package/dist/components.js +577 -0
  14. package/dist/components.min.js +413 -0
  15. package/dist/data.js +1212 -0
  16. package/dist/data.min.js +918 -0
  17. package/dist/diagnostics.js +187 -0
  18. package/dist/diagnostics.min.js +134 -0
  19. package/dist/dom.js +796 -0
  20. package/dist/dom.min.js +603 -0
  21. package/dist/entries/a11y.js +43 -0
  22. package/dist/entries/a11y.min.js +43 -0
  23. package/dist/entries/data.js +29 -0
  24. package/dist/entries/data.min.js +29 -0
  25. package/dist/entries/dom.js +45 -0
  26. package/dist/entries/dom.min.js +45 -0
  27. package/dist/entries/form.js +31 -0
  28. package/dist/entries/form.min.js +31 -0
  29. package/dist/entries/internal.js +123 -0
  30. package/dist/entries/internal.min.js +123 -0
  31. package/dist/entries/motion.js +23 -0
  32. package/dist/entries/motion.min.js +23 -0
  33. package/dist/entries/ui.js +25 -0
  34. package/dist/entries/ui.min.js +25 -0
  35. package/dist/env.js +5 -0
  36. package/dist/env.min.js +5 -0
  37. package/dist/errors.js +1518 -0
  38. package/dist/errors.min.js +548 -0
  39. package/dist/form.js +936 -0
  40. package/dist/form.min.js +703 -0
  41. package/dist/guardrails.js +84 -0
  42. package/dist/guardrails.min.js +55 -0
  43. package/dist/h.js +232 -0
  44. package/dist/h.min.js +171 -0
  45. package/dist/head.js +241 -0
  46. package/dist/head.min.js +207 -0
  47. package/dist/helpers.js +126 -0
  48. package/dist/helpers.min.js +98 -0
  49. package/dist/hooks.js +255 -0
  50. package/dist/hooks.min.js +153 -0
  51. package/dist/hot.js +215 -0
  52. package/dist/hot.min.js +24 -0
  53. package/dist/hydration-data.js +495 -0
  54. package/dist/hydration-data.min.js +371 -0
  55. package/dist/import-changes.js +273 -0
  56. package/dist/import-changes.min.js +272 -0
  57. package/dist/index.js +95 -0
  58. package/dist/index.min.js +95 -227
  59. package/dist/jsx-dev-runtime.js +10 -0
  60. package/dist/jsx-dev-runtime.min.js +10 -1
  61. package/dist/jsx-runtime.js +27 -0
  62. package/dist/jsx-runtime.min.js +15 -1
  63. package/dist/live.js +54 -0
  64. package/dist/live.min.js +49 -0
  65. package/dist/markup-rules.js +250 -0
  66. package/dist/markup-rules.min.js +213 -0
  67. package/dist/reactive.js +3334 -0
  68. package/dist/reactive.min.js +2033 -0
  69. package/dist/render.js +4746 -0
  70. package/dist/render.min.js +2797 -1
  71. package/dist/scheduler.js +225 -0
  72. package/dist/scheduler.min.js +162 -0
  73. package/dist/selector.js +11 -0
  74. package/dist/selector.min.js +10 -0
  75. package/dist/server-context.js +148 -0
  76. package/dist/server-context.min.js +121 -0
  77. package/dist/skeleton.js +342 -0
  78. package/dist/skeleton.min.js +310 -0
  79. package/dist/store.js +72 -0
  80. package/dist/store.min.js +50 -0
  81. package/dist/testing.js +720 -0
  82. package/dist/testing.min.js +458 -1
  83. package/dist/vnode-adoption.js +19 -0
  84. package/dist/vnode-adoption.min.js +19 -0
  85. package/dist/vnode-renderer.js +61 -0
  86. package/dist/vnode-renderer.min.js +47 -0
  87. package/dom.d.ts +44 -0
  88. package/form.d.ts +218 -0
  89. package/hot.d.ts +35 -0
  90. package/index.d.ts +421 -736
  91. package/internal.d.ts +284 -0
  92. package/jsx-runtime.d.ts +160 -137
  93. package/markup-rules.d.ts +83 -0
  94. package/motion.d.ts +156 -0
  95. package/package.json +117 -3
  96. package/render.d.ts +278 -29
  97. package/src/a11y.js +64 -59
  98. package/src/actions.js +226 -0
  99. package/src/animation.js +105 -57
  100. package/src/async.js +259 -0
  101. package/src/components.js +495 -144
  102. package/src/data.js +1410 -1159
  103. package/src/diagnostics.js +263 -0
  104. package/src/dom.js +1159 -872
  105. package/src/entries/a11y.js +24 -0
  106. package/src/entries/data.js +17 -0
  107. package/src/entries/dom.js +29 -0
  108. package/src/entries/form.js +16 -0
  109. package/src/entries/internal.js +63 -0
  110. package/src/entries/motion.js +13 -0
  111. package/src/entries/ui.js +13 -0
  112. package/src/env-development.js +12 -0
  113. package/src/env.js +33 -0
  114. package/src/errors.js +1144 -168
  115. package/src/form.js +723 -225
  116. package/src/guardrails.js +38 -126
  117. package/src/h.js +227 -152
  118. package/src/head.js +189 -19
  119. package/src/helpers.js +47 -75
  120. package/src/hooks.js +233 -248
  121. package/src/hot.js +316 -0
  122. package/src/hydration-data.js +859 -16
  123. package/src/import-changes.js +156 -0
  124. package/src/index.js +38 -188
  125. package/src/jsx-dev-runtime.js +7 -14
  126. package/src/jsx-runtime.js +25 -9
  127. package/src/live.js +80 -0
  128. package/src/markup-rules.js +387 -0
  129. package/src/reactive.js +4400 -862
  130. package/src/render.js +6502 -2570
  131. package/src/scheduler.js +56 -21
  132. package/src/selector.js +31 -0
  133. package/src/server-context.js +252 -22
  134. package/src/skeleton.js +22 -12
  135. package/src/store.js +17 -31
  136. package/src/testing.js +389 -63
  137. package/src/vnode-adoption.js +48 -0
  138. package/src/vnode-renderer.js +114 -0
  139. package/testing.d.ts +81 -1
  140. package/ui.d.ts +20 -0
  141. package/dist/chunk-6YOUZ6T4.min.js +0 -1
  142. package/dist/chunk-FN6HXME3.min.js +0 -11
  143. package/dist/chunk-VKZY7JPN.min.js +0 -1
  144. package/src/agent-context.js +0 -127
  145. package/src/warnings.js +0 -193
package/src/errors.js CHANGED
@@ -1,8 +1,9 @@
1
1
  // What Framework - Structured Error System
2
2
  // Agent-first error reporting with actionable codes, suggestions, and JSON output.
3
3
  // Every error tells an AI agent exactly what went wrong and how to fix it.
4
-
5
- import { __DEV__ } from './reactive.js';
4
+ //
5
+ // Import-free on purpose: diagnostics.js and the engine both depend on this
6
+ // catalogue, and anything it imported would sit in their import graph.
6
7
 
7
8
  // --- Error Codes ---
8
9
  // Each code maps to a specific, well-documented mistake pattern.
@@ -11,9 +12,11 @@ export const ERROR_CODES = {
11
12
  INFINITE_EFFECT: {
12
13
  code: 'ERR_INFINITE_EFFECT',
13
14
  severity: 'error',
14
- template: 'Effect "{{effectName}}" exceeded 25 flush iterations — likely an infinite loop.',
15
+ template: 'Effect "{{effectName}}" was stopped after {{rounds}} re-runs in one flush: it keeps re-triggering itself, likely an infinite loop.',
15
16
  suggestion: 'An effect is writing to a signal it also reads, creating a cycle. Use untrack() to read the signal without subscribing, or restructure so the write and read are in separate effects.',
16
- codeExample: `// Bad — reads and writes count, creating a cycle:
17
+ codeExample: `const count = signal(0);
18
+
19
+ // Bad — reads and writes count, creating a cycle:
17
20
  effect(() => { count(count() + 1); });
18
21
 
19
22
  // Good — use untrack() so the read doesn't subscribe:
@@ -23,59 +26,349 @@ effect(() => { count(untrack(count) + 1); });
23
26
  const doubled = computed(() => count() * 2);`,
24
27
  },
25
28
 
29
+ COMPUTED_CYCLE: {
30
+ code: 'ERR_COMPUTED_CYCLE',
31
+ severity: 'error',
32
+ template: 'Computed "{{name}}" reads its own value, directly or through computeds that read it.',
33
+ suggestion: 'A computed cannot depend on itself. Find which computed it reads that reads it back, and move the input they share into a signal or computed of its own that both read. A value that has to build on its own previous value is state: keep it in a signal and write it from an effect.',
34
+ codeExample: `// Bad - total reads itself through average:
35
+ const average = computed(() => total() / items().length);
36
+ const total = computed(() => average() * items().length + shipping());
37
+
38
+ // Good - both read the inputs, never each other:
39
+ const subtotal = computed(() => items().reduce((sum, item) => sum + item.price, 0));
40
+ const total = computed(() => subtotal() + shipping());
41
+ const average = computed(() => subtotal() / items().length);
42
+
43
+ // Good - a running value keeps its previous value in a signal:
44
+ const spent = signal(0);
45
+ effect(() => { const price = lastPurchase(); spent((previous) => previous + price); });`,
46
+ },
47
+
48
+ SIGNAL_WRITE_IN_COMPUTED: {
49
+ code: 'ERR_SIGNAL_WRITE_IN_COMPUTED',
50
+ severity: 'warning',
51
+ template: 'Computed "{{computedName}}" wrote signal "{{signalName}}". A computed only derives a value; a write from it runs again on every recomputation and can loop.',
52
+ suggestion: 'A computed runs lazily, whenever it is read after an input changed, so a write inside it happens an unpredictable number of times and can re-trigger its own readers. Derive the second value as a computed of its own, or make the write in an effect or an event handler.',
53
+ codeExample: `// Bad - the computed writes count:
54
+ const count = signal(0);
55
+ const total = computed(() => {
56
+ count(items().length);
57
+ return items().reduce((sum, item) => sum + item.price, 0);
58
+ });
59
+
60
+ // Good - each derived value is its own computed:
61
+ const count = computed(() => items().length);
62
+ const total = computed(() => items().reduce((sum, item) => sum + item.price, 0));`,
63
+ },
64
+
65
+ NESTED_FLUSH_SYNC: {
66
+ code: 'ERR_NESTED_FLUSH_SYNC',
67
+ severity: 'warning',
68
+ template: 'flushSync() was called while {{context}} was running, so it did nothing: the effects it would run already run when the current flush reaches them.',
69
+ suggestion: 'flushSync() runs queued effects immediately, which is only safe when no effect, computed or flush is running; inside one it returns without running anything. Call it from an event handler, onMount or test code, or drop it: effects queued during an effect run later in the same flush.',
70
+ codeExample: `// Bad - inside an effect, flushSync() does nothing:
71
+ effect(() => {
72
+ width(container().offsetWidth);
73
+ flushSync();
74
+ layout();
75
+ });
76
+
77
+ // Good - flush from the handler that made the write:
78
+ button.addEventListener('click', () => {
79
+ open(true);
80
+ flushSync();
81
+ panel.focus();
82
+ });`,
83
+ },
84
+
26
85
  MISSING_SIGNAL_READ: {
27
86
  code: 'ERR_MISSING_SIGNAL_READ',
28
87
  severity: 'warning',
29
- template: 'Signal "{{signalName}}" used without calling () — renders as "[Function]" instead of its value.',
30
- suggestion: 'Signals are functions. Call them to read: count() not count. In JSX: {count()} not {count}.',
31
- codeExample: `// Bad — signal reference, not value:
32
- <span>{count}</span> // renders "[Function]"
33
-
34
- // Good — call the signal:
35
- <span>{count()}</span> // renders the actual value`,
88
+ template: 'Signal "{{signalName}}" was used as a value without being called (in a template literal, `+`, arithmetic, a comparison or as a property key), so the function\'s source text stood in for its value.',
89
+ suggestion: 'Signals are functions, and so are the accessors useState, useReducer and useMemo return and computed() creates. Call them to read: count() not count, in a template literal (`${count()}`), in arithmetic (`count() + 1`), in a comparison (`count() > 5`: `count > 5` compares the source text and is false) and as a key (`labels[count()]`). On its own as a JSX child or attribute value (`<span>{count}</span>`) an accessor is a live binding and needs no call. Development renders exactly what production renders here, so the broken text you see is the bug. The report names the scope that used the signal, and its location is the line that used it when the browser\'s stack names one (the module as the dev server serves it, so the line can differ from the source), else that scope\'s; `data.createdAt` is where the signal was created.',
90
+ codeExample: `// Bad - the accessor itself is converted:
91
+ const [count, setCount] = useState(3);
92
+ const label = \`Total: \${count}\`; // "Total: function sig(next) {..."
93
+ if (count > 5) {} // compares the function's text: always false
94
+
95
+ // Good - call it:
96
+ const label = \`Total: \${count()}\`; // "Total: 3"
97
+ if (count() > 5) {}`,
36
98
  },
37
99
 
38
100
  HYDRATION_MISMATCH: {
39
101
  code: 'ERR_HYDRATION_MISMATCH',
40
102
  severity: 'error',
41
- template: 'Hydration mismatch in component "{{component}}": server rendered "{{serverHTML}}" but client expects "{{clientHTML}}".',
42
- suggestion: 'Ensure server and client render identical initial HTML. Avoid reading browser-only APIs (window, localStorage) during the initial render. Use onMount() for client-only logic.',
43
- codeExample: `// Bad — different on server vs client:
44
- function App() {
45
- return <p>{window.innerWidth}</p>;
103
+ template: 'Hydration mismatch ({{kind}}) in <{{component}}> at {{path}}: the server rendered {{found}} where the client renders {{expected}}. Recovery: {{recovery}}.',
104
+ suggestion: 'hydrate() adopts the server\'s DOM only where the client renders the same thing. Here it does not, so that region was rendered on the client instead (a component\'s key mismatch only reports: the markup itself matched). The usual cause is a value the server cannot know or computes differently: Date.now(), Math.random(), typeof window, localStorage, the viewport, a locale. Render the same value on both sides during hydration and change it in onMount(), or send it with the page (a loader, a keyed resource). Each report carries the record { kind, component, ownerPath, path, expected, found, recovery } (the diagnostic\'s data in development, the argument of hydrate()\'s onHydrationError option in every build): kind is tag, text, missing, extra-nodes, marker, key (a component\'s data-hk, or a keyed list whose server rows have other keys, or keys in another order, or keys hydration cannot compare (anything but strings and finite numbers): expected and found list them), shadow-root (an element hosting a declarative shadow root, which a client render never makes: the element is replaced), prebuilt (JSX the client built before the walk reached its place: in a variable, read by a component that inspects it, or given to an h() component; it takes the server\'s place, and what the user changed in a form control there is kept), not-hydratable, or attribute (development only, and the diagnostic only: an attribute the server wrote otherwise than the client\'s first write, or that only one side wrote; the record also carries `attribute`, its name; the client\'s value is written, recovery client-value; a boolean attribute present on both sides and style declarations the DOM reads as the same are equal, class tokens in another order and a URL written otherwise are not); component and ownerPath name the component and its owner path (its data-hk); path is the DOM path under the hydrate() container; expected and found describe the client\'s and the server\'s node; recovery is client-render, move (a keyed list: each server row was taken as the row of its own key and moved into the client\'s order; a row is never given to another key, so what was typed in it stays with its key), or none for a component\'s key mismatch. kind not-hydratable means hydrate() was handed DOM already built, reported once: compiled JSX adopts server markup only when compiled for hydration (what-compiler\'s hydratable option, which the Vite plugin sets when the project renders on the server), and DOM made by hand in a component body is replaced the same way (create it in onMount).',
105
+ codeExample: `// Bad — the client renders a value the server could not know:
106
+ import { h, hydrate } from 'what-framework';
107
+
108
+ function Width() {
109
+ return h('p', {}, \`\${window.innerWidth}px\`);
46
110
  }
47
111
 
48
- // Good — use onMount for client-only values:
49
- function App() {
112
+ const page = document.createElement('main');
113
+ page.innerHTML = '<p>1280px</p>'; // what the server sent
114
+ document.body.append(page);
115
+ hydrate(h(Width), page, { onHydrationError: (record) => console.log(record) });
116
+ // { kind: 'text', component: 'Width', ownerPath: '~0', path: 'p>#text',
117
+ // expected: '"1024px"', found: '"1280px"', recovery: 'client-render' }
118
+
119
+ // Good — the same on both sides, corrected after hydration:
120
+ function Width() {
50
121
  const width = signal(0);
51
122
  onMount(() => width(window.innerWidth));
52
- return <p>{width()}</p>;
123
+ return <p>{width()}px</p>;
53
124
  }`,
54
125
  },
55
126
 
127
+ HYDRATION_OWNER_MISMATCH: {
128
+ code: 'ERR_HYDRATION_OWNER_MISMATCH',
129
+ severity: 'warning',
130
+ template: 'A keyless resource or async value at owner path {{path}} was rendered by <{{server}}> on the server and <{{client}}> on the client, so it fetches instead of adopting the server value.',
131
+ suggestion: 'While hydrating, a keyless createResource() or async computed() takes the value the server rendered with by its position in the tree (its owner path), and in development only when the component at that position is the same one on both sides. Here it is not: a component exists on one side only (a branch on isServerRender(), typeof window, localStorage or a feature flag) and moved its neighbours. In development the value fetches again; a production build cannot compare names, since its bundle renames every function, so there the component at this position takes the value the server rendered for the other one. Render the same components on both sides during hydration (decide client-only content in onMount), wrap the one-sided branch in a component that exists on both sides, or give the resource a key, which is adopted by that key wherever it is.',
132
+ codeExample: `// Bad — a branch that exists only on the client moves its siblings:
133
+ <div>{showChat() && <ChatWidget />}<Account /></div>
134
+
135
+ // Good — the same component on both sides; the widget decides after mount:
136
+ <div><ChatSlot /><Account /></div>
137
+
138
+ // Good — a keyed resource is adopted by its key, wherever it is:
139
+ const [account] = createResource(loadAccount, { key: 'account' });`,
140
+ },
141
+
56
142
  ORPHAN_EFFECT: {
57
143
  code: 'ERR_ORPHAN_EFFECT',
58
144
  severity: 'warning',
59
- template: 'Effect "{{effectName}}" was created outside a reactive root — it will never be cleaned up.',
60
- suggestion: 'Wrap effect creation in createRoot() or create effects inside component functions where they are automatically tracked.',
61
- codeExample: `// Bad — orphaned, leaks memory:
62
- effect(() => console.log(count()));
145
+ template: 'Effect "{{effectName}}" was created after an await, where no owner is current: nothing will dispose it when the component that started the async work goes away.',
146
+ suggestion: 'Work created after an `await` belongs to no owner. Read getOwner() before the await and create the effect inside runWithOwner(owner, ...), so it is disposed with the component (or with the effect run) that started the work; or create it before the await.',
147
+ codeExample: `// Bad — the effect outlives the component:
148
+ onMount(async () => {
149
+ const user = await loadUser();
150
+ effect(() => console.log(user.name, count()));
151
+ });
63
152
 
64
- // Good — inside a root with cleanup:
65
- createRoot(dispose => {
66
- effect(() => console.log(count()));
67
- // later: dispose() cleans up
153
+ // Good — attach the work to the owner that started it:
154
+ onMount(async () => {
155
+ const owner = getOwner();
156
+ const user = await loadUser();
157
+ runWithOwner(owner, () => {
158
+ effect(() => console.log(user.name, count()));
159
+ });
68
160
  });`,
69
161
  },
70
162
 
163
+ REBUILT_COMPONENT: {
164
+ code: 'ERR_REBUILT_COMPONENT',
165
+ severity: 'warning',
166
+ template: 'A reactive region rebuilt <{{component}}> when it ran again, and the state <{{component}}> held is gone: "{{region}}" builds everything it returns anew on every run.',
167
+ suggestion: 'Write the branches as a JSX ternary or <Show> (<Switch>/<Match> for more than two), and read the changing value where the component takes it: `<Panel data={query.data()} />`, with a computed() for a derived value. The compiler then builds <Panel> once and updates its props in place. A block function child (`{() => { const d = q(); if (!d) return ...; return <Panel data={d} />; }}`) runs again whenever anything it read changes, and rebuilds what it returns.',
168
+ codeExample: `// Bad — the region runs again on every refetch and rebuilds <Chart>:
169
+ <div>{() => {
170
+ if (query.isLoading()) return <Spinner />;
171
+ const counts = countByKind(query.data());
172
+ return <Chart counts={counts} />;
173
+ }}</div>
174
+
175
+ // Good — <Chart> is built once; its counts follow the data:
176
+ const counts = computed(() => countByKind(query.data()));
177
+ <div>
178
+ <Show when={!query.isLoading()} fallback={<Spinner />}>
179
+ <Chart counts={counts()} />
180
+ </Show>
181
+ </div>`,
182
+ },
183
+
184
+ ASYNC_EFFECT: {
185
+ code: 'ERR_ASYNC_EFFECT',
186
+ severity: 'warning',
187
+ template: 'Effect "{{effectName}}" is an async function. Only what it reads before its first await is tracked, the promise it returns is not a cleanup, and an older run can finish after a newer one and overwrite it.',
188
+ suggestion: 'Fetch in an async computed instead: computed(async () => ...) is a value in the graph that supersedes older runs, aborts them and shows as pending, and an effect or binding that reads it runs when the value lands. Keep effects synchronous; if one must start async work, start it inside and keep the effect itself sync, returning a cleanup that cancels it.',
189
+ codeExample: `// Bad — reads after the await are not tracked, and a slow old run can win:
190
+ useEffect(async () => {
191
+ const res = await fetch('/api/users/' + id());
192
+ user(await res.json());
193
+ });
194
+
195
+ // Good — an async computed: one value, newest run wins, older runs aborted:
196
+ function Profile() {
197
+ const user = computed(async ({ signal }) => {
198
+ const res = await fetch('/api/users/' + id(), { signal });
199
+ return res.json();
200
+ });
201
+ return <h1>{user().name}</h1>;
202
+ }`,
203
+ },
204
+
205
+ PENDING_READ_UNTRACKED: {
206
+ code: 'ERR_PENDING_READ_UNTRACKED',
207
+ severity: 'warning',
208
+ template: '{{call}} was read in a component body. The body runs once, so this reads the pending state once and it never changes on screen.',
209
+ suggestion: 'Read pending state where it is tracked: in JSX (users.pending() is a zero-argument call the compiler wraps, so {users.pending() && <Spinner />} updates), or wrap the expression in a function: {() => isPending(() => users()) ? "Refreshing" : ""}. In an event handler, reading it once is what you want, and nothing is reported.',
210
+ codeExample: `// Bad — read once when the component is created:
211
+ function Users() {
212
+ const refreshing = users.pending();
213
+ return <p>{refreshing ? 'Refreshing…' : ''}</p>;
214
+ }
215
+
216
+ // Good — read in JSX, where it is tracked:
217
+ function Users() {
218
+ return <p>{users.pending() ? 'Refreshing…' : ''}</p>;
219
+ }`,
220
+ },
221
+
222
+ WRITE_AFTER_AWAIT: {
223
+ code: 'ERR_WRITE_AFTER_AWAIT',
224
+ severity: 'warning',
225
+ template: 'Signal "{{signalName}}" was written outside a transition while the async function of a transition that also wrote it was still running: a write after an await is not part of the transition, so it shows before the transition commits.',
226
+ suggestion: 'startTransition holds what the writes made synchronously inside its function reach. After an await, the function runs on its own and its writes are ordinary writes (as in React). Make the writes that belong to the commit before the first await, or wrap the later ones in startTransition again; data that arrives later belongs in an async computed, which the transition waits for.',
227
+ codeExample: `// Bad — status('saved') shows at once, before the list commits:
228
+ startTransition(async () => {
229
+ status('saving');
230
+ await save(item);
231
+ status('saved');
232
+ await refresh(list);
233
+ });
234
+
235
+ // Good — the later write is a transition of its own:
236
+ startTransition(async () => {
237
+ status('saving');
238
+ await save(item);
239
+ startTransition(() => status('saved'));
240
+ await refresh(list);
241
+ });`,
242
+ },
243
+
244
+ ASYNC_WITHOUT_SUSPENSE: {
245
+ code: 'ERR_ASYNC_WITHOUT_SUSPENSE',
246
+ severity: 'warning',
247
+ template: 'Component "{{component}}" suspended (lazy(), use() or a value that had not landed, read in its body) with no <Suspense> above it: it renders nothing until the promise settles.',
248
+ suggestion: 'A component that suspends waits for its promise and then renders in place. With a <Suspense fallback> above it, the fallback shows meanwhile on first load. Wrap the part of the page that loads in <Suspense>, or read the async value in JSX instead of in the component body: a binding that reads it renders nothing until it lands, and is not a suspension.',
249
+ codeExample: `// Bad — nothing on screen, and no fallback, until the chunk arrives:
250
+ mount(<Settings />, '#app'); // Settings = lazy(() => import('./Settings.jsx'))
251
+
252
+ // Good — a fallback while it loads:
253
+ mount(<Suspense fallback={<Spinner />}><Settings /></Suspense>, '#app');`,
254
+ },
255
+
256
+ ASYNC_READ_IN_BODY: {
257
+ code: 'ERR_ASYNC_READ_IN_BODY',
258
+ severity: 'error',
259
+ template: 'Component "{{component}}" read an async value it made in its own body before the value landed: suspending would run it again, make the value again and fetch again, forever.',
260
+ suggestion: 'A component body runs once; reading an async value there before it lands suspends the component, and running it again makes a new computed with a new fetch. Read the value in JSX, where a binding waits for it (and a <Suspense> shows its fallback), or make the computed outside the component (a parent, a module) and pass it in.',
261
+ codeExample: `// Bad — read in the body that made it:
262
+ function Profile() {
263
+ const user = computed(() => fetchUser());
264
+ const name = user().name;
265
+ return <h1>{name}</h1>;
266
+ }
267
+
268
+ // Good — read in JSX:
269
+ function Profile() {
270
+ const user = computed(() => fetchUser());
271
+ return <h1>{user().name}</h1>;
272
+ }`,
273
+ },
274
+
275
+ USE_UNCACHED_PROMISE: {
276
+ code: 'ERR_USE_UNCACHED_PROMISE',
277
+ severity: 'error',
278
+ template: 'Component "{{component}}" keeps suspending on a new promise: use() received a promise made in the component body, which is new on every attempt, so it never finishes.',
279
+ suggestion: 'A component that suspends on use(promise) runs again when the promise settles, and a promise created in its body is created again then. Pass use() a promise made outside the component (a prop, a module-level cache), or make the value an async computed, which is created once and suspends its readers until it lands.',
280
+ codeExample: `// Bad — a new promise on every attempt:
281
+ function User(props) {
282
+ const user = use(fetch('/api/users/' + props.id).then((r) => r.json()));
283
+ return <h1>{user.name}</h1>;
284
+ }
285
+
286
+ // Good — an async computed, created once:
287
+ function User(props) {
288
+ const user = computed(() => fetch('/api/users/' + props.id).then((r) => r.json()));
289
+ return <h1>{user().name}</h1>;
290
+ }`,
291
+ },
292
+
293
+ OPTIMISTIC_OUTSIDE_TRANSITION: {
294
+ code: 'ERR_OPTIMISTIC_OUTSIDE_TRANSITION',
295
+ severity: 'warning',
296
+ template: 'addOptimistic() was called outside a transition, so the optimistic value drops at once instead of lasting until the action finishes.',
297
+ suggestion: 'An optimistic overlay lives as long as the transition it was added in. Call addOptimistic synchronously inside startTransition, before its first await (after an await the function is no longer inside the transition, as in React).',
298
+ codeExample: `// Bad — added after an await, or in a plain handler:
299
+ const toggle = async (id) => {
300
+ await save(id);
301
+ addOptimistic(id);
302
+ };
303
+
304
+ // Good — added first, inside the transition:
305
+ const toggle = (id) => startTransition(async () => {
306
+ addOptimistic(id);
307
+ await save(id);
308
+ await refresh(todos);
309
+ });`,
310
+ },
311
+
312
+ ASYNC_COMPONENT: {
313
+ code: 'ERR_ASYNC_COMPONENT',
314
+ severity: 'warning',
315
+ template: 'Component "{{component}}" returned a promise: an async component renders as text.',
316
+ suggestion: 'Components run once and synchronously, so an async one renders the promise\'s text, even under <Suspense>. Keep the component synchronous and make the data an async value: computed(async ({ signal }) => ...) made in the body or outside it, and read in JSX, where a binding waits for it to land and a <Suspense> above shows its fallback meanwhile. For a component whose code loads later, use lazy().',
317
+ codeExample: `// Bad — an async component renders "[object Promise]":
318
+ async function Profile(props) {
319
+ const user = await fetchUser(props.id);
320
+ return <h1>{user.name}</h1>;
321
+ }
322
+
323
+ // Good — a synchronous component that reads an async value:
324
+ function Profile(props) {
325
+ const user = computed(({ signal }) => fetchUser(props.id, { signal }));
326
+ return <h1>{user().name}</h1>;
327
+ }`,
328
+ },
329
+
330
+ ASYNC_MEMO: {
331
+ code: 'ERR_ASYNC_MEMO',
332
+ severity: 'warning',
333
+ template: 'useMemo() returned a promise; useMemo keeps it, so its readers get the promise.',
334
+ suggestion: 'useMemo keeps what its function returns, as React\'s does. For a value that loads, use computed() or useComputed() instead: computed(async ({ signal }) => ...) is an async value, whose readers wait for it to land and which refetches when what it reads changes. Keep useMemo for values computed synchronously.',
335
+ codeExample: `// Bad — user() is a promise:
336
+ const user = useMemo(() => fetch('/api/users/' + id()).then((r) => r.json()));
337
+
338
+ // Good — user() is the user once it has landed:
339
+ const user = computed(({ signal }) => fetch('/api/users/' + id(), { signal }).then((r) => r.json()));`,
340
+ },
341
+
342
+ SUSPEND_IN_TRANSITION: {
343
+ code: 'ERR_SUSPEND_IN_TRANSITION',
344
+ severity: 'warning',
345
+ template: 'Component "{{component}}" suspended while a transition committed: its fallback shows.',
346
+ suggestion: 'The component suspended on a promise (use() or a lazy() chunk), so its <Suspense> shows the fallback again. A transition holds async values, not components that suspend (React keeps the old content here). Make what the component waits for an async value of the state the transition writes, and read it in JSX: computed(async ({ signal }) => fetchTab(tab(), { signal })) is held by the transition, which keeps the old content on screen until the new value has landed. A lazy() chunk can be loaded before the transition (call its import() first), or read as an async value in its parent: computed(() => import("./Page.jsx")).',
347
+ codeExample: `// Bad — React's tabs pattern: the fallback replaces the old tab:
348
+ function Panel(props) {
349
+ const data = use(props.promise);
350
+ return <p>{data.text}</p>;
351
+ }
352
+ <button onClick={() => startTransition(() => tab('b'))}>B</button>
353
+
354
+ // Good — the tab's data is an async value of the tab:
355
+ const data = computed(({ signal }) => fetchTab(tab(), { signal }));
356
+ function Panel() {
357
+ return <p>{data().text}</p>;
358
+ }
359
+ <button onClick={() => startTransition(() => tab('b'))}>B</button>`,
360
+ },
361
+
71
362
  SIGNAL_WRITE_IN_RENDER: {
72
363
  code: 'ERR_SIGNAL_WRITE_IN_RENDER',
73
364
  severity: 'error',
74
365
  template: 'Signal "{{signalName}}" written during render of component "{{component}}". This triggers re-execution.',
75
366
  suggestion: 'Move signal writes into event handlers, effects, or onMount(). The component body should only read signals, not write them.',
76
- codeExample: `// Bad — write during render:
367
+ codeExample: `const count = signal(0);
368
+
369
+ // Bad — write during render:
77
370
  function Counter() {
78
- count(count() + 1); // triggers infinite loop
371
+ count(count() + 1); // a side effect of rendering: every mount writes it
79
372
  return <span>{count()}</span>;
80
373
  }
81
374
 
@@ -120,13 +413,169 @@ html\`<div>\${sanitizedContent}</div>\``,
120
413
  MISSING_KEY: {
121
414
  code: 'ERR_MISSING_KEY',
122
415
  severity: 'warning',
123
- template: 'List rendered without key prop in component "{{component}}". Items may re-order incorrectly.',
416
+ template: 'A .map() returns JSX without a key prop.',
124
417
  suggestion: 'Add a unique key prop to each item in a list. Use a stable identifier (like an ID), not the array index.',
125
418
  codeExample: `// Bad — no key:
126
- <For each={items()}>{item => <li>{item.name}</li>}</For>
419
+ <ul>{items().map(item => <li>{item.name}</li>)}</ul>
127
420
 
128
421
  // Good — stable key:
129
- <For each={items()}>{item => <li key={item.id}>{item.name}</li>}</For>`,
422
+ <ul>{items().map(item => <li key={item.id}>{item.name}</li>)}</ul>`,
423
+ },
424
+
425
+ PROP_READ_ONCE: {
426
+ code: 'ERR_PROP_READ_ONCE',
427
+ severity: 'warning',
428
+ template: 'Prop `{{name}}` is read once, when <{{component}}> runs: {{reason}}.',
429
+ suggestion: 'what-compiler reads a destructured prop where it is used (`({ label }) => <b>{label}</b>` reads `props.label` in the binding), so it follows the parent\'s state as React re-renders with it, and a rest element keeps the props\' live values (`({ as: Tag, ...rest }) => <Tag {...rest} />`). It cannot when the binding is assigned again, its key is computed, it is destructured twice, its default reads a name of the component or calls something, its nested pattern holds a rest element or an array, or the pattern is declared with `var`. A component that decides what it returns from a prop the React way (`if (!open) return null`, `return on ? <A /> : <B />`, a `switch` whose cases return) follows it: the compiler lowers the body from that statement on to the branch it means, as `<>{on ? <A /> : <B />}</>` is, built when it is shown, while the code before it runs once. It does not lower a return inside a loop or a `try`, a `var` after the branch, an `if` neither arm of which ends the component with code after it, a `switch` with a `break` or whose `default` is not its last case, a return left with `break` out of a labeled block, or h() code, which it does not compile: those decide once, so branch where it renders (`<>{() => (on ? <A /> : <B />)}</>` or `<Show when={…}>`; with h(), `() => (on ? h(A) : null)`). A `let` the body computes from a prop (`let cls = \'btn\'; if (primary) cls += \' primary\'`) follows it: the compiler makes it a memo of the statements that assign it, read where it is used. It cannot when those statements do anything else (assign another name or a property, call a hook, build JSX, return or `break` out), the `let` is also assigned in a function or read before them: then it keeps its first value and is reported, so compute it where it is shown. Two more shapes read a prop once: a value computed from a prop in the body and shown in JSX (`const label = name.toUpperCase()` with `{label}`) keeps its first value, so write the expression in the JSX (`{name.toUpperCase()}`) or make it a function and call it there (`const label = () => name.toUpperCase()` with `{label()}`); and a prop handed as a value to the JSX helper a component returns (`return mk(value)`) is the value it had. Handed in an object literal (`return mk({ value })`, or the props spread into it, `mk({ ...props })`) it follows, wherever `mk` is declared and when it is a method of an object literal (`ui.row({ value })`): the compiler makes the object\'s props getters, as compiled JSX hands a component its props; or hand the props on (`mk(props)`). A route page\'s `params` and `route` are not reported: the router builds a page again for other params. Its `query` is: a change of query alone (`?page=2`) keeps the page mounted, as React Router keeps the route\'s element, so a read in the body of a component under the page keeps its first value, and in development what-router reports one (a static `queryKey: [\'items\', query.page]`, `useSearch().q`) the first time the query changes under it, unless that change disposes the component (a `key` that changes with it builds a new one, as in React; a branch it closes removes it); a read that seeds state meant to keep its first value (`useState(query.q)`) is reported too, and keeps it as meant. Neither is a value derived from a field of a keyed row\'s item (`item.title` in `<Row key={item.id} item={item} />`): the row is built again when that field changes. The compiler reports each at build time (development builds), and a value derived only from fields of props on the page, where the component renders outside such a row; where it does not build (the islands template, h() code), eslint-plugin-what\'s no-prop-read-once reports the return decided by a prop. Read the prop where you use it (`props.size ?? \'md\'`), give the result a name of its own instead of assigning the prop, make a default a constant at module scope, or keep a value that must change in a signal.',
430
+ codeExample: `// Bad - size is assigned again, so it is read once:
431
+ function Button({ size, ...rest }) {
432
+ size = size ?? 'md';
433
+ return <button class={'btn-' + size} {...rest} />;
434
+ }
435
+
436
+ // Bad - a return inside a loop is decided once:
437
+ function FirstOn({ items = [] }) {
438
+ for (const item of items) {
439
+ if (item.on) return <b>{item.name}</b>;
440
+ }
441
+ return null;
442
+ }
443
+
444
+ // Bad - label is computed once, from the first name:
445
+ function Title({ name }) {
446
+ const label = name.toUpperCase();
447
+ return <h1>{label}</h1>;
448
+ }
449
+
450
+ // Good - the default applies where size is read, and size follows the parent:
451
+ function Button({ size = 'md', ...rest }) {
452
+ return <button class={'btn-' + size} {...rest} />;
453
+ }
454
+
455
+ // Good - a computed default, read where it is used:
456
+ function IconButton(props) {
457
+ return <button class={'btn-' + (props.size ?? defaultSize())} />;
458
+ }
459
+
460
+ // Good - a branch returned the React way follows the prop:
461
+ function Status({ online }) {
462
+ if (!online) return <i>offline</i>;
463
+ return <b>online</b>;
464
+ }
465
+
466
+ // Good - the loop in a reactive child, run where it renders:
467
+ function FirstOn({ items = [] }) {
468
+ return <>{() => {
469
+ const item = items.find((i) => i.on);
470
+ return item ? <b>{item.name}</b> : null;
471
+ }}</>;
472
+ }
473
+
474
+ // Good - label is a function, called where it is shown:
475
+ function Title({ name }) {
476
+ const label = () => name.toUpperCase();
477
+ return <h1>{label()}</h1>;
478
+ }`,
479
+ },
480
+
481
+ STATE_READ_ONCE: {
482
+ code: 'ERR_STATE_READ_ONCE',
483
+ severity: 'warning',
484
+ template: 'State `{{name}}` is read once in <{{component}}>: {{reason}}.',
485
+ suggestion: 'A component runs once, so state it reads in its body, outside JSX and outside a function, is read once, where React reads it again on every render. A component that decides what it returns from its state the React way (`if (loading()) return <Spinner />`, `return open() ? <Dialog /> : null`) follows it: the compiler lowers the body from that statement on to the branch it means, built when it is shown. So does a return decided by state the component does not own: a signal or `computed` of the module, a function imported from another module and called with no arguments (a store\'s accessor, `session()`), what a hook returns (the accessor it returns, `const isMobile = useMediaQuery(q); if (isMobile())`, an accessor destructured from it, `const { user } = useAuth(); if (!user())`, or a method or a field of its object, a store\'s `todos.remaining`, from the component\'s module or another), a function that reads any of these, and a context\'s value (`const theme = useContext(Theme)`, or `useContext(Theme)` read in the condition itself, which the compiler makes a memo of the `useContext` call). Where it cannot (a return inside a loop or a `try`, a `var` after the branch, a `switch` with a `break` or whose `default` is not last, a labeled block left with `break`, h() code), the branch is decided once, so branch where it renders (`<>{() => (loading() ? <Spinner /> : <List />)}</>` or `<Show when={…}>`). A value one of the app\'s hooks returned, read as it is (`const { user } = useAuth(); if (!user)`, or a hook that returns a plain value, `const isMobile = useIsMobile(); if (isMobile)`), was read when the hook ran, once, with the component: call the accessor the hook returns (`user()`), or keep its result and read the field where it is used, and have a hook that returns a value return an accessor instead, called where it is read (`isMobile()`). A field read off the hook createStore() makes (`const auth = createStore({ user: null })`, then `auth.user`) is a property of that function, not the store\'s state: call the hook in the component (`const state = auth()`) and read `state.user`. A value derived from state in the body and shown in JSX (`const valid = name().length > 0` with `disabled={!valid}`) keeps its first value, so write the expression in the JSX (`disabled={name().length === 0}`) or derive it with `computed()` or `useMemo()` and call it there (`valid()`). State is the accessor a What hook or primitive returns (`useState`, `useReducer`, `useSignal`, `signal`, `computed`, `useMemo`, …). what-compiler reports both at build time (development builds), and eslint-plugin-what\'s no-state-read-once where the compiler does not build (the islands template, h() code). A read inside a function is not reported: `untrack(() => count())` keeps the first value on purpose.',
486
+ codeExample: `import { useState, useEffect, useMemo } from 'what-framework';
487
+
488
+ // Bad - a return inside a loop is decided once:
489
+ function FirstDone() {
490
+ const [tasks, setTasks] = useState([]);
491
+ useEffect(() => { load().then(setTasks); }, []);
492
+ for (const task of tasks()) {
493
+ if (task.done) return <p>{task.title}</p>;
494
+ }
495
+ return <p>None done</p>;
496
+ }
497
+
498
+ // Bad - the button never enables: valid is computed once:
499
+ function Signup() {
500
+ const [name, setName] = useState('');
501
+ const valid = name().length > 0;
502
+ return <button disabled={!valid}>Sign up</button>;
503
+ }
504
+
505
+ // Good - an early return on state follows it:
506
+ function Users() {
507
+ const [loading, setLoading] = useState(true);
508
+ useEffect(() => { load().then(() => setLoading(false)); }, []);
509
+ if (loading()) return <p>Loading…</p>;
510
+ return <ul>…</ul>;
511
+ }
512
+
513
+ // Good - derived with useMemo, read where it is shown:
514
+ function Signup() {
515
+ const [name, setName] = useState('');
516
+ const valid = useMemo(() => name().length > 0);
517
+ return <button disabled={!valid()}>Sign up</button>;
518
+ }`,
519
+ },
520
+
521
+ CLEANUP_READS_LIVE: {
522
+ code: 'ERR_CLEANUP_READS_LIVE',
523
+ severity: 'warning',
524
+ template: 'The {{hook}} cleanup in <{{component}}> reads `{{name}}` when it runs, not the value its run used.',
525
+ suggestion: 'React\'s cleanup closes over the render that made it, so a cleanup that undoes what its run did with a prop (`join(roomId)`, then `leave(roomId)`) undoes it for the old value when the value changes. A component runs once, so what-compiler keeps, for a cleanup the effect\'s callback returns (`return () => leave(roomId)`), each prop and state accessor it reads as the run that returned it read them, in a local of that run: it leaves the old room, as React\'s does. A cleanup the component made once, outside the effect, and the effect returns (`const stop = () => leave(roomId)` in the body, then `return stop`) is not one: it reads the values of when it runs, after the change that makes the effect run again, and undoes the new value, so the old one is never undone. Write the cleanup in the effect and return it there, or keep the value the run used in a local of the run and hand it to the function. what-compiler reports it at build time (development builds) when that function reads a prop or calls a state accessor that the run also reads, and the effect can run again (it has no `[]` dependency array). Where the compiler does not build (the islands template, h() code) no value is kept, and eslint-plugin-what\'s no-cleanup-reads-live reports a cleanup that reads what its run reads.',
526
+ codeExample: `import { useEffect } from 'what-framework';
527
+
528
+ // Bad - stop is made once: when roomId changes, it leaves the new room:
529
+ function ChatRoom({ roomId }) {
530
+ const stop = () => leave(roomId);
531
+ useEffect(() => {
532
+ join(roomId);
533
+ return stop;
534
+ });
535
+ return <h2>{roomId}</h2>;
536
+ }
537
+
538
+ // Good - a cleanup the effect returns sees the values of its run:
539
+ function ChatRoom({ roomId }) {
540
+ useEffect(() => {
541
+ join(roomId);
542
+ return () => leave(roomId);
543
+ });
544
+ return <h2>{roomId}</h2>;
545
+ }`,
546
+ },
547
+
548
+ DUPLICATE_KEY: {
549
+ code: 'ERR_DUPLICATE_KEY',
550
+ severity: 'warning',
551
+ template: 'A keyed list has more than one item with the key {{key}}.',
552
+ suggestion: 'Every item with that key still gets a row of its own, and none is lost or leaked, but rows that share a key can only be told apart by their order: when the list is reordered, one item can be handed another item\'s DOM, focus and component state. Key each item by a value that is unique within the list, such as its id. A list of plain values that may repeat needs no key at all: an unkeyed list tracks each value by position among its equals.',
553
+ codeExample: `// Bad — two todos can share a title:
554
+ {todos().map(todo => <li key={todo.title}>{todo.title}</li>)}
555
+
556
+ // Good — key by a unique id:
557
+ {todos().map(todo => <li key={todo.id}>{todo.title}</li>)}`,
558
+ },
559
+
560
+ SYMBOL_CHILD: {
561
+ code: 'ERR_SYMBOL_CHILD',
562
+ severity: 'warning',
563
+ template: 'A Symbol ({{symbol}}) is a child of <{{component}}>, which renders nothing for it ({{path}}).',
564
+ suggestion: 'A Symbol is not renderable. The server, the client and hydration all render nothing in its place, as for null, so the page shows a gap where a value was meant to be. The usual cause is a Symbol used as an enum value or a sentinel reaching JSX. Render a string for it instead: its description (sym.description), or a label looked up by it. Reported once for each component and Symbol, in development.',
565
+ codeExample: `// Bad — a Symbol status renders nothing:
566
+ const OPEN = Symbol('open');
567
+ function Status() {
568
+ const status = OPEN;
569
+ return <span>{status}</span>; // an empty span
570
+ }
571
+
572
+ // Good — render a label for it:
573
+ const OPEN = Symbol('open');
574
+ const LABELS = { [OPEN]: 'Open' };
575
+ function Status() {
576
+ const status = OPEN;
577
+ return <span>{LABELS[status]}</span>;
578
+ }`,
130
579
  },
131
580
 
132
581
  ASYNC_MIDDLEWARE: {
@@ -135,20 +584,20 @@ html\`<div>\${sanitizedContent}</div>\``,
135
584
  template: 'Route middleware must be synchronous; received a promise or thenable.',
136
585
  suggestion: 'Return true or void to continue, false to deny access, or a redirect path synchronously. Promises and thenables fail closed: the protected component never mounts, and their results are not awaited or used to authorize navigation. For async authorization, wrap the route component with asyncGuard(check)(Component), optionally passing fallback and loading options to asyncGuard.',
137
586
  codeExample: `// Bad - an async middleware result cannot authorize a route:
138
- { path: '/private', component: Component, middleware: [async () => check()] }
587
+ const routes = [{ path: '/private', component: Component, middleware: [async () => check()] }];
139
588
 
140
589
  // Good - the component wrapper waits for the authorization check:
141
- { path: '/private', component: asyncGuard(check)(Component) }
590
+ const routes = [{ path: '/private', component: asyncGuard(check)(Component) }];
142
591
 
143
592
  // Optional denial redirect and loading UI:
144
- { path: '/private', component: asyncGuard(check, { fallback: '/login', loading: Spinner })(Component) }`,
593
+ const Private = asyncGuard(check, { fallback: '/login', loading: Spinner })(Component);`,
145
594
  },
146
595
 
147
596
  UNSAFE_REDIRECT: {
148
597
  code: 'ERR_UNSAFE_REDIRECT',
149
598
  severity: 'error',
150
- template: 'redirect() refused an unsafe target: {{target}}.',
151
- suggestion: 'redirect() accepts same-origin paths and http:, https:, mailto: or tel: URLs only. Protocol-relative ("//host"), backslash-smuggled and javascript:/data: targets are open-redirect vectors. Check a user-supplied target against an allowlist first.',
599
+ template: 'redirect() refused an unsafe target: {{target}}',
600
+ suggestion: 'redirect() accepts same-origin paths and http:, https:, mailto: or tel: URLs only, in the browser and in a server render alike. Protocol-relative ("//host"), backslash-smuggled, javascript:/data: and credential-carrying ("https://trusted.example@evil.example") targets are open-redirect vectors. Check a user-supplied target against an allowlist first.',
152
601
  codeExample: `// Bad - a user-controlled target can leave your origin:
153
602
  redirect(query.next);
154
603
 
@@ -159,18 +608,226 @@ redirect(ALLOWED.has(query.next) ? query.next : '/');`,
159
608
  REDIRECT_NOT_CAUGHT: {
160
609
  code: 'ERR_REDIRECT_NOT_CAUGHT',
161
610
  severity: 'error',
162
- template: 'A redirect() to "{{target}}" surfaced uncaught, so nothing performed the navigation.',
163
- suggestion: 'redirect() is caught in route middleware and in a component body. From an event handler, a promise callback, a timer or a reactive thunk, call navigate(to) instead. If the call is inside a try/catch, rethrow anything whose name is RouterRedirect. On the server this signal escapes renderToString to its caller: read its `to` and emit a 302 rather than calling navigate().',
611
+ template: '[what-router] redirect to {{target}}',
612
+ suggestion: 'redirect() is caught in route middleware and in a component body, in the browser and in every server renderer, and in a server action. From an event handler, a promise callback, a timer or a reactive thunk, call navigate(to) instead. If the call is inside a try/catch, rethrow anything whose name is RouterRedirect. On the server the render answers it: its response redirects, below the base, so pass renderToString a response (createResponse()) and answer with its status and location, as the request handler does.',
164
613
  codeExample: `// Bad - a reactive thunk re-runs outside the render the Router caught:
165
614
  <div>{() => (loggedOut() ? redirect('/login') : <Dashboard />)}</div>
166
615
 
167
616
  // Good - navigate() from a thunk or a handler:
168
- <div>{() => (loggedOut() ? (navigate('/login'), null) : <Dashboard />)}</div>
169
- <button onclick={() => navigate('/login')}>Sign in</button>
617
+ <div>{() => (loggedOut() ? (navigate('/login'), null) : <Dashboard />)}</div>;
618
+ <button onclick={() => navigate('/login')}>Sign in</button>;
170
619
 
171
- // On the server, catch it instead of navigating:
172
- try { html = renderToString(<App />); }
173
- catch (e) { if (e.name === 'RouterRedirect') return Response.redirect(e.to, 302); throw e; }`,
620
+ // On the server, the render redirects the response it was given:
621
+ const response = createResponse();
622
+ const html = renderToString(<App />, { response });
623
+ if (response.location) res.writeHead(response.status, { location: response.location }).end();`,
624
+ },
625
+
626
+ REDIRECT_CYCLE: {
627
+ code: 'ERR_REDIRECT_CYCLE',
628
+ severity: 'error',
629
+ template: '[what-router] Redirect loop ({{kind}}): {{cycle}}. Guards of: {{guards}}.',
630
+ suggestion: 'Route middleware sent the navigation round in a loop, so the router stopped it and showed the redirect-loop screen. The cycle lists each hop as the pattern of the route it matched, in order (never the URL itself: a path segment, a query or a fragment may carry what the visitor sent), and a hop no route matches as (no route); the guards are the patterns of the routes whose middleware or component redirected. Make each guard a fixed point for the state it redirects to: a guard must let its own target through (the login page must not redirect a logged-out user to itself or back), and two guards must not send each other the same state.',
631
+ codeExample: `// Bad — a logged-in non-admin bounces between the two forever:
632
+ const routes = [
633
+ { path: '/login', component: Login, middleware: [() => !isLoggedIn() || '/dashboard'] },
634
+ { path: '/dashboard', component: Dashboard, middleware: [() => isAdmin() || '/login'] },
635
+ ];
636
+
637
+ // Good — the dashboard's guard sends a logged-in non-admin somewhere that lets them in:
638
+ const routes = [
639
+ { path: '/login', component: Login, middleware: [() => !isLoggedIn() || '/dashboard'] },
640
+ { path: '/dashboard', component: Dashboard, middleware: [() => isAdmin() || (isLoggedIn() ? '/account' : '/login')] },
641
+ ];`,
642
+ },
643
+
644
+ // --- Development checks in core ---
645
+ // Raised through diagnostics.js report(), so they reach devtools, the MCP
646
+ // bridge and what-framework/testing as coded events.
647
+
648
+ HOOK_OUTSIDE_COMPONENT: {
649
+ code: 'ERR_HOOK_OUTSIDE_COMPONENT',
650
+ severity: 'error',
651
+ template: '{{hookName}}() can only be called inside a component function. Did you call it outside of a component or in an async callback? If you need reactive state outside a component, use signal() directly.',
652
+ suggestion: 'A hook attaches its state to the component it belongs to, found through the current owner: the component body, or an effect, region or list row the component created. Code that runs later under no owner has no component: an event handler, a timer, anything after an await, module scope. What components run once, so call hooks at the top of the body, where each runs once. Outside a component use signal(), computed() and effect() directly; to use a context value in a callback, read it in the body and close over the result.',
653
+ codeExample: `import { onMount, useState } from 'what-framework';
654
+
655
+ // Bad - after the await nothing owns the call:
656
+ function Profile() {
657
+ onMount(async () => {
658
+ await Promise.resolve();
659
+ const [user, setUser] = useState(null); // throws
660
+ });
661
+ }
662
+
663
+ // Good - hooks at the top of the body, async work inside:
664
+ function Profile() {
665
+ const [user, setUser] = useState(null);
666
+ onMount(async () => setUser(await fetchUser()));
667
+ return <p>{() => user()?.name}</p>;
668
+ }`,
669
+ },
670
+
671
+ EFFECT_DEP_NOT_FUNCTION: {
672
+ code: 'ERR_EFFECT_DEP_NOT_FUNCTION',
673
+ severity: 'warning',
674
+ template: 'useEffect dependency at index {{index}} is a plain value, so the effect cannot re-run when it changes.',
675
+ suggestion: 'A dependency array lists signals and computeds, which the effect reads to track them. A value in the array is read once when the component runs and never changes, so the effect never re-runs for it. Pass the signal itself, not its current value; for a prop or any other expression, a computed over it (useMemo(() => props.count)). Omitting the array tracks whatever the effect reads.',
676
+ codeExample: `const [count, setCount] = useState(0);
677
+
678
+ // Bad - count() is read once, the array holds a number:
679
+ useEffect(() => save(count()), [count()]);
680
+
681
+ // Good - pass the signal:
682
+ useEffect(() => save(count()), [count]);
683
+
684
+ // Good - or let the effect track what it reads:
685
+ useEffect(() => save(count()));`,
686
+ },
687
+
688
+ EFFECT_DEP_NOT_SIGNAL: {
689
+ code: 'ERR_EFFECT_DEP_NOT_SIGNAL',
690
+ severity: 'warning',
691
+ // Short: the agents' index (skills/what-diagnostics) has a size limit.
692
+ template: 'useEffect dependency {{index}} is a function, never read.',
693
+ suggestion: 'A function in a dependency array that is not a signal or a computed is never called, so the effect cannot re-run for what it reads. A dependency array re-runs the effect for the signals and computeds in it. Any other function is left alone: a deps array often holds setters and callbacks ([setCount], [load], [props.onClose]), and calling one to see what it reads would write state or start work on every run. If this one is a getter, list a computed over the same expression (useMemo(() => props.count)), or omit the array so the effect tracks what its callback reads. If it is a callback, leave it out: a component runs once, so a callback never changes. A function that takes arguments is never reported.',
694
+ codeExample: `// Bad - the arrow is never called, so the effect runs once:
695
+ useEffect(() => save(props.count), [() => props.count]);
696
+
697
+ // Good - a computed is a signal:
698
+ const count = useMemo(() => props.count);
699
+ useEffect(() => save(count()), [count]);
700
+
701
+ // Good - or let the effect track what it reads:
702
+ useEffect(() => save(props.count));`,
703
+ },
704
+
705
+ CONTEXT_NOT_PROVIDED: {
706
+ code: 'ERR_CONTEXT_NOT_PROVIDED',
707
+ severity: 'warning',
708
+ template: '{{context}} was read with no provider above the component and has no default value, so useContext returned undefined.',
709
+ suggestion: 'createContext() called with no argument says the value must come from a provider. Render the reader inside <Ctx value={...}> (or <Ctx.Provider value={...}>), or pass createContext a default for the case with no provider. Set Ctx.displayName to name the context in this message.',
710
+ codeExample: `const Theme = createContext();
711
+ Theme.displayName = 'Theme';
712
+
713
+ // Bad - no provider above <Toolbar>:
714
+ mount(<Toolbar />, '#app');
715
+
716
+ // Good - provide a value:
717
+ mount(<Theme value="dark"><Toolbar /></Theme>, '#app');
718
+
719
+ // Good - or give the context a default:
720
+ const Theme = createContext('light');`,
721
+ },
722
+
723
+ CLEANUP_WITHOUT_OWNER: {
724
+ code: 'ERR_CLEANUP_WITHOUT_OWNER',
725
+ severity: 'warning',
726
+ template: 'onCleanup() was called outside a component and outside any reactive owner, so the cleanup never runs.',
727
+ suggestion: 'onCleanup attaches to the component being rendered, or else to the reactive owner around the call: createRoot, a list row, a mount root, or the run of an effect. Code that runs later has none of these: an async callback after an await, a timer, an event handler. Register the cleanup while the component body runs, before anything awaits. For a subscription outside any component, create it inside createRoot and keep the dispose function it passes you.',
728
+ codeExample: `// Bad - after the await nothing owns the call, so the cleanup never runs:
729
+ function Room({ id }) {
730
+ onMount(async () => {
731
+ const room = await joinRoom(id);
732
+ onCleanup(() => room.leave());
733
+ });
734
+ }
735
+
736
+ // Good - register the cleanup while the body runs, before anything awaits:
737
+ function Room({ id }) {
738
+ const joined = joinRoom(id);
739
+ onCleanup(() => joined.then((room) => room.leave()));
740
+ }`,
741
+ },
742
+
743
+ DERIVED_WITHOUT_STATE: {
744
+ code: 'ERR_DERIVED_WITHOUT_STATE',
745
+ severity: 'warning',
746
+ template: 'derived() for "{{key}}" takes no parameter, so it cannot read the store state.',
747
+ suggestion: 'createStore calls a derived function with the store state as its argument, and tracks the fields it reads through that argument. A function that declares no parameter reads nothing reactive and never updates.',
748
+ codeExample: `import { createStore, derived } from 'what-framework';
749
+
750
+ // Bad - the function takes no state, so it never updates:
751
+ const useCounter = createStore({ count: 0, doubled: derived(() => 0) });
752
+
753
+ // Good:
754
+ const useCounter = createStore({ count: 0, doubled: derived(state => state.count * 2) });`,
755
+ },
756
+
757
+ FORM_HANDLER_WITHOUT_EVENT: {
758
+ code: 'ERR_FORM_HANDLER_WITHOUT_EVENT',
759
+ severity: 'warning',
760
+ template: 'register("{{name}}") change handler was called without an event; the field was left unchanged.',
761
+ suggestion: 'The handler register() returns reads the new value from event.target. Pass the DOM event through, or set the value directly with form.setValue(name, value).',
762
+ codeExample: `// Bad - calls the handler with a value instead of an event:
763
+ const field = register('email');
764
+ field.onchange('a@b.co');
765
+
766
+ // Good:
767
+ <input {...register('email')} />
768
+ form.setValue('email', 'a@b.co');`,
769
+ },
770
+
771
+ FORM_RADIO_WITHOUT_VALUE: {
772
+ code: 'ERR_FORM_RADIO_WITHOUT_VALUE',
773
+ severity: 'warning',
774
+ template: 'Radio for field "{{name}}" has no value, so it cannot record a choice.',
775
+ suggestion: 'Radios in a group share one field that holds the selected option\'s value. A radio with no value attribute reports "on", which identifies nothing, so the registration ignores it. Give every radio a value.',
776
+ codeExample: `// Bad:
777
+ <Radio name="size" register={register} />
778
+
779
+ // Good:
780
+ <Radio name="size" value="small" register={register} />;
781
+ <input type="radio" {...register('size', { type: 'radio', value: 'small' })} />;`,
782
+ },
783
+
784
+ FORM_RADIO_UNTYPED: {
785
+ code: 'ERR_FORM_RADIO_UNTYPED',
786
+ severity: 'warning',
787
+ template: 'register("{{name}}") was spread onto a radio without { type: \'radio\' }, which overwrote the radio\'s value.',
788
+ suggestion: 'A plain registration binds the input\'s value to the field, which for a radio replaces the option it stands for. Tell the registration it is a radio and which value it contributes, or use <Radio>.',
789
+ codeExample: `// Bad:
790
+ <input type="radio" value="small" {...register('size')} />
791
+
792
+ // Good:
793
+ <input type="radio" {...register('size', { type: 'radio', value: 'small' })} />;
794
+ <Radio name="size" value="small" register={register} />;`,
795
+ },
796
+
797
+ STORAGE_FAILED: {
798
+ code: 'ERR_STORAGE_FAILED',
799
+ severity: 'warning',
800
+ template: 'useLocalStorage("{{key}}") could not {{operation}} localStorage: {{reason}}.',
801
+ suggestion: 'A write fails when the quota is exhausted or storage is disabled (private browsing); a read fails when the stored text is not valid JSON, usually because something else wrote that key. The signal keeps working in memory either way. Use a key no other code writes, and keep stored values small.',
802
+ codeExample: `// Good - a namespaced key and a small value:
803
+ const theme = useLocalStorage('myapp:theme', 'light');`,
804
+ },
805
+
806
+ PORTAL_TARGET_MISSING: {
807
+ code: 'ERR_PORTAL_TARGET_MISSING',
808
+ severity: 'warning',
809
+ template: '<Portal target="{{selector}}"> matched no element, so its children render nowhere.',
810
+ suggestion: 'A string target is a CSS selector, looked up when the portal is built: the element has to be in the document by then. Leave `target` out to render into document.body, pass an element (a ref, document.getElementById), or put the container in the page before the component that holds the portal.',
811
+ codeExample: `// Bad - #modal-root is not in the page:
812
+ <Portal target="#modal-root"><Dialog /></Portal>
813
+
814
+ // Good - no target renders into document.body:
815
+ <Portal><Dialog /></Portal>`,
816
+ },
817
+
818
+ MOUNT_TARGET_MISSING: {
819
+ code: 'ERR_MOUNT_TARGET_MISSING',
820
+ severity: 'error',
821
+ template: '{{fn}}() got no container element.',
822
+ suggestion: 'mount() and hydrate() render into an element that is in the page when they run: pass the element, or a CSS selector that matches one. The full-page document what-server renders (renderDocument, createRequestHandler, the scaffold) puts the route directly under <body> with no wrapper of its own, so its client hydrates document.body. Use a selector such as #app only where the page writes that element itself.',
823
+ codeExample: `// Bad - the built-in document has no #app wrapper:
824
+ hydrate(<App />, document.getElementById('app'));
825
+
826
+ // Good - the built-in document:
827
+ hydrate(<App />, document.body);
828
+
829
+ // Good - a page that writes <div id="app"> itself:
830
+ hydrate(<App />, '#app');`,
174
831
  },
175
832
 
176
833
  // --- Outside core ---
@@ -202,7 +859,7 @@ catch (e) { if (e.name === 'RouterRedirect') return Response.redirect(e.to, 302)
202
859
  NO_SECURE_RANDOM: {
203
860
  code: 'ERR_NO_SECURE_RANDOM',
204
861
  severity: 'error',
205
- template: '[what] No secure random source available for CSRF token generation.',
862
+ template: 'No secure random source available for CSRF token generation.',
206
863
  suggestion: 'Neither globalThis.crypto.getRandomValues nor node:crypto was reachable. On Node this means a build older than 18 or a bundler that stripped node:crypto; on an edge runtime it means the Web Crypto global was not provided. A CSRF token from Math.random is not a token, so this refuses rather than degrading.',
207
864
  codeExample: `// Node 18+ exposes Web Crypto globally; nothing to configure.
208
865
  // If a bundler dropped it, restore the global before creating the server:
@@ -210,11 +867,33 @@ import { webcrypto } from 'node:crypto';
210
867
  globalThis.crypto ??= webcrypto;`,
211
868
  },
212
869
 
870
+ PAYLOAD_TOO_LARGE: {
871
+ code: 'ERR_PAYLOAD_TOO_LARGE',
872
+ severity: 'error',
873
+ template: 'A call over the {{limit}}-byte bodyLimit was refused.',
874
+ suggestion: 'The action call\'s body (every field and file in it) was over the server\'s bodyLimit (1 MB by default), so the server answered 413 and ran nothing. The error carries `status` 413 and `limit`, the bytes allowed (none when a proxy or the platform answered the 413 itself: its message then says the server accepts less). Raise bodyLimit for uploads, check a file\'s size before the form is sent (setCustomValidity on the file input keeps the form and tells the visitor), and show the error in an <ErrorBoundary> around the component whose useActionState dispatched the action, which a throwing action reaches. Without JavaScript the visitor gets the server\'s 413 page, which names the limit.',
875
+ codeExample: `// Good - refuse a file over the limit before the form is sent:
876
+ const MAX_UPLOAD = 1_000_000; // the server's bodyLimit, less room for the other fields
877
+ const avatar = <input type="file" name="avatar" onChange={(e) => {
878
+ const file = e.target.files[0];
879
+ e.target.setCustomValidity(file && file.size > MAX_UPLOAD ? 'Choose a file under 1 MB' : '');
880
+ }} />;
881
+
882
+ // Good - and the error reaches a boundary around the component whose
883
+ // useActionState dispatched the action:
884
+ const page = <ErrorBoundary fallback={({ error, reset }) => (
885
+ <p role="alert">{error.code === 'ERR_PAYLOAD_TOO_LARGE' && error.limit !== undefined ? \`Too large: the limit is \${error.limit} bytes.\` : error.message}
886
+ <button onClick={reset}>Try again</button></p>
887
+ )}>
888
+ <Signup />
889
+ </ErrorBoundary>;`,
890
+ },
891
+
213
892
  ACTION_FAILED: {
214
893
  code: 'ERR_ACTION_FAILED',
215
894
  severity: 'error',
216
895
  template: '{{message}}',
217
- suggestion: 'The server action rejected. The message is the one the action threw, forwarded to the client by the action handler. Throw a typed error from the action and branch on its shape rather than parsing this string.',
896
+ suggestion: 'The server action rejected. The server refused the call or the action threw: `status` is the response\'s (403 for a CSRF check, 404 for an action it does not have, 400 for arguments it cannot read, 500 for a throw), and the message is the one the action threw, forwarded to the client by the action handler. Throw a typed error from the action and branch on its shape rather than parsing this string; a body over bodyLimit is ERR_PAYLOAD_TOO_LARGE.',
218
897
  codeExample: `// In the action, fail with something the client can read:
219
898
  export const save = action(async (data) => {
220
899
  if (!data.email) throw Object.assign(new Error('Email required'), { field: 'email' });
@@ -224,13 +903,15 @@ export const save = action(async (data) => {
224
903
  STATIC_WRITE_ESCAPE: {
225
904
  code: 'ERR_STATIC_WRITE_ESCAPE',
226
905
  severity: 'error',
227
- template: '[what-server] Refusing to write outside outDir: {{path}}.',
906
+ template: '[what-server] Refusing to write outside outDir: {{path}}',
228
907
  suggestion: 'A route path resolved to a location outside the export directory, which a "../" segment in a route or a param can do. Sanitize the route path, or drop the route from the static export.',
229
- codeExample: `// Bad — a param that can contain a slash escapes outDir:
230
- { path: '/docs/:slug*', mode: 'static' }
908
+ codeExample: `// Bad — a slug from the CMS such as '../../x' resolves outside outDir:
909
+ const docs = { path: '/docs/:slug', mode: 'static', component: Doc,
910
+ getStaticPaths: () => ({ paths: slugs.map((slug) => ({ params: { slug } })) }) };
231
911
 
232
- // Good — constrain the param, or precompute the exact paths:
233
- { path: '/docs/:slug', mode: 'static', paths: () => slugs.map(slug => ({ slug })) }`,
912
+ // Good — export only slugs that are one safe path segment:
913
+ const docs = { path: '/docs/:slug', mode: 'static', component: Doc,
914
+ getStaticPaths: () => ({ paths: slugs.filter((s) => /^[a-z0-9-]+$/.test(s)).map((slug) => ({ params: { slug } })) }) };`,
234
915
  },
235
916
 
236
917
  INVALID_HTML_NESTING: {
@@ -242,74 +923,296 @@ export const save = action(async (data) => {
242
923
  <p>Intro<div>{body()}</div>Outro</p>
243
924
 
244
925
  // Good — a block container can hold block content:
245
- <div class="prose">Intro<div>{body()}</div>Outro</div>
926
+ <div class="prose">Intro<div>{body()}</div>Outro</div>;
246
927
 
247
928
  // Good — or keep the paragraph and use phrasing content:
248
- <p>Intro<span>{body()}</span>Outro</p>`,
929
+ <p>Intro<span>{body()}</span>Outro</p>;`,
930
+ },
931
+
932
+ TEMPLATE_NAMESPACE: {
933
+ code: 'ERR_TEMPLATE_NAMESPACE',
934
+ severity: 'error',
935
+ template: 'The compiled template for <{{tag}}> has no namespace flag, so its root would render as an unknown HTML element instead of SVG or MathML.',
936
+ suggestion: 'what-compiler marks every template whose root is an SVG or MathML element other than <svg> and <math>, and the runtime parses it in that namespace; the runtime no longer guesses the namespace from the tag. A template without the mark comes from a what-compiler older than the runtime, usually a library that ships precompiled output. Compiler and runtime versions move together: recompile the module with the what-compiler release that matches what-framework, and have a library declare what-framework at its own minor version as a peer dependency.',
937
+ codeExample: `// Bad — output of what-compiler 0.14, loaded by a newer runtime:
938
+ const _tmpl$0 = _$template("<circle r='1'></circle>");
939
+
940
+ // Good — the same component recompiled by the matching what-compiler:
941
+ const _tmpl$0 = _$template("<svg><circle r='1'></circle></svg>", 2);`,
942
+ },
943
+
944
+ COMPILER_RUNTIME_MISMATCH: {
945
+ code: 'ERR_COMPILER_RUNTIME_MISMATCH',
946
+ severity: 'error',
947
+ template: 'what-compiler {{compiler}} cannot build for {{name}} {{version}} ({{file}}).',
948
+ suggestion: 'what-compiler\'s output imports the runtime helpers of its own release, so a build needs what-compiler, what-framework and what-core of one release. npm refuses an install that mixes them (each declares the others as peers at its release), so a mixed install comes from one that skipped peer checks: --legacy-peer-deps, --force, or a package manager that only warns. what-compiler/vite and the Babel plugin check the installed versions before they compile and stop with this error. Move every What package to one release in one install, as step 1 of "Before you start" in UPGRADING.md says.',
949
+ codeExample: `// Bad — the compiler upgraded alone, peer checks skipped:
950
+ // npm install -D what-compiler@latest --legacy-peer-deps
951
+ // what-compiler 0.15.0 beside what-framework 0.14.0: the build stops here
952
+
953
+ // Good — every What package in one install, at one release:
954
+ // npm install what-framework@0.15.0 what-compiler@0.15.0`,
955
+ },
956
+
957
+ HOT_UPDATE_FAILED: {
958
+ code: 'ERR_HOT_UPDATE_FAILED',
959
+ severity: 'error',
960
+ template: 'The edit to {{file}} was not applied: {{phase}} threw "{{message}}". The page keeps running the code it had before the edit.',
961
+ suggestion: 'Fix what the error says (Vite\'s overlay shows it, with its stack) and save again: the next save that compiles and runs replaces the changed components in place, without a reload. A compile error stops the edit before any of it runs; a throw while the new module runs, or while a changed component renders its new code, leaves every instance on the page as it was, with its state.',
962
+ codeExample: `// Bad — saved with a typo: <Counter>'s new code throws when it renders,
963
+ // and the page keeps the <Counter> it had:
964
+ export function Counter() {
965
+ const count = signal(0);
966
+ return <button onClick={() => count((c) => c + 1)}>{cuont()}</button>;
967
+ }
968
+
969
+ // Good — the next save renders, and replaces <Counter> where it stands:
970
+ export function Counter() {
971
+ const count = signal(0);
972
+ return <button onClick={() => count((c) => c + 1)}>{count()}</button>;
973
+ }`,
974
+ },
975
+
976
+ NO_VNODE_RENDERER: {
977
+ code: 'ERR_NO_VNODE_RENDERER',
978
+ severity: 'error',
979
+ template: '{{what}} reached the compiled-JSX runtime, but no vnode renderer is installed.',
980
+ suggestion: 'Compiled JSX builds DOM directly, so a program that only uses compiled JSX leaves the vnode renderer out of its bundle, and something handed the runtime a vnode anyway. The producers that make vnodes install the renderer as they do (h, Fragment and html from what-framework, the automatic JSX runtime, and the components that return vnodes: ErrorBoundary, Suspense, Portal, lazy, Island), so the vnode came from the compiled-JSX runtime itself: the form what-compiler gives JSX handed to hydrate(), passed somewhere else. Write the JSX where it is used. An object built by hand in the { tag, props, children } shape is not a vnode (vnodes carry a brand only those producers give) and renders as its text instead.',
981
+ codeExample: `// Bad — the compiled form of <App /> for hydrate(), given to mount():
982
+ import { mount } from 'what-framework';
983
+ import { _$componentVNode } from 'what-framework/render';
984
+
985
+ const App = () => <p>Hello</p>;
986
+ mount(_$componentVNode(App, null, []), document.body);
987
+
988
+ // Good — mount the JSX itself, which the compiler builds directly:
989
+ import { mount } from 'what-framework';
990
+
991
+ const App = () => <p>Hello</p>;
992
+ mount(<App />, document.body);`,
249
993
  },
250
994
 
251
995
  INVALID_SSR_TAG: {
252
996
  code: 'ERR_INVALID_SSR_TAG',
253
997
  severity: 'error',
254
- template: '[what-server] Invalid tag name in SSR: {{tag}}.',
255
- suggestion: 'renderToString reached a vnode whose tag is neither a string nor a component function. This is almost always a component that returned a raw object, or a value interpolated where an element was expected.',
256
- codeExample: `// Bad — returns a plain object, not a vnode:
257
- function Row() { return { name: 'a' }; }
998
+ template: 'Invalid tag name in SSR: "{{tag}}"',
999
+ suggestion: 'A server renderer reached a vnode whose tag is neither an element name nor a component function: h() was given a tag built from data (one with a space, a quote or a "<" in it), or a value that is not a string or a function. Choose the tag from the ones you allow. A component that returns a plain object is not this error: an object that is not a vnode renders as its text.',
1000
+ codeExample: `// Bad — the tag is built from data, and is not an element name:
1001
+ function Heading({ level }) {
1002
+ return h(\`h\${level} class="big"\`, {}, 'Title');
1003
+ }
258
1004
 
259
- // Good — return elements, and interpolate values as children:
260
- function Row({ name }) { return <li>{name}</li>; }`,
1005
+ // Good — choose the tag from the ones you allow:
1006
+ const TAGS = { 1: 'h1', 2: 'h2', 3: 'h3' };
1007
+ function Heading({ level }) {
1008
+ return h(TAGS[level] || 'h2', { class: 'big' }, 'Title');
1009
+ }`,
261
1010
  },
262
1011
 
263
1012
  COMPILED_JSX_IN_SSR: {
264
1013
  code: 'ERR_COMPILED_JSX_IN_SSR',
265
1014
  severity: 'error',
266
- template: 'what-compiler output cannot be server-rendered: {{file}}.',
267
- suggestion: 'what-compiler lowers JSX to module-scope _$template() calls that run document.createElement() at import time, and to _$createComponent() which builds DOM. Neither has a server-rendered form, so a module it compiled throws "document is not defined" when a server imports it. Server-rendered views have two supported spellings: author them with h(), or compile them with the automatic JSX runtime (jsxImportSource: "what-framework"), which emits h() calls that renderToString understands. what-compiler stays on the client entry, where the fine-grained output is the point.',
268
- codeExample: `// Bad — a server module compiled by what-compiler:
269
- // vite.config.js: plugins: [what()] + vite build --ssr
270
- export function Page() { return <h1>Hi</h1>; } // throws on import
1015
+ template: 'what-compiler client output cannot be server-rendered: {{file}}.',
1016
+ suggestion: 'what-compiler has two targets. Its client output lowers JSX to _$template() calls, which parse their markup with document.createElement() the first time a template is used, and to _$createComponent(), which builds DOM, so it has no server-rendered form. Its server target (generate: "ssr") lowers the same JSX to string templates that what-server renders. The Vite plugin compiles server transforms with the server target unless the project sets ssr: false, which is when this error is raised for a module that builds DOM; at render time it means a module compiled for the client reached a server renderer. Remove ssr: false, or author the view with h(), or compile it with the automatic JSX runtime (jsxImportSource: "what-framework").',
1017
+ codeExample: `// Bad — server transforms compiled as client output:
1018
+ // vite.config.js: plugins: [what({ ssr: false })] + vite build --ssr
1019
+ export function Page() { return <h1>Hi</h1>; } // refused at build time
1020
+
1021
+ // Good — the default: server transforms use the server target:
1022
+ // vite.config.js: plugins: [what()]
1023
+ export function Page() { return <h1>Hi</h1>; } // renders on the server
271
1024
 
272
- // Good — h(), which renderToString understands:
1025
+ // Good — or h(), which renderToString understands:
273
1026
  import { h } from 'what-framework';
274
- export function Page() { return h('h1', null, 'Hi'); }
1027
+ export function Title() { return h('h1', null, 'Hi'); }`,
1028
+ },
1029
+
1030
+ FOREIGN_ENGINE_IN_SSR: {
1031
+ code: 'ERR_FOREIGN_ENGINE_IN_SSR',
1032
+ severity: 'error',
1033
+ template: 'An async value was made by a second copy of what-core during a server render.',
1034
+ suggestion: 'The page is server-rendered by one copy of what-core, and a component made a resource, a query or another async value with a different copy: usually a library that bundled what-framework into its own build instead of declaring it as a peer dependency. A second copy never joins the render, so its value would start over on every retry of the render and never reach the client; the render fails instead. Bundle one copy: mark what-framework (and what-core) external in the library\'s build and list it under peerDependencies, or dedupe the install (npm ls what-core shows each copy). Effects and computeds of a second copy are still owned by the render and disposed with it.',
1035
+ codeExample: `// Bad — a library's vite.config.js bundles what-framework into dist/index.js:
1036
+ export default defineConfig({ build: { lib: { entry: 'src/index.js' } } });
1037
+
1038
+ // Good — the library leaves the framework to the app (and lists it in peerDependencies):
1039
+ export default defineConfig({
1040
+ build: {
1041
+ lib: { entry: 'src/index.js' },
1042
+ rollupOptions: { external: [/^what-framework/, /^what-core/] },
1043
+ },
1044
+ });`,
1045
+ },
1046
+
1047
+ SECOND_CORE_COPY: {
1048
+ code: 'ERR_SECOND_CORE_COPY',
1049
+ severity: 'warning',
1050
+ template: 'A second copy of what-core is running on this page.',
1051
+ suggestion: 'Two copies of what-core loaded into one page, usually a component library that bundled what-framework into its own build beside the app\'s. Their delegated events share one listener, so each handler runs once, but nothing else is shared: a context one copy provides is not found by components of the other, flushSync() and batch() of one do not reach the other\'s effects, and the page downloads the framework twice. Keep one copy: the library marks what-framework (and what-core) external in its build and lists it under peerDependencies, and the app dedupes the install (Vite\'s resolve.dedupe: [\'what-framework\', \'what-core\'], or npm ls what-core to find each copy). Reported in development once for each copy after the first, when it first delegates an event: by that copy, or, for a production build, by a development copy loaded before it.',
1052
+ codeExample: `// Bad — a library's vite.config.js bundles what-framework into dist/index.js:
1053
+ export default defineConfig({ build: { lib: { entry: 'src/index.js' } } });
1054
+
1055
+ // Good — the library leaves the framework to the app (and lists it in
1056
+ // peerDependencies); the app keeps one copy with
1057
+ // resolve: { dedupe: ['what-framework', 'what-core'] } in its own config:
1058
+ export default defineConfig({
1059
+ build: {
1060
+ lib: { entry: 'src/index.js' },
1061
+ rollupOptions: { external: [/^what-framework/, /^what-core/] },
1062
+ },
1063
+ });`,
1064
+ },
1065
+
1066
+ UNSAFE_STATIC_MARKUP: {
1067
+ code: 'ERR_UNSAFE_STATIC_MARKUP',
1068
+ severity: 'error',
1069
+ template: 'Refused unsafe static markup: {{message}}',
1070
+ suggestion: 'what-compiler writes static tags, attributes and text straight into markup (the DOM target\'s template strings, which the browser parses, and the server target\'s string templates), so it checks them when the module is compiled, by the same rules the runtime applies to a value on every path: a URL attribute (href, src, action, formaction, data, ping, xlink:href) must not use a javascript:, vbscript: or data: scheme, srcdoc and outerHTML are never written because escaping cannot make markup safe, innerHTML or dangerouslySetInnerHTML take { __html: trustedString }, never a string, the text of a <script> cannot contain "</" or "<!--" and that of a <style> cannot contain "</", and a tag cannot be a namespaced name such as <svg:rect>. The server target also checks that a tag or attribute name can be emitted verbatim. Fix the value in the source; a dynamic value is still checked at run time.',
1071
+ codeExample: `// Bad — each of these fails the build:
1072
+ <a href="javascript:void 0">Open</a>;
1073
+ <iframe srcdoc="<p>hi</p>" />;
1074
+ <div innerHTML="<b>raw</b>" />;
1075
+ <script>{"document.write('</p>')"}</script>;
1076
+ <svg:rect />;
1077
+
1078
+ // Good:
1079
+ <button type="button" onClick={open}>Open</button>;
1080
+ <iframe src="/preview.html" />;
1081
+ <div innerHTML={{ __html: trustedHtml }} />;
1082
+ <script>{"document.write('<\\\\/p>')"}</script>;
1083
+ <svg><rect /></svg>;`,
1084
+ },
1085
+
1086
+ JSX_ISLAND_PROP: {
1087
+ code: 'ERR_JSX_ISLAND_PROP',
1088
+ severity: 'error',
1089
+ template: 'An island prop holds JSX: {{message}}',
1090
+ suggestion: 'An island\'s props are serialized to JSON so the browser can hydrate it, and markup is not data: JSX in a prop would arrive as an empty object, or as a plain object pretending to be an element. what-compiler refuses it on both targets. Pass the markup as a child of the island, which renders on the server and hydrates with it, or pass the data and build the markup inside the island. A function prop (a render prop) is fine: functions are left out of the JSON, and the island makes its own when it hydrates.',
1091
+ codeExample: `// Bad — the icon would reach the browser as {}:
1092
+ <Chart client:load icon={<StarIcon />} />;
1093
+
1094
+ // Good — markup as a child:
1095
+ <Chart client:load><StarIcon /></Chart>;
1096
+
1097
+ // Good — data, and the markup built inside the island:
1098
+ <Chart client:load icon="star" />;`,
1099
+ },
275
1100
 
276
- // Good — the automatic JSX runtime for the server build:
277
- // vite.config.js (server): esbuild: { jsx: 'automatic',
278
- // jsxImportSource: 'what-framework' }
279
- export function Page() { return <h1>Hi</h1>; } // lowers to h()`,
1101
+ SSR_SUSPENSE_TIMEOUT: {
1102
+ code: 'ERR_SSR_SUSPENSE_TIMEOUT',
1103
+ severity: 'error',
1104
+ template: '[what-server] A resource was still pending after 12 attempts during streaming SSR.',
1105
+ suggestion: 'A resource or async component inside <Suspense> never settled while the page streamed, so the renderer stopped waiting for it. Make every fetcher resolve or reject, or give it a timeout so that it does. The boundary keeps its fallback in the streamed HTML, and the client renders the boundary itself.',
1106
+ codeExample: `// Bad — a fetch with no bound can leave the boundary waiting forever:
1107
+ const [posts] = createResource(() => fetch(API).then((r) => r.json()));
1108
+
1109
+ // Good — a timeout, so the fetcher settles either way:
1110
+ const [posts] = createResource(() =>
1111
+ fetch(API, { signal: AbortSignal.timeout(5000) }).then((r) => r.json()));`,
280
1112
  },
281
1113
 
282
- FORM_ACTION_NOT_REGISTERED: {
283
- code: 'ERR_FORM_ACTION_NOT_REGISTERED',
1114
+ LATE_REDIRECT: {
1115
+ code: 'ERR_LATE_REDIRECT',
284
1116
  severity: 'error',
285
- template: '[what] <Form action={fn}>: that function is not a server action.',
286
- suggestion: 'Wrap it with action() from what-server, or pass the action id as a string. A plain function has no id, so there is nothing for the form post to address.',
287
- codeExample: `// Bad — a plain function:
288
- async function save(data) {}
289
- <Form action={save} />
1117
+ template: '[what-server] redirect({{location}}) after the shell was sent needs an inline script, and this stream has noScripts.',
1118
+ suggestion: 'Once the shell is sent, the status line has gone out, so a redirect from a streamed boundary can only be made by an inline script that navigates. With noScripts the stream may not write one, and the redirect is dropped. Redirect from the loader, or from anything that runs before the shell is sent, so the response is a real 3xx; or allow the script with a nonce instead of noScripts.',
1119
+ codeExample: `// Bad — a redirect from inside a streamed <Suspense>, with noScripts:
1120
+ function Account() {
1121
+ const [user] = createResource(loadUser);
1122
+ if (!user()) getResponse().redirect('/login');
1123
+ return <p>{() => user()?.name}</p>;
1124
+ }
1125
+ renderDocumentStream(page, req, { noScripts: true });
290
1126
 
291
- // Good — a registered action:
292
- export const save = action(async (data) => {});
293
- <Form action={save} />`,
1127
+ // Good — redirect from the loader, before the shell: a real 3xx:
1128
+ export async function loader({ request, response }) {
1129
+ if (!(await loadSession(request))) response.redirect('/login', 302);
1130
+ }
1131
+
1132
+ // Good — or let the stream write the one script, under a CSP nonce:
1133
+ renderDocumentStream(page, req, { nonce });`,
1134
+ },
1135
+
1136
+ SSR_UNSAFE_REDIRECT: {
1137
+ code: 'ERR_SSR_UNSAFE_REDIRECT',
1138
+ severity: 'warning',
1139
+ template: '[what-server] {{method}}: refusing unsafe redirect target {{target}}; redirecting to {{root}} instead. (ERR_SSR_UNSAFE_REDIRECT)',
1140
+ suggestion: 'A server response redirect(), from a loader\'s `response` or from getResponse(), takes a same-origin path only ("/account?tab=2"), by the same rule as the action handler\'s _redirect field. An absolute URL, "//host", "/\\host" or javascript: is refused, because a loader that redirects to request data (`?next=`) would otherwise be an open redirect; the response goes to the app\'s root ("/", or "/app/" below a base) instead of failing the request. To send the visitor off the site on purpose, call redirectExternal(url), which takes an absolute http(s) URL with no credentials, or a mailto: or tel: URL.',
1141
+ codeExample: `// Bad — an absolute URL through redirect() is refused:
1142
+ export function loader({ query, response }) {
1143
+ response.redirect(query.next); // ?next=https://evil.example -> "/"
1144
+ }
1145
+
1146
+ // Good — a local path from request data, checked by redirect() itself,
1147
+ // and leaving the site explicitly:
1148
+ export function loader({ query, response }) {
1149
+ if (query.billing) response.redirectExternal('https://billing.example.com/portal');
1150
+ else response.redirect(query.next ?? '/'); // "/account" is kept
1151
+ }`,
1152
+ },
1153
+
1154
+ SSR_INVALID_ID_PREFIX: {
1155
+ code: 'ERR_SSR_INVALID_ID_PREFIX',
1156
+ severity: 'error',
1157
+ template: 'idPrefix {{idPrefix}} is not a letter followed by letters, digits, "_" or "-".',
1158
+ suggestion: 'The streaming renderer writes idPrefix into element ids, comments and an inline script, so it is validated rather than escaped: a letter, then letters, digits, "_" or "-". It only needs to differ between streams on one page; every stream already adds a random part after it.',
1159
+ codeExample: `// Bad — characters that would end the attribute or the comment:
1160
+ renderToStream(app, { idPrefix: 'side"bar' });
1161
+
1162
+ // Good:
1163
+ renderToStream(app, { idPrefix: 'sidebar' });`,
1164
+ },
1165
+
1166
+ SSR_LATE_HEAD: {
1167
+ code: 'ERR_SSR_LATE_HEAD',
1168
+ severity: 'warning',
1169
+ template: '[what-server] <Head> inside a streamed <Suspense> (boundary {{boundaryId}}) set head tags after the shell was sent.',
1170
+ suggestion: 'A streamed document sends its <head> with the shell. Tags a <Head> sets inside a <Suspense> that streams later travel with that boundary and are applied to document.head by script (or by applyStreamedBoundaries() with noScripts), so the page gets them, but the HTML <head> does not carry them and a crawler that runs no scripts does not see them. Set the title and meta from data the shell already has (the loader\'s), or render the route buffered (page.stream: false), to have them in the server HTML.',
1171
+ codeExample: `// Bad for crawlers — the title waits for a streamed resource:
1172
+ function Post() {
1173
+ const [post] = createResource(loadPost, { key: 'post' });
1174
+ return <><Head title={post().title} /><h1>{post().title}</h1></>;
1175
+ }
1176
+
1177
+ // Good — the loader has the title before the shell is sent:
1178
+ export const loader = ({ params }) => loadPostMeta(params.id);
1179
+ function Page({ loaderData }) {
1180
+ return <><Head title={loaderData.title} /><Suspense fallback="..."><Post /></Suspense></>;
1181
+ }`,
294
1182
  },
295
1183
 
296
1184
  FORM_ACTION_MISSING: {
297
1185
  code: 'ERR_FORM_ACTION_MISSING',
298
1186
  severity: 'error',
299
- template: '[what] <Form> requires an `action` prop: a server action or its id.',
300
- suggestion: 'Pass the action itself, or the string id it was registered under.',
1187
+ template: '<Form> requires an `action` prop: a server action, its id, or a function.',
1188
+ suggestion: 'Pass the server action itself, the string id it was registered under, or a client action such as the dispatch useActionState returns.',
301
1189
  codeExample: `// Bad:
302
1190
  <Form method="post" />
303
1191
 
304
1192
  // Good:
305
- <Form action={save} />
306
- <Form action="save-user" />`,
1193
+ <Form action={save} />;
1194
+ <Form action="save-user" />;`,
1195
+ },
1196
+
1197
+ ISLAND_WITHOUT_NAME: {
1198
+ code: 'ERR_ISLAND_WITHOUT_NAME',
1199
+ severity: 'warning',
1200
+ template: 'Island <{{component}}> has no `name`: a minified build renames its function, so the server and the browser name the island differently.',
1201
+ suggestion: 'what-compiler names a `client:*` island by its tag as written (`<Counter client:idle />` is "Counter"). An island written by hand, `h(_$Island, { component: Counter })`, takes its function\'s name instead, which a minifier renames in one bundle and not the other: the server marks the island "Counter" and the browser calls it "a", in its `data-island` attribute and in the `island:hydrated` event\'s `detail.name`. Pass `name`, the same string in both builds, or write the island as `<Counter client:idle />`. Reported in development only.',
1202
+ codeExample: `// Bad — a minified browser bundle renames Counter:
1203
+ h(_$Island, { component: Counter, mode: 'idle' });
1204
+
1205
+ // Good — a name both builds share:
1206
+ h(_$Island, { component: Counter, name: 'Counter', mode: 'idle' });
1207
+
1208
+ // Good — the compiler names it by its tag:
1209
+ <Counter client:idle />;`,
307
1210
  },
308
1211
 
309
1212
  ISLAND_STORE_OUTSIDE_RENDER: {
310
1213
  code: 'ERR_ISLAND_STORE_OUTSIDE_RENDER',
311
1214
  severity: 'error',
312
- template: '[what-server] Island store "{{name}}" was accessed outside an active server render.',
1215
+ template: 'Island store "{{name}}" was accessed outside an active server render.',
313
1216
  suggestion: 'A module-scoped island store resolves against the current request, so it can only be read or written from a component rendered by renderDocument/renderPage. Reading one at module scope, or from a background task, has no request to bind to.',
314
1217
  codeExample: `// Bad — runs at import time, with no request in scope:
315
1218
  const count = cart.items.length;
@@ -318,10 +1221,25 @@ const count = cart.items.length;
318
1221
  function Cart() { return <span>{cart.items.length}</span>; }`,
319
1222
  },
320
1223
 
1224
+ QUERY_OUTSIDE_RENDER: {
1225
+ code: 'ERR_QUERY_OUTSIDE_RENDER',
1226
+ severity: 'warning',
1227
+ template: '[what] Server query cache used outside a render, loader or action.',
1228
+ suggestion: 'On the server, each render, loader and server action has a query cache of its own, so one request\'s data never answers another. Code outside them (module scope, a timer, a background task, or code after an await on a runtime without AsyncLocalStorage) has no request to bind to, and a cache every request shared would hand one user\'s data to the next. So prefetchQuery, setQueryData, getQueryData and query() there get an empty cache of their own. Call them in a loader, an action or a component the server renders. On an edge runtime, enable AsyncLocalStorage (Cloudflare Workers: the nodejs_compat flag).',
1229
+ codeExample: `// Bad: runs at import time, with no request in scope.
1230
+ prefetchQuery(['config'], loadConfig);
1231
+
1232
+ // Good: in the loader, which runs in the request's render.
1233
+ export async function loader() {
1234
+ await prefetchQuery(['config'], loadConfig);
1235
+ return null;
1236
+ }`,
1237
+ },
1238
+
321
1239
  ISR_MISSING_CLIENT: {
322
1240
  code: 'ERR_ISR_MISSING_CLIENT',
323
1241
  severity: 'error',
324
- template: '[what-isr] createRedisStore requires { client }.',
1242
+ template: '[what-isr] createRedisStore requires { client }',
325
1243
  suggestion: 'what-isr ships no Redis driver on purpose, so the client is injected. Pass an ioredis or node-redis instance (get/set/del/sadd/srem/smembers, optionally expire/scan/keys).',
326
1244
  codeExample: `import Redis from 'ioredis';
327
1245
  const store = createRedisStore({ client: new Redis(process.env.REDIS_URL) });`,
@@ -347,8 +1265,8 @@ cacheKey({ path, vary: { 'cookie:session': sessionId } });`,
347
1265
  severity: 'error',
348
1266
  template: '[what-isr] route declares `vary` but the adapter supplied no request headers; refusing to cache.',
349
1267
  suggestion: 'The route varies its output per header, and the adapter called the engine without them. Caching anyway would serve one variant to every request. Forward the request headers from the adapter into the engine call.',
350
- codeExample: `// In the adapter:
351
- await engine.handle(routeMatch, { headers: request.headers });`,
1268
+ codeExample: `// In the adapter, the route match carries the request headers:
1269
+ await engine.handle({ ...routeMatch, headers: request.headers });`,
352
1270
  },
353
1271
 
354
1272
  DUPLICATE_ACTION_ID: {
@@ -356,11 +1274,14 @@ await engine.handle(routeMatch, { headers: request.headers });`,
356
1274
  severity: 'error',
357
1275
  template: 'Duplicate server action ID "{{id}}".',
358
1276
  suggestion: 'Action ids are the wire address of a server action, so two actions cannot share one. Ids derive from the file path and export name, so this usually means the same action is being registered twice, or an explicit id was reused.',
359
- codeExample: `// Bad — two actions pinned to the same id:
1277
+ codeExample: `import { action } from 'what-framework/server';
1278
+
1279
+ // Bad — two actions pinned to the same id:
360
1280
  export const save = action(fn, { id: 'save' });
361
1281
  export const store = action(fn, { id: 'save' });
362
1282
 
363
1283
  // Good — let ids derive, or make them distinct:
1284
+ import { action } from 'what-framework/server';
364
1285
  export const save = action(fn);
365
1286
  export const store = action(fn, { id: 'store-user' });`,
366
1287
  },
@@ -387,6 +1308,47 @@ import { reactCompat } from 'what-react/vite';
387
1308
  export default { plugins: [reactCompat()] };`,
388
1309
  },
389
1310
 
1311
+ NOT_TRANSLATED: {
1312
+ code: 'ERR_NOT_TRANSLATED',
1313
+ severity: 'warning',
1314
+ template: '[what-react] <{{component}}> stays a React component on what-react: {{reason}}.',
1315
+ suggestion: 'With `reactCompat({ translate: true })`, the function components of the app\'s React files compile to native What components that run once, where the result behaves as React\'s: state is an accessor read where it is used, a value the body derives is a memo, props are read live, and useEffect, useLayoutEffect, useMemo and useCallback keep their deps. A component the compiler cannot show to behave the same stays a React component, rendered by what-react, and keeps React\'s rules and speed; the rest of its file is translated. What keeps one: a hook it does not translate (a React package\'s, useSyncExternalStore, useTransition, useImperativeHandle, a custom hook of another file), a `let` assigned again while it renders, a statement that runs while it renders (`console.log(…)`, `items.push(…)`), state set while it renders, `ref.current` read while it renders, `this`, a tag held in a value (`<Icon />` with `Icon` a prop), `forwardRef()`, `memo()` with a comparison function, an event handler that builds JSX, and an effect that hands on a function of the component (a listener, an interval) that reads a value missing from its deps, whose React closure keeps the old value. Rewrite the construct the reason names if the component is on a hot path, or leave it: a component that stays React works as it did.',
1316
+ codeExample: `// vite.config.js: reactCompat({ translate: true })
1317
+ import { useState } from 'react';
1318
+
1319
+ // Bad - stays React: the body pushes to a value while it renders:
1320
+ function Tags({ items }) {
1321
+ const shown = [];
1322
+ for (const item of items) shown.push(<li key={item}>{item}</li>);
1323
+ return <ul>{shown}</ul>;
1324
+ }
1325
+
1326
+ // Good - translated: the same list, derived where it renders:
1327
+ function Tags({ items }) {
1328
+ return <ul>{items.map((item) => <li key={item}>{item}</li>)}</ul>;
1329
+ }
1330
+
1331
+ // Good - translated: state read where it is used, a derived value:
1332
+ function Counter({ step }) {
1333
+ const [count, setCount] = useState(0);
1334
+ const label = \`\${count} clicks\`;
1335
+ return <button onClick={() => setCount(count + step)}>{label}</button>;
1336
+ }`,
1337
+ },
1338
+
1339
+ CLASS_COMPONENT_NOT_INSTALLED: {
1340
+ code: 'ERR_CLASS_COMPONENT_NOT_INSTALLED',
1341
+ severity: 'error',
1342
+ template: "[what-react] {{name}} is a class component, which this bundle cannot render: use what-react's Vite plugin, import 'what-react/class', or extend Component.",
1343
+ suggestion: "Class components come with what-react's Component and PureComponent, or with `what-react/class`. A class whose prototype is marked isReactComponent without extending Component (by hand, or by a library) needs the install. reactCompat() adds `import 'what-react/class'` to every module that has the marker; a build without the plugin (esbuild, another bundler) imports it once, in its entry.",
1344
+ codeExample: `// main.jsx, built without what-react's Vite plugin
1345
+ import 'what-react/class';
1346
+ import { createRoot } from 'react-dom/client';
1347
+ import { App } from './App.jsx';
1348
+
1349
+ createRoot(document.getElementById('app')).render(<App />);`,
1350
+ },
1351
+
390
1352
  CHILDREN_ONLY: {
391
1353
  code: 'ERR_CHILDREN_ONLY',
392
1354
  severity: 'error',
@@ -399,14 +1361,49 @@ export default { plugins: [reactCompat()] };`,
399
1361
  <Tooltip><span>a</span></Tooltip>`,
400
1362
  },
401
1363
 
1364
+ RECONCILER_CHILD: {
1365
+ code: 'ERR_RECONCILER_CHILD',
1366
+ severity: 'error',
1367
+ template: "[what-react] A custom renderer's tree cannot render {{what}}.",
1368
+ suggestion: "A renderer built on react-reconciler (react-three-fiber, ink, @react-pdf/renderer) holds its own host's elements, texts and React components. A DOM node, a react-dom portal or a native What component has no place in a 3D scene or a terminal. Render it beside the renderer's root, outside <Canvas>, or with the renderer's own way into the page (drei's <Html> for react-three-fiber).",
1369
+ codeExample: `// Bad: a native What component inside the scene
1370
+ <Canvas>
1371
+ <Score />
1372
+ </Canvas>
1373
+
1374
+ // Good: beside the canvas, in the page
1375
+ <>
1376
+ <Canvas>
1377
+ <Ship />
1378
+ </Canvas>
1379
+ <Score />
1380
+ </>`,
1381
+ },
1382
+
1383
+ RECONCILER_PERSISTENCE: {
1384
+ code: 'ERR_RECONCILER_PERSISTENCE',
1385
+ severity: 'error',
1386
+ template: "[what-react] This renderer uses persistence mode (supportsMutation: false), which what-react's react-reconciler does not support.",
1387
+ suggestion: "what-react's react-reconciler renders in mutation mode, which React DOM, ink, react-three-fiber, react-konva and @react-pdf/renderer use. A renderer whose host config sets supportsMutation to false and supportsPersistence to true (React Native's Fabric) needs React's own reconciler: leave `react` and `react-reconciler` unaliased for it.",
1388
+ codeExample: `// A host config what-react can drive: mutation mode
1389
+ const reconciler = createReconciler({
1390
+ supportsMutation: true,
1391
+ createInstance: (type, props) => ({ type, props, children: [] }),
1392
+ appendChild: (parent, child) => parent.children.push(child),
1393
+ });`,
1394
+ },
1395
+
402
1396
  USE_INVALID_ARG: {
403
1397
  code: 'ERR_USE_INVALID_ARG',
404
1398
  severity: 'error',
405
1399
  template: '[what-react] use() expects a promise or a context.',
406
- suggestion: 'use() reads either a thenable or a context object. Anything else has nothing to suspend on or subscribe to.',
407
- codeExample: `// Good:
408
- const value = use(ThemeContext);
409
- const data = use(fetchUser(id));`,
1400
+ suggestion: 'use() reads either a thenable or a context object. Anything else has nothing to suspend on or subscribe to. A promise read with use() must outlive the component: make it outside the component and pass it in, since one made in the body is a new promise every time the component runs.',
1401
+ codeExample: `// Good — a context, and a promise made outside the component:
1402
+ function Profile({ userPromise }) {
1403
+ const theme = use(ThemeContext);
1404
+ const user = use(userPromise);
1405
+ return <p className={theme}>{user.name}</p>;
1406
+ }`,
410
1407
  },
411
1408
 
412
1409
  PRETEXT_NOT_INSTALLED: {
@@ -414,30 +1411,36 @@ const data = use(fetchUser(id));`,
414
1411
  severity: 'error',
415
1412
  template: '[what-text] Failed to load @chenglou/pretext: {{message}}.',
416
1413
  suggestion: 'what-text declares pretext as an optional peer so the package installs without it. Install it to use the text engine: npm install @chenglou/pretext',
417
- codeExample: `npm install @chenglou/pretext`,
1414
+ codeExample: `// Install the optional peer first: npm install @chenglou/pretext
1415
+ // Then load it up front, so a missing install fails at startup:
1416
+ import { ensurePretext } from 'what-text';
1417
+ await ensurePretext();`,
418
1418
  },
419
1419
 
420
- DESTRUCTURED_PROPS: {
421
- code: 'ERR_DESTRUCTURED_PROPS',
422
- severity: 'warning',
423
- template: "Destructuring '{{binding}}' in the component body snapshots props and loses reactivity.",
424
- suggestion: "What components run ONCE, so the body is not re-run when a prop changes. Reading `props.foo` goes through the reactive proxy and tracks; `const { foo } = props` reads the value once and detaches it. Read through the proxy inside JSX and effects, or wrap each field in an accessor.",
425
- codeExample: `// Bad - snapshots at first run, never updates:
426
- function Row(props) {
427
- const { label } = props;
428
- return <span>{label}</span>;
429
- }
1420
+ DEPENDENCY_JSX: {
1421
+ code: 'ERR_DEPENDENCY_JSX',
1422
+ severity: 'error',
1423
+ template: '[what-compiler] {{package}} ships JSX in {{file}} without declaring What.',
1424
+ suggestion: 'Declare what-framework or what-core in dependencies or peerDependencies, or opt into compiling the source files with what({ compileDependencies: /my-ui-kit/ }).',
1425
+ codeExample: `// Bad - my-ui-kit ships JSX without declaring its runtime:
1426
+ what()
430
1427
 
431
- // Good - reads through the proxy each time:
432
- function Row(props) {
433
- return <span>{props.label}</span>;
434
- }
1428
+ // Good - opt in when the package expects What semantics:
1429
+ what({ compileDependencies: /my-ui-kit/ })`,
1430
+ },
435
1431
 
436
- // Good - an accessor keeps the destructured name:
437
- function Row(props) {
438
- const label = () => props.label;
439
- return <span>{label()}</span>;
440
- }`,
1432
+ MOVED_IMPORT: {
1433
+ code: 'ERR_MOVED_IMPORT',
1434
+ severity: 'error',
1435
+ template: '"{{name}}" is not exported by {{source}}. {{answer}}',
1436
+ suggestion: 'In 0.15 the root entry (what-framework, and what-core alike) kept the core API: the domain kits moved to subpaths such as what-framework/form and what-framework/ui, a few names were renamed, and some were removed. Each name has one answer, recorded in IMPORT_CHANGES (what-core/internal) and listed in UPGRADING.md. eslint --fix with eslint-plugin-what\'s no-moved-imports rule splits the import per destination; a removed name is left for you to replace as its answer says. A name only a subpath has ever exported, such as the router\'s (Router, Link, navigate from what-framework/router), gets the same answer when it is imported from the root entry, from what-compiler\'s Vite plugin and from no-moved-imports, whose fix moves it to what-framework/router.',
1437
+ codeExample: `// Bad - useForm and Spinner left the root entry in 0.15:
1438
+ import { signal, useForm, Spinner } from 'what-framework';
1439
+
1440
+ // Good:
1441
+ import { signal } from 'what-framework';
1442
+ import { useForm } from 'what-framework/form';
1443
+ import { Spinner } from 'what-framework/ui';`,
441
1444
  },
442
1445
 
443
1446
  // --- Fallbacks ---
@@ -457,10 +1460,12 @@ try { render(); } catch (e) { console.log(classifyError(e).toJSON()); }`,
457
1460
  UNKNOWN: {
458
1461
  code: 'ERR_UNKNOWN',
459
1462
  severity: 'error',
460
- template: 'Unknown error: {{errorCode}}.',
1463
+ template: 'Unknown error: {{errorCode}}',
461
1464
  suggestion: 'createWhatError() was called with a code that is not in this catalogue. Check the spelling against ERROR_CODES, or add the entry.',
462
- codeExample: `// Bad - not a catalogue key:
463
- createWhatError('MISSING_KEYS');
1465
+ codeExample: `import { createWhatError } from 'what-core/internal';
1466
+
1467
+ // Bad - not a catalogue key:
1468
+ throw createWhatError('MISSING_KEYS');
464
1469
 
465
1470
  // Good:
466
1471
  createWhatError('MISSING_KEY', { component: 'TodoList' });`,
@@ -471,12 +1476,12 @@ createWhatError('MISSING_KEY', { component: 'TodoList' });`,
471
1476
  severity: 'error',
472
1477
  template: 'Unknown tool: {{name}}.',
473
1478
  suggestion: 'The MCP client called a tool this server does not expose. Call tools/list to enumerate what is available; a stale client cache is the usual cause.',
474
- codeExample: `// List what the server actually exposes:
475
- { "method": "tools/list" }`,
1479
+ codeExample: `// List what the server actually exposes (tools/list), with the MCP SDK client:
1480
+ const { tools } = await client.listTools();`,
476
1481
  },
477
1482
  };
478
1483
 
479
- // Reverse index: an error carries `code: 'ERR_X'`, and the catalogue is keyed
1484
+ // Reverse index: an error carries its full ERR_* code, and the catalogue is keyed
480
1485
  // by its short name.
481
1486
  //
482
1487
  // Built on first use, NOT at module load. A top-level `new Map(...)` over
@@ -505,9 +1510,15 @@ export class WhatError extends Error {
505
1510
  // there and `suggestion` had to carry the whole fix in prose. It matters more
506
1511
  // here than in a framework aimed at humans: the audience reading toJSON() is
507
1512
  // usually an agent, and a diff-shaped example is the part it can copy.
1513
+ //
1514
+ // The class never reads the catalogue: it is a root export that apps import
1515
+ // for `instanceof`, and a lookup here kept all of ERROR_CODES (about 14 KB
1516
+ // gzipped) in those bundles. createWhatError() and classifyError() fill
1517
+ // severity, suggestion and codeExample from the entry.
508
1518
  /**
509
1519
  * @param {object} init
510
1520
  * @param {string} init.code
1521
+ * @param {'error' | 'warning'} [init.severity]
511
1522
  * @param {string} [init.message]
512
1523
  * @param {string} [init.suggestion]
513
1524
  * @param {{ bad?: string, good?: string } | string} [init.codeExample]
@@ -517,10 +1528,11 @@ export class WhatError extends Error {
517
1528
  * @param {string} [init.signal]
518
1529
  * @param {string} [init.effect]
519
1530
  */
520
- constructor({ code, message, suggestion, codeExample, file, line, component, signal, effect }) {
1531
+ constructor({ code, severity, message, suggestion, codeExample, file, line, component, signal, effect }) {
521
1532
  super(message);
522
1533
  this.name = 'WhatError';
523
1534
  this.code = code;
1535
+ this.severity = severity || 'error';
524
1536
  this.suggestion = suggestion;
525
1537
  this.codeExample = codeExample;
526
1538
  this.file = file;
@@ -533,6 +1545,7 @@ export class WhatError extends Error {
533
1545
  toJSON() {
534
1546
  return {
535
1547
  code: this.code,
1548
+ severity: this.severity,
536
1549
  message: this.message,
537
1550
  suggestion: this.suggestion,
538
1551
  codeExample: this.codeExample,
@@ -553,8 +1566,10 @@ export function createWhatError(errorCode, context = {}) {
553
1566
  if (!def) {
554
1567
  return new WhatError({
555
1568
  code: 'ERR_UNKNOWN',
1569
+ severity: /** @type {'error' | 'warning'} */ (ERROR_CODES.UNKNOWN.severity),
556
1570
  message: `Unknown error: ${errorCode}`,
557
- suggestion: 'Check the error code and try again.',
1571
+ suggestion: ERROR_CODES.UNKNOWN.suggestion,
1572
+ codeExample: ERROR_CODES.UNKNOWN.codeExample,
558
1573
  });
559
1574
  }
560
1575
 
@@ -568,6 +1583,7 @@ export function createWhatError(errorCode, context = {}) {
568
1583
 
569
1584
  return new WhatError({
570
1585
  code: def.code,
1586
+ severity: def.severity,
571
1587
  message,
572
1588
  suggestion: def.suggestion,
573
1589
  // Verbatim from the definition: codeExample is a worked bad/good pair, not
@@ -581,32 +1597,6 @@ export function createWhatError(errorCode, context = {}) {
581
1597
  });
582
1598
  }
583
1599
 
584
- // --- Error Collector ---
585
- // Dev-mode error accumulator for agent retrieval.
586
-
587
- let collectedErrors = [];
588
- const MAX_COLLECTED = 200;
589
-
590
- export function collectError(whatError) {
591
- if (!__DEV__) return;
592
- collectedErrors.push({
593
- ...whatError.toJSON(),
594
- timestamp: Date.now(),
595
- });
596
- if (collectedErrors.length > MAX_COLLECTED) {
597
- collectedErrors = collectedErrors.slice(-MAX_COLLECTED);
598
- }
599
- }
600
-
601
- export function getCollectedErrors(since) {
602
- if (since) return collectedErrors.filter(e => e.timestamp > since);
603
- return collectedErrors.slice();
604
- }
605
-
606
- export function clearCollectedErrors() {
607
- collectedErrors = [];
608
- }
609
-
610
1600
  // --- Error Classification ---
611
1601
  // Classify a raw Error into a structured WhatError if possible.
612
1602
 
@@ -616,13 +1606,15 @@ export function classifyError(err, context = {}) {
616
1606
  // An error the framework threw already says what it is. Every throw outside
617
1607
  // core carries a `code` and nothing else — the suggestion and the worked
618
1608
  // example live once, in ERROR_CODES — so resolving the code here is what
619
- // makes them reachable at all. Message sniffing below is only for errors
620
- // that predate the code, or that come from user code.
1609
+ // makes them reachable at all. Framework checks report through
1610
+ // diagnostics.js; nothing here guesses a code from message text, because a
1611
+ // guessed code sends an agent to the wrong fix.
621
1612
  if (err && typeof err.code === 'string') {
622
1613
  const def = getErrorDefinition(err.code);
623
1614
  if (def) {
624
1615
  return new WhatError({
625
1616
  code: def.code,
1617
+ severity: def.severity,
626
1618
  // The thrown message is the specific one; the template is generic.
627
1619
  message: msg,
628
1620
  suggestion: def.suggestion,
@@ -636,29 +1628,13 @@ export function classifyError(err, context = {}) {
636
1628
  }
637
1629
  }
638
1630
 
639
- // Infinite effect loop
640
- if (msg.includes('infinite effect loop') || msg.includes('25 iterations')) {
641
- return createWhatError('INFINITE_EFFECT', context);
642
- }
643
-
644
- // Hydration mismatch
645
- if (msg.includes('hydration') || msg.includes('Hydration')) {
646
- return createWhatError('HYDRATION_MISMATCH', context);
647
- }
648
-
649
- // Signal write in computed
650
- if (msg.includes('Signal.set() called inside a computed')) {
651
- return createWhatError('SIGNAL_WRITE_IN_RENDER', {
652
- ...context,
653
- signalName: msg.match(/signal: (\w+)/)?.[1] || context.signalName,
654
- });
655
- }
656
-
657
1631
  // Fallback — return a generic WhatError with the original message
658
1632
  return new WhatError({
659
1633
  code: 'ERR_RUNTIME',
1634
+ severity: /** @type {'error' | 'warning'} */ (ERROR_CODES.RUNTIME.severity),
660
1635
  message: msg,
661
- suggestion: 'Check the stack trace and component context for more details.',
1636
+ suggestion: ERROR_CODES.RUNTIME.suggestion,
1637
+ codeExample: ERROR_CODES.RUNTIME.codeExample,
662
1638
  ...context,
663
1639
  });
664
1640
  }