what-compiler 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.
- package/LICENSE +21 -0
- package/README.md +181 -2
- package/babel.d.ts +78 -2
- package/dist/babel/auto-selector.min.js +94 -0
- package/dist/babel/common.min.js +2053 -0
- package/dist/babel/dev-metadata.min.js +106 -0
- package/dist/babel/dom.min.js +1669 -0
- package/dist/babel/jsx-root.min.js +13 -0
- package/dist/babel/lists.min.js +492 -0
- package/dist/babel/nesting.min.js +328 -0
- package/dist/babel/reactivity.min.js +1218 -0
- package/dist/babel/server-actions.min.js +85 -0
- package/dist/babel/ssr.min.js +496 -0
- package/dist/babel/types.min.js +9 -0
- package/dist/babel-plugin.min.js +101 -1
- package/dist/file-router.min.js +368 -12
- package/dist/framework-files.min.js +62 -0
- package/dist/hot.min.js +315 -0
- package/dist/index.min.js +13 -414
- package/dist/release.min.js +78 -0
- package/dist/runtime.min.js +9 -1
- package/dist/tables/import-changes.min.js +272 -0
- package/dist/tables/markup-rules.min.js +213 -0
- package/dist/vite-plugin.min.js +432 -399
- package/file-router.d.ts +3 -1
- package/index.d.ts +1 -1
- package/package.json +11 -2
- package/runtime.d.ts +2 -1
- package/src/babel/auto-selector.js +248 -0
- package/src/babel/common.js +3800 -0
- package/src/babel/dev-metadata.js +167 -0
- package/src/babel/dom.js +3386 -0
- package/src/babel/jsx-root.js +27 -0
- package/src/babel/lists.js +704 -0
- package/src/babel/nesting.js +260 -0
- package/src/babel/reactivity.js +1998 -0
- package/src/babel/server-actions.js +144 -0
- package/src/babel/ssr.js +870 -0
- package/src/babel/types.js +10 -0
- package/src/babel-plugin.js +185 -3598
- package/src/file-router.js +58 -38
- package/src/framework-files.js +106 -0
- package/src/hot.js +523 -0
- package/src/release.js +127 -0
- package/src/runtime.js +7 -7
- package/src/tables/import-changes.js +157 -0
- package/src/tables/markup-rules.js +388 -0
- package/src/vite-plugin.js +460 -175
- package/vite.d.ts +47 -3
- package/src/error-overlay.js +0 -428
package/src/babel-plugin.js
CHANGED
|
@@ -1,3318 +1,90 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* What Framework Babel Plugin
|
|
2
|
+
* What Framework Babel Plugin
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
* Static HTML extracted to module-level templates, dynamic expressions wrapped in effects.
|
|
6
|
-
* Components run ONCE. All reactivity is signal-driven.
|
|
4
|
+
* One front end, two back ends, chosen with the `generate` option:
|
|
7
5
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
6
|
+
* generate: 'dom' (default) JSX -> cloned templates + fine-grained bindings
|
|
7
|
+
* const _tmpl$0 = _$template('<div class="container"><h1>Title</h1><p></p></div>');
|
|
8
|
+
* function App() {
|
|
9
|
+
* const _el$0 = _tmpl$0();
|
|
10
|
+
* _$insert(_el$0.firstChild.nextSibling, () => desc());
|
|
11
|
+
* return _el$0;
|
|
12
|
+
* }
|
|
15
13
|
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
14
|
+
* generate: 'ssr' JSX -> pre-joined server strings, holes as h() gets them
|
|
15
|
+
* const _tmpl$0 = ['<div class="container"><h1>Title</h1><p>', '</p></div>'];
|
|
16
|
+
* function App() {
|
|
17
|
+
* return _$ssr(_tmpl$0, () => desc());
|
|
18
|
+
* }
|
|
19
|
+
*
|
|
20
|
+
* Both back ends read the same element classification, attribute aliases,
|
|
21
|
+
* child layout, list detection and component lowering decisions, so server
|
|
22
|
+
* markup and client templates cannot drift apart. Modules:
|
|
23
|
+
*
|
|
24
|
+
* babel/common.js shared front end: names, attributes, namespaces, child slots
|
|
25
|
+
* babel/reactivity.js which expressions read signals
|
|
26
|
+
* babel/lists.js `.map()` detection and key analysis
|
|
27
|
+
* babel/nesting.js compile-time HTML nesting rules
|
|
28
|
+
* babel/dom.js DOM back end (what-framework/render)
|
|
29
|
+
* babel/auto-selector.js DOM-only `sel() === row.id` rewrite
|
|
30
|
+
* babel/ssr.js server back end (what-framework/ssr-runtime)
|
|
31
|
+
* babel/dev-metadata.js development names and source locations
|
|
32
|
+
* babel/server-actions.js stable server action ids
|
|
33
|
+
*
|
|
34
|
+
* Options:
|
|
35
|
+
* generate 'dom' | 'ssr' which back end lowers JSX (default 'dom')
|
|
36
|
+
* hydratable boolean DOM back end: output that hydrate() can adopt
|
|
37
|
+
* server-rendered markup with (default false)
|
|
38
|
+
* production boolean production build: no development warnings or metadata
|
|
39
|
+
* devMetadata boolean development builds only: component, signal and
|
|
40
|
+
* binding names with source locations
|
|
41
|
+
* projectRoot string root that source locations and action ids are relative to
|
|
42
|
+
* autoSelector boolean DOM back end: rewrite `sel() === row.key` (default true)
|
|
43
|
+
* onActionId (meta) => void called for every server action id
|
|
44
|
+
* appSource boolean compile a file of one of What's own packages
|
|
45
|
+
* (framework-files.js) as the app's source:
|
|
46
|
+
* development names, server action ids and
|
|
47
|
+
* components without JSX (default false)
|
|
18
48
|
*/
|
|
19
49
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
//
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
// Built-in prototype methods that convert or copy a value. A zero-argument call
|
|
45
|
-
// is otherwise assumed to be a signal read (see isPotentiallyReactive); these
|
|
46
|
-
// names are the ones JavaScript itself defines, so they never are, and they are
|
|
47
|
-
// common enough in JSX that wrapping them would be pure cost.
|
|
48
|
-
const PURE_BUILTIN_METHODS = new Set([
|
|
49
|
-
'toString', 'toLocaleString', 'valueOf', 'toJSON',
|
|
50
|
-
'toUpperCase', 'toLowerCase', 'toLocaleUpperCase', 'toLocaleLowerCase',
|
|
51
|
-
'trim', 'trimStart', 'trimEnd',
|
|
52
|
-
'toFixed', 'toPrecision', 'toExponential',
|
|
53
|
-
'toISOString', 'toUTCString', 'toDateString', 'toTimeString',
|
|
54
|
-
'toLocaleDateString', 'toLocaleTimeString',
|
|
55
|
-
'slice', 'reverse', 'sort', 'flat', 'concat', 'join',
|
|
56
|
-
]);
|
|
57
|
-
|
|
58
|
-
// Known signal-creating functions
|
|
59
|
-
const SIGNAL_CREATORS = new Set([
|
|
60
|
-
'useSignal', 'signal', 'computed', 'useComputed', 'useState', 'useReducer',
|
|
61
|
-
'createResource', 'useSWR', 'useQuery', 'useInfiniteQuery',
|
|
62
|
-
]);
|
|
63
|
-
|
|
64
|
-
// Control-flow tags the plugin lowers itself instead of emitting
|
|
65
|
-
// _$createComponent, so their children never travel through a factory.
|
|
66
|
-
const LOWERED_TAGS = new Set(['For', 'Show', 'Switch', 'Match']);
|
|
67
|
-
|
|
68
|
-
const SERVER_ACTION_SOURCES = new Set([
|
|
69
|
-
'what-framework/server',
|
|
70
|
-
'what-server',
|
|
71
|
-
'what-server/actions',
|
|
72
|
-
]);
|
|
73
|
-
|
|
74
|
-
// A bare specifier that resolves to this framework, entry point included:
|
|
75
|
-
// 'what-framework', 'what-framework/render', 'what-core', 'what-core/render'.
|
|
76
|
-
// Used to decide whether an imported binding is provably ours before the plugin
|
|
77
|
-
// changes how a call to it is compiled.
|
|
78
|
-
function isWhatModuleSource(source) {
|
|
79
|
-
return source === 'what-framework'
|
|
80
|
-
|| source.startsWith('what-framework/')
|
|
81
|
-
|| source === 'what-core'
|
|
82
|
-
|| source.startsWith('what-core/');
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
function stableActionHash(value) {
|
|
86
|
-
let hash = 0xcbf29ce484222325n;
|
|
87
|
-
for (let i = 0; i < value.length; i++) {
|
|
88
|
-
hash ^= BigInt(value.charCodeAt(i));
|
|
89
|
-
hash = BigInt.asUintN(64, hash * 0x100000001b3n);
|
|
90
|
-
}
|
|
91
|
-
return hash.toString(36);
|
|
50
|
+
import { t, setTypes } from './babel/types.js';
|
|
51
|
+
import { deferPlacedProps, keepCleanupValues, liveHelperArgs, lowerLiveReturns, markHookResults, memoBranchValues, memoLiveLets, markPropFieldReads, readPropFields, warnDerivedPropOnce, warnLiveCleanup, warnStateReadOnce, initFileState, isComponentElement, isWhatModuleSource, recordName, spreadChildren, unwrapHostSpreads } from './babel/common.js';
|
|
52
|
+
import { initDomState, finishDomProgram, transformJsxRoot, mayBuildTag } from './babel/dom.js';
|
|
53
|
+
import { initSsrState, finishSsrProgram, transformSsrRoot } from './babel/ssr.js';
|
|
54
|
+
import { SERVER_ACTION_SOURCES, normalizeActionFilename, transformServerAction } from './babel/server-actions.js';
|
|
55
|
+
import { annotatePrimitive } from './babel/dev-metadata.js';
|
|
56
|
+
import { resolveCallees } from './babel/reactivity.js';
|
|
57
|
+
import { markRowKey } from './babel/lists.js';
|
|
58
|
+
import { fileRuntimeMismatch } from './release.js';
|
|
59
|
+
import { isFrameworkModule } from './framework-files.js';
|
|
60
|
+
|
|
61
|
+
// A function what-react's translate mode leaves React code in a file it
|
|
62
|
+
// otherwise made native (react-compat translate.js): its JSX is lowered to
|
|
63
|
+
// what-react already, and it re-renders by React's rules, so none of the
|
|
64
|
+
// compiler's passes for components applies to it.
|
|
65
|
+
const REACT_DIRECTIVE = 'what-react';
|
|
66
|
+
// The calls of what-react/translated that mark a component translate mode
|
|
67
|
+
// made native and hand it over when React code renders it: they leave it a
|
|
68
|
+
// plain function (dom.js isPlainFunctionComponent).
|
|
69
|
+
const TRANSLATED_MARKS = new Set(['_$translated', '_$inReact', '_$renderNative']);
|
|
70
|
+
function isReactFunction(fnPath) {
|
|
71
|
+
const body = fnPath.node.body;
|
|
72
|
+
return t.isBlockStatement(body) && body.directives.some((d) => d.value.value === REACT_DIRECTIVE);
|
|
92
73
|
}
|
|
93
74
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
return
|
|
75
|
+
// The element a component-cased JSX tag names when its binding is a constant
|
|
76
|
+
// holding an element's name (`const Tag = 'select'`), else null.
|
|
77
|
+
function constantTag(elPath) {
|
|
78
|
+
const name = elPath.node.openingElement.name;
|
|
79
|
+
if (!t.isJSXIdentifier(name) || !/^[A-Z]/.test(name.name)) return null;
|
|
80
|
+
const binding = elPath.scope.getBinding(name.name);
|
|
81
|
+
if (!binding || !binding.constant || !t.isVariableDeclarator(binding.path.node)) return null;
|
|
82
|
+
const init = binding.path.node.init;
|
|
83
|
+
return t.isStringLiteral(init) && /^[a-z][a-zA-Z0-9]*(-[a-zA-Z0-9]+)*$/.test(init.value) ? init.value : null;
|
|
103
84
|
}
|
|
104
85
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
// - For interior lines: trim leading and trailing horizontal whitespace.
|
|
108
|
-
// - For the first line: only trim trailing whitespace.
|
|
109
|
-
// - For the last line: only trim leading whitespace.
|
|
110
|
-
// - Skip lines that are entirely whitespace (don't add a separator space).
|
|
111
|
-
// - Join the remaining non-empty lines with single spaces.
|
|
112
|
-
//
|
|
113
|
-
// This preserves leading/trailing single-line whitespace that sits next to
|
|
114
|
-
// an expression like `{count} items` — without this, the space is eaten and
|
|
115
|
-
// the rendered output reads `5items`.
|
|
116
|
-
function normalizeJsxText(value) {
|
|
117
|
-
// Single-line text (no newlines): preserve the original (just tabs->spaces).
|
|
118
|
-
// This keeps the space in cases like `{a} {b}` where the JSXText is " ".
|
|
119
|
-
if (!/[\r\n]/.test(value)) {
|
|
120
|
-
return value.replace(/\t/g, ' ');
|
|
121
|
-
}
|
|
122
|
-
const lines = value.split(/\r\n|\n|\r/);
|
|
123
|
-
let lastNonEmpty = -1;
|
|
124
|
-
for (let i = 0; i < lines.length; i++) {
|
|
125
|
-
if (/[^ \t]/.test(lines[i])) lastNonEmpty = i;
|
|
126
|
-
}
|
|
127
|
-
if (lastNonEmpty === -1) return '';
|
|
128
|
-
let out = '';
|
|
129
|
-
for (let i = 0; i < lines.length; i++) {
|
|
130
|
-
let line = lines[i].replace(/\t/g, ' ');
|
|
131
|
-
const isFirst = i === 0;
|
|
132
|
-
const isLast = i === lines.length - 1;
|
|
133
|
-
if (!isFirst) line = line.replace(/^ +/, '');
|
|
134
|
-
if (!isLast) line = line.replace(/ +$/, '');
|
|
135
|
-
if (!line) continue;
|
|
136
|
-
if (i !== lastNonEmpty) line += ' ';
|
|
137
|
-
out += line;
|
|
138
|
-
}
|
|
139
|
-
return out;
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
export default function whatBabelPlugin({ types: t }) {
|
|
143
|
-
// =====================================================
|
|
144
|
-
// Shared utilities
|
|
145
|
-
// =====================================================
|
|
146
|
-
|
|
147
|
-
// Warn-once tracking for unknown event modifier segments. Keyed by
|
|
148
|
-
// `${filename}::${segment}` so each typo is reported at most once per file
|
|
149
|
-
// per compile process. Without the filename in the key, the same typo in
|
|
150
|
-
// two different files would silently warn for the first file only —
|
|
151
|
-
// problematic in long-running Vite dev servers.
|
|
152
|
-
const _unknownModifierWarned = new Set();
|
|
153
|
-
const _forInfoWarned = new Set();
|
|
154
|
-
|
|
155
|
-
function hasEventModifiers(name, state) {
|
|
156
|
-
// Any `__` in an `on*` attribute is intended as modifier syntax — even
|
|
157
|
-
// if every segment is unknown. Returning false there would emit the
|
|
158
|
-
// attribute as a plain delegated-event property (e.g.
|
|
159
|
-
// `el.$$onclick__totalyWrong = handler`), which never fires. Instead,
|
|
160
|
-
// always route through the modifier-handling branch so the parser can
|
|
161
|
-
// warn about the typo and drop the unknown segments.
|
|
162
|
-
if (!name.includes('__')) return false;
|
|
163
|
-
if (!name.startsWith('on')) return false;
|
|
164
|
-
const parts = name.split('__');
|
|
165
|
-
const tail = parts.slice(1).filter(s => s !== '');
|
|
166
|
-
if (tail.length === 0) return false;
|
|
167
|
-
if (process.env.NODE_ENV !== 'production') {
|
|
168
|
-
const unknown = tail.filter(m => !EVENT_MODIFIERS.has(m));
|
|
169
|
-
const filename = (state && (state.filename || (state.file && state.file.opts && state.file.opts.filename))) || '<unknown>';
|
|
170
|
-
for (const m of unknown) {
|
|
171
|
-
const key = `${filename}::${m}`;
|
|
172
|
-
if (!_unknownModifierWarned.has(key)) {
|
|
173
|
-
_unknownModifierWarned.add(key);
|
|
174
|
-
console.warn(
|
|
175
|
-
`[what-compiler] Unknown event modifier "__${m}" in attribute "${name}" (${filename}). ` +
|
|
176
|
-
`Known modifiers: ${[...EVENT_MODIFIERS].join(', ')}. ` +
|
|
177
|
-
`Unknown segments are ignored.`
|
|
178
|
-
);
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
return true;
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
function parseEventModifiers(name) {
|
|
186
|
-
// Support both '|' (template strings) and '__' (JSX-safe) as modifier delimiters
|
|
187
|
-
const delimiter = name.includes('|') ? '|' : '__';
|
|
188
|
-
const parts = name.split(delimiter);
|
|
189
|
-
const eventName = parts[0];
|
|
190
|
-
const modifiers = parts.slice(1).filter(m => EVENT_MODIFIERS.has(m));
|
|
191
|
-
return { eventName, modifiers };
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
function isBindingAttribute(name) {
|
|
195
|
-
return name.startsWith('bind:');
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
function getBindingProperty(name) {
|
|
199
|
-
return name.slice(5);
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
function isComponent(name) {
|
|
203
|
-
return /^[A-Z]/.test(name);
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
// Build the Error for a JSX shape the compiler refuses to lower.
|
|
207
|
-
//
|
|
208
|
-
// Every fine-grained transform is reachable two ways: from the JSXElement
|
|
209
|
-
// visitor, where `path` is a real NodePath, and recursively from a parent
|
|
210
|
-
// transform, which passes a SYNTHETIC `{ node: child }` (see the
|
|
211
|
-
// transformElementFineGrained / transformFragmentFineGrained calls further
|
|
212
|
-
// down). Only the visitor's path carries buildCodeFrameError, so calling it
|
|
213
|
-
// unguarded threw "path.buildCodeFrameError is not a function" — an internal
|
|
214
|
-
// crash in place of the diagnostic the author was meant to act on. That hit
|
|
215
|
-
// the ordinary shapes, not the exotic ones: `<div><Show>…</Show></div>` is
|
|
216
|
-
// already synthetic, so only a control-flow tag that was the ENTIRE return
|
|
217
|
-
// value ever reported properly.
|
|
218
|
-
//
|
|
219
|
-
// Guarding the call is not enough either. `throw new Error(message)` reaches
|
|
220
|
-
// the developer, but with no file and no line, which for a build error in a
|
|
221
|
-
// 300-file app is barely better than the crash. state.file is Babel's File
|
|
222
|
-
// for the module being compiled and its buildCodeFrameError(node, msg) pins
|
|
223
|
-
// the frame from the node's own loc, so a synthetic path still gets the same
|
|
224
|
-
// pointed-at source the visitor path does.
|
|
225
|
-
function compileError(path, state, message) {
|
|
226
|
-
if (typeof path?.buildCodeFrameError === 'function') {
|
|
227
|
-
return path.buildCodeFrameError(message);
|
|
228
|
-
}
|
|
229
|
-
const node = path?.node;
|
|
230
|
-
if (node && typeof state?.file?.buildCodeFrameError === 'function') {
|
|
231
|
-
return state.file.buildCodeFrameError(node, message);
|
|
232
|
-
}
|
|
233
|
-
// No NodePath and no File (a direct unit-test call, or a node the parser
|
|
234
|
-
// never produced). Name the file and line by hand so the message still
|
|
235
|
-
// says where to look.
|
|
236
|
-
const loc = node?.loc?.start;
|
|
237
|
-
const filename = state?.filename || state?.file?.opts?.filename || '<unknown>';
|
|
238
|
-
return new Error(
|
|
239
|
-
`[what-compiler] ${message} (${loc ? `${filename}:${loc.line}:${loc.column + 1}` : filename})`
|
|
240
|
-
);
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
// Dotted tags (<Ctx.Provider>, <Foo.Bar.Baz>) are always components.
|
|
244
|
-
function isComponentElement(el) {
|
|
245
|
-
const name = el.openingElement ? el.openingElement.name : el.name;
|
|
246
|
-
if (t.isJSXMemberExpression(name)) return true;
|
|
247
|
-
return t.isJSXIdentifier(name) && isComponent(name.name);
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
// A tag whose binding came from a package other than What. isWhatTag is the
|
|
251
|
-
// stronger claim: the binding came from What, so the tag is provably ours.
|
|
252
|
-
function isForeignTag(name, state) {
|
|
253
|
-
return !!(state.foreignImports && state.foreignImports.has(name));
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
function isWhatTag(name, state) {
|
|
257
|
-
return !!(state.whatImports && state.whatImports.has(name));
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
// Literal <Match> arms are proof enough that a <Switch> is What's, whoever it
|
|
261
|
-
// was imported from: a bare specifier can be a re-export of What's control
|
|
262
|
-
// flow just as a relative one can, and nobody writes <Match> arms against a
|
|
263
|
-
// third-party <Switch>. Unlike <Show> and <For>, <Switch> has no working
|
|
264
|
-
// runtime path, so guessing wrong here renders the fallback forever.
|
|
265
|
-
function hasLiteralMatchArms(node) {
|
|
266
|
-
return node.children.some((child) =>
|
|
267
|
-
t.isJSXElement(child) && t.isJSXIdentifier(child.openingElement.name, { name: 'Match' }));
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
// --- The JSX handed straight to hydrate() ---
|
|
271
|
-
//
|
|
272
|
-
// hydrate() can only adopt the server's markup from an UNBUILT tree: a node
|
|
273
|
-
// that has already been built has its bindings wired to itself, so hydrateNode
|
|
274
|
-
// inserts it and lets the trim delete everything the server sent. The
|
|
275
|
-
// documented client entry, `hydrate(<App />, el)`, lowered to
|
|
276
|
-
// `_$createComponent(App, ...)`, which runs App and builds its DOM before
|
|
277
|
-
// hydrate() is even called — so every compiled app that hydrated threw its
|
|
278
|
-
// server render away and re-rendered from scratch, silently in production
|
|
279
|
-
// where the warning is stripped.
|
|
280
|
-
//
|
|
281
|
-
// Only the first argument is the tree; the second is the container. And only a
|
|
282
|
-
// binding that provably resolves to OUR hydrate qualifies, because rewriting a
|
|
283
|
-
// call to somebody else's `hydrate` would change what their code means.
|
|
284
|
-
function isHydrateRootArgument(path) {
|
|
285
|
-
// transformElementFineGrained is also called with a bare `{ node }` stand-in
|
|
286
|
-
// when it recurses into children, and a child is never the hydrate root.
|
|
287
|
-
const parent = path.parentPath;
|
|
288
|
-
if (!parent || typeof parent.isCallExpression !== 'function' || !parent.isCallExpression()) {
|
|
289
|
-
return false;
|
|
290
|
-
}
|
|
291
|
-
if (parent.node.arguments[0] !== path.node) return false;
|
|
292
|
-
return isWhatHydrateCallee(parent.node.callee, parent.scope);
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
// Resolve the callee through Babel's scope rather than by name, so a local
|
|
296
|
-
// `function hydrate()` or `const hydrate = ...` that shadows the import is left
|
|
297
|
-
// alone. getBinding returns the NEAREST binding, which is exactly the shadowing
|
|
298
|
-
// rule the language itself applies. An unresolved (global) `hydrate` is not
|
|
299
|
-
// ours either, so it stays untouched too.
|
|
300
|
-
function isWhatHydrateCallee(callee, scope) {
|
|
301
|
-
// `ns.hydrate(...)` after `import * as ns from 'what-framework'`.
|
|
302
|
-
if (t.isMemberExpression(callee) && !callee.computed
|
|
303
|
-
&& t.isIdentifier(callee.property, { name: 'hydrate' })
|
|
304
|
-
&& t.isIdentifier(callee.object)) {
|
|
305
|
-
return importedFrom(scope.getBinding(callee.object.name), t.isImportNamespaceSpecifier, null);
|
|
306
|
-
}
|
|
307
|
-
if (!t.isIdentifier(callee)) return false;
|
|
308
|
-
// `import { hydrate }` and `import { hydrate as boot }` alike: the binding
|
|
309
|
-
// remembers the name that was IMPORTED, which is the one that matters.
|
|
310
|
-
return importedFrom(scope.getBinding(callee.name), t.isImportSpecifier, 'hydrate');
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
// A binding is ours when it came from an import declaration of a What module
|
|
314
|
-
// through the expected specifier kind, optionally carrying a required imported
|
|
315
|
-
// name (`hydrate` for a named import, none for a namespace).
|
|
316
|
-
function importedFrom(binding, isSpecifier, importedName) {
|
|
317
|
-
if (!binding || binding.kind !== 'module' || !binding.path) return false;
|
|
318
|
-
const spec = binding.path.node;
|
|
319
|
-
if (!isSpecifier(spec)) return false;
|
|
320
|
-
if (importedName !== null) {
|
|
321
|
-
const imported = spec.imported;
|
|
322
|
-
const name = t.isIdentifier(imported) ? imported.name
|
|
323
|
-
: t.isStringLiteral(imported) ? imported.value
|
|
324
|
-
: null;
|
|
325
|
-
if (name !== importedName) return false;
|
|
326
|
-
}
|
|
327
|
-
const decl = binding.path.parent;
|
|
328
|
-
return t.isImportDeclaration(decl) && isWhatModuleSource(decl.source.value);
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
// JSXMemberExpression -> MemberExpression callee for _$createComponent.
|
|
332
|
-
function componentCallee(name) {
|
|
333
|
-
if (t.isJSXMemberExpression(name)) {
|
|
334
|
-
return t.memberExpression(componentCallee(name.object), t.identifier(name.property.name));
|
|
335
|
-
}
|
|
336
|
-
return t.identifier(name.name);
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
// --- Forwarded children on a destructured parameter ---
|
|
340
|
-
// `function Wrap({ children }) { return <ErrorBoundary>{children}</ErrorBoundary>; }`
|
|
341
|
-
// realizes the subtree while the parameter list is destructured, which is
|
|
342
|
-
// before ErrorBoundary is entered, so the boundary never catches and a
|
|
343
|
-
// provider publishes its value too late for its own subtree. Rewriting the
|
|
344
|
-
// pattern to a props identifier moves the read into the deferred children
|
|
345
|
-
// factory, where the enclosing component is already on the stack. Only a
|
|
346
|
-
// binding whose every reference is a component-child forward qualifies: a
|
|
347
|
-
// component that inspects its children still needs them realized.
|
|
348
|
-
function deferForwardedChildren(fnPath) {
|
|
349
|
-
const params = fnPath.node.params;
|
|
350
|
-
if (params.length !== 1 || !t.isObjectPattern(params[0])) return;
|
|
351
|
-
const pattern = params[0];
|
|
352
|
-
let index = -1;
|
|
353
|
-
for (let i = 0; i < pattern.properties.length; i++) {
|
|
354
|
-
const prop = pattern.properties[i];
|
|
355
|
-
if (t.isRestElement(prop)) return;
|
|
356
|
-
if (t.isObjectProperty(prop) && !prop.computed &&
|
|
357
|
-
t.isIdentifier(prop.key, { name: 'children' })) {
|
|
358
|
-
// A duplicate key would leave the other one destructured in the body,
|
|
359
|
-
// which reads the getter and defeats the deferral.
|
|
360
|
-
if (index !== -1 || !t.isIdentifier(prop.value)) return;
|
|
361
|
-
index = i;
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
if (index === -1) return;
|
|
365
|
-
|
|
366
|
-
const binding = fnPath.scope.getBinding(pattern.properties[index].value.name);
|
|
367
|
-
if (!binding || binding.constantViolations.length > 0 || binding.referencePaths.length === 0) return;
|
|
368
|
-
const forwarded = binding.referencePaths.every((ref) => {
|
|
369
|
-
const container = ref.parentPath;
|
|
370
|
-
if (!container || !container.isJSXExpressionContainer()) return false;
|
|
371
|
-
const owner = container.parentPath;
|
|
372
|
-
if (!owner || !owner.isJSXElement() || !isComponentElement(owner.node)) return false;
|
|
373
|
-
const tag = owner.node.openingElement.name;
|
|
374
|
-
return !(t.isJSXIdentifier(tag) && LOWERED_TAGS.has(tag.name));
|
|
375
|
-
});
|
|
376
|
-
if (!forwarded) return;
|
|
377
|
-
|
|
378
|
-
const propsId = fnPath.scope.generateUidIdentifier('props');
|
|
379
|
-
if (pattern.typeAnnotation) propsId.typeAnnotation = pattern.typeAnnotation;
|
|
380
|
-
params[0] = propsId;
|
|
381
|
-
const remaining = pattern.properties.filter((_, i) => i !== index);
|
|
382
|
-
if (remaining.length > 0) {
|
|
383
|
-
if (!t.isBlockStatement(fnPath.node.body)) {
|
|
384
|
-
fnPath.node.body = t.blockStatement([t.returnStatement(fnPath.node.body)]);
|
|
385
|
-
}
|
|
386
|
-
const moved = t.objectPattern(remaining);
|
|
387
|
-
fnPath.node.body.body.unshift(
|
|
388
|
-
t.variableDeclaration('const', [
|
|
389
|
-
t.variableDeclarator(moved, t.cloneNode(propsId)),
|
|
390
|
-
])
|
|
391
|
-
);
|
|
392
|
-
// collectSignalNamesFromScope classifies a component's props by reading
|
|
393
|
-
// the parameter list, so the moved pattern has to stay visible to it or
|
|
394
|
-
// every sibling prop silently stops being treated as reactive.
|
|
395
|
-
fnPath.node._whatMovedProps = moved;
|
|
396
|
-
}
|
|
397
|
-
for (const ref of binding.referencePaths) {
|
|
398
|
-
ref.replaceWith(t.memberExpression(t.cloneNode(propsId), t.identifier('children')));
|
|
399
|
-
}
|
|
400
|
-
fnPath.scope.crawl();
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
function isVoidHtmlElement(name) {
|
|
404
|
-
return VOID_HTML_ELEMENTS.has(String(name).toLowerCase());
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
function getAttributeValue(value) {
|
|
408
|
-
if (!value) return t.booleanLiteral(true);
|
|
409
|
-
if (t.isJSXExpressionContainer(value)) return value.expression;
|
|
410
|
-
if (t.isStringLiteral(value)) return value;
|
|
411
|
-
return t.stringLiteral(value.value || '');
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
// Prop names whose HTML attribute is not just the prop name in another case.
|
|
415
|
-
// A static attribute is baked into a template string that the HTML parser
|
|
416
|
-
// reads, and the parser only lowercases names, so an unrenamed
|
|
417
|
-
// `httpEquiv="refresh"` became a meaningless `httpequiv` attribute. The h()
|
|
418
|
-
// path and what-server rename the same set.
|
|
419
|
-
const ATTRIBUTE_ALIASES = new Map([
|
|
420
|
-
['className', 'class'],
|
|
421
|
-
['htmlFor', 'for'],
|
|
422
|
-
['httpEquiv', 'http-equiv'],
|
|
423
|
-
['acceptCharset', 'accept-charset'],
|
|
424
|
-
]);
|
|
425
|
-
|
|
426
|
-
function normalizeAttrName(attrName) {
|
|
427
|
-
return ATTRIBUTE_ALIASES.get(attrName) || attrName;
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
// Is this attribute overwritten by a later one naming the same DOM property?
|
|
431
|
-
//
|
|
432
|
-
// `<div id={a} id="b"/>` is legal JSX and means id="b": the last writer of a
|
|
433
|
-
// name wins, exactly as it does in the object literal the h() spelling
|
|
434
|
-
// builds. The template could not express that, because a repeated attribute
|
|
435
|
-
// in an HTML string keeps the FIRST value and a dynamic attribute is applied
|
|
436
|
-
// after the template regardless of where it was written. Dropping the
|
|
437
|
-
// shadowed one leaves a single writer per name, so written order decides.
|
|
438
|
-
//
|
|
439
|
-
// A later SPREAD never shadows: it overrides only the names it actually
|
|
440
|
-
// carries, which is not knowable here and is handled by ordering instead.
|
|
441
|
-
function isShadowedAttr(attributes, index) {
|
|
442
|
-
const name = normalizeAttrName(getAttrName(attributes[index]));
|
|
443
|
-
for (let i = index + 1; i < attributes.length; i += 1) {
|
|
444
|
-
const later = attributes[i];
|
|
445
|
-
if (t.isJSXSpreadAttribute(later)) continue;
|
|
446
|
-
if (normalizeAttrName(getAttrName(later)) === name) return true;
|
|
447
|
-
}
|
|
448
|
-
return false;
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
// Safely extract attribute name, handling JSXNamespacedName (e.g., client:idle, bind:value)
|
|
452
|
-
function getAttrName(attr) {
|
|
453
|
-
if (t.isJSXNamespacedName(attr.name)) {
|
|
454
|
-
return `${attr.name.namespace.name}:${attr.name.name.name}`;
|
|
455
|
-
}
|
|
456
|
-
return typeof attr.name.name === 'string' ? attr.name.name : String(attr.name.name);
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
// The key half of a prop in an emitted object literal. A JSX attribute name is
|
|
460
|
-
// frequently NOT a valid JavaScript identifier — `data-x`, `aria-label` and
|
|
461
|
-
// every namespaced name contain characters an identifier cannot — so anything
|
|
462
|
-
// that does not match has to be quoted.
|
|
463
|
-
//
|
|
464
|
-
// Shared rather than inlined because babel's builders do not validate: handing
|
|
465
|
-
// t.identifier() a name with a dash produces `{data-x: "1"}` in the output and
|
|
466
|
-
// no error anywhere, so the mistake surfaces as a parse failure in generated
|
|
467
|
-
// code. Two call sites had their own copy of this test and one of them was
|
|
468
|
-
// missing it entirely.
|
|
469
|
-
function propKey(name) {
|
|
470
|
-
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name) ? t.identifier(name) : t.stringLiteral(name);
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
// Handler-shaped attribute name, case-insensitive. Mirrors _isEventProp in
|
|
474
|
-
// what-core's dom.js.
|
|
475
|
-
function isEventAttrName(name) {
|
|
476
|
-
return !!name && name.length > 2 && /^on/i.test(name);
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
function createEventHandler(handler, modifiers) {
|
|
480
|
-
if (modifiers.length === 0) return handler;
|
|
481
|
-
|
|
482
|
-
let wrappedHandler = handler;
|
|
483
|
-
|
|
484
|
-
for (const mod of modifiers) {
|
|
485
|
-
switch (mod) {
|
|
486
|
-
case 'preventDefault':
|
|
487
|
-
wrappedHandler = t.arrowFunctionExpression(
|
|
488
|
-
[t.identifier('e')],
|
|
489
|
-
t.blockStatement([
|
|
490
|
-
t.expressionStatement(
|
|
491
|
-
t.callExpression(
|
|
492
|
-
t.memberExpression(t.identifier('e'), t.identifier('preventDefault')),
|
|
493
|
-
[]
|
|
494
|
-
)
|
|
495
|
-
),
|
|
496
|
-
t.expressionStatement(
|
|
497
|
-
t.callExpression(wrappedHandler, [t.identifier('e')])
|
|
498
|
-
)
|
|
499
|
-
])
|
|
500
|
-
);
|
|
501
|
-
break;
|
|
502
|
-
|
|
503
|
-
case 'stopPropagation':
|
|
504
|
-
wrappedHandler = t.arrowFunctionExpression(
|
|
505
|
-
[t.identifier('e')],
|
|
506
|
-
t.blockStatement([
|
|
507
|
-
t.expressionStatement(
|
|
508
|
-
t.callExpression(
|
|
509
|
-
t.memberExpression(t.identifier('e'), t.identifier('stopPropagation')),
|
|
510
|
-
[]
|
|
511
|
-
)
|
|
512
|
-
),
|
|
513
|
-
t.expressionStatement(
|
|
514
|
-
t.callExpression(wrappedHandler, [t.identifier('e')])
|
|
515
|
-
)
|
|
516
|
-
])
|
|
517
|
-
);
|
|
518
|
-
break;
|
|
519
|
-
|
|
520
|
-
case 'self':
|
|
521
|
-
wrappedHandler = t.arrowFunctionExpression(
|
|
522
|
-
[t.identifier('e')],
|
|
523
|
-
t.blockStatement([
|
|
524
|
-
t.ifStatement(
|
|
525
|
-
t.binaryExpression(
|
|
526
|
-
'===',
|
|
527
|
-
t.memberExpression(t.identifier('e'), t.identifier('target')),
|
|
528
|
-
t.memberExpression(t.identifier('e'), t.identifier('currentTarget'))
|
|
529
|
-
),
|
|
530
|
-
t.expressionStatement(
|
|
531
|
-
t.callExpression(wrappedHandler, [t.identifier('e')])
|
|
532
|
-
)
|
|
533
|
-
)
|
|
534
|
-
])
|
|
535
|
-
);
|
|
536
|
-
break;
|
|
537
|
-
|
|
538
|
-
case 'once':
|
|
539
|
-
case 'capture':
|
|
540
|
-
case 'passive':
|
|
541
|
-
break;
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
|
|
545
|
-
return wrappedHandler;
|
|
546
|
-
}
|
|
547
|
-
|
|
548
|
-
// =====================================================
|
|
549
|
-
// Reactivity Detection — Signal-Aware
|
|
550
|
-
// =====================================================
|
|
551
|
-
|
|
552
|
-
// Check if an identifier is known to be a signal (from useSignal/signal/computed/useState)
|
|
553
|
-
function isSignalIdentifier(name, signalNames) {
|
|
554
|
-
return signalNames.has(name);
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
// Collect signal identifiers using Babel's scope analysis.
|
|
558
|
-
// Walks the scope chain from the given path upward, collecting signals
|
|
559
|
-
// defined in each lexical scope (function/block).
|
|
560
|
-
function collectSignalNamesFromScope(path) {
|
|
561
|
-
const signalNames = new Set();
|
|
562
|
-
// Names that came from a DESTRUCTURED PROP rather than a signal() call.
|
|
563
|
-
//
|
|
564
|
-
// They belong in signalNames because they might hold an accessor and so
|
|
565
|
-
// must still be wrapped in an effect. They must NOT be auto-invoked: a prop
|
|
566
|
-
// is whatever the parent passed, and `_$createComponent` passes plain
|
|
567
|
-
// values, so `<span data-label={label}>` inside `({ label })` compiled to
|
|
568
|
-
// `setAttr(el, 'data-label', label())` and threw "label is not a function"
|
|
569
|
-
// on any ordinary string prop, blanking the whole component subtree.
|
|
570
|
-
//
|
|
571
|
-
// The same identifier as a CHILD compiled to `() => label`, uncalled, so
|
|
572
|
-
// the two positions disagreed inside a single element. The runtime setters
|
|
573
|
-
// (setAttr, setClass, setValue, ...) already resolve a function value
|
|
574
|
-
// reactively, so passing the identifier through uncalled is correct for
|
|
575
|
-
// both a plain value and an accessor.
|
|
576
|
-
const propNames = new Set();
|
|
577
|
-
signalNames.fromDestructuredProps = propNames;
|
|
578
|
-
|
|
579
|
-
// Helper: extract signal names from a VariableDeclarator node
|
|
580
|
-
function extractFromDeclarator(decl) {
|
|
581
|
-
const init = decl.init;
|
|
582
|
-
if (!init || !t.isCallExpression(init)) return;
|
|
583
|
-
|
|
584
|
-
const callee = init.callee;
|
|
585
|
-
let calleeName = '';
|
|
586
|
-
if (t.isIdentifier(callee)) {
|
|
587
|
-
calleeName = callee.name;
|
|
588
|
-
} else if (t.isMemberExpression(callee) && t.isIdentifier(callee.property)) {
|
|
589
|
-
calleeName = callee.property.name;
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
if (SIGNAL_CREATORS.has(calleeName)) {
|
|
593
|
-
const id = decl.id;
|
|
594
|
-
if (t.isIdentifier(id)) {
|
|
595
|
-
signalNames.add(id.name);
|
|
596
|
-
} else if (t.isArrayPattern(id)) {
|
|
597
|
-
for (const el of id.elements) {
|
|
598
|
-
if (t.isIdentifier(el)) signalNames.add(el.name);
|
|
599
|
-
}
|
|
600
|
-
} else if (t.isObjectPattern(id)) {
|
|
601
|
-
for (const prop of id.properties) {
|
|
602
|
-
if (t.isObjectProperty(prop) && t.isIdentifier(prop.value)) {
|
|
603
|
-
signalNames.add(prop.value.name);
|
|
604
|
-
}
|
|
605
|
-
}
|
|
606
|
-
}
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
function extractFromPattern(param) {
|
|
611
|
-
if (!t.isObjectPattern(param)) return;
|
|
612
|
-
for (const prop of param.properties) {
|
|
613
|
-
if (t.isObjectProperty(prop) && t.isIdentifier(prop.value)) {
|
|
614
|
-
signalNames.add(prop.value.name);
|
|
615
|
-
propNames.add(prop.value.name);
|
|
616
|
-
} else if (t.isRestElement(prop) && t.isIdentifier(prop.argument)) {
|
|
617
|
-
signalNames.add(prop.argument.name);
|
|
618
|
-
propNames.add(prop.argument.name);
|
|
619
|
-
}
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
|
|
623
|
-
// Walk up the scope chain using Babel's scope API.
|
|
624
|
-
let scope = path.scope;
|
|
625
|
-
while (scope) {
|
|
626
|
-
// Check all variable bindings in this scope.
|
|
627
|
-
for (const binding of Object.values(scope.bindings)) {
|
|
628
|
-
if (binding.path.isVariableDeclarator()) {
|
|
629
|
-
extractFromDeclarator(binding.path.node);
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
// Scan this scope's own function params (destructured props) ONCE per
|
|
633
|
-
// scope — not once per binding. The old per-binding rescan made this
|
|
634
|
-
// O(params × bindings) per scope per JSXElement. (AUDIT-2026-06-06 H2)
|
|
635
|
-
const fnNode = scope.path && scope.path.node;
|
|
636
|
-
if (fnNode) {
|
|
637
|
-
if (fnNode.params) {
|
|
638
|
-
for (const param of fnNode.params) extractFromPattern(param);
|
|
639
|
-
}
|
|
640
|
-
// deferForwardedChildren moved this pattern out of the parameter list;
|
|
641
|
-
// it is still the same props destructuring and classifies the same way.
|
|
642
|
-
if (fnNode._whatMovedProps) extractFromPattern(fnNode._whatMovedProps);
|
|
643
|
-
}
|
|
644
|
-
scope = scope.parent;
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
return signalNames;
|
|
648
|
-
}
|
|
649
|
-
|
|
650
|
-
// A `collectSignalNames` wrapper lived here, commented "legacy wrapper for
|
|
651
|
-
// backward compat (used in collectSignalNames calls)". Nothing called it;
|
|
652
|
-
// every call site uses collectSignalNamesFromScope directly.
|
|
653
|
-
|
|
654
|
-
// `x.toUpperCase()` and friends, listed in PURE_BUILTIN_METHODS. Only the method
|
|
655
|
-
// name is checked: whether the RECEIVER is reactive is decided separately, so
|
|
656
|
-
// `user().name.trim()` stays reactive through its object.
|
|
657
|
-
function isPureBuiltinMethodCall(expr) {
|
|
658
|
-
return t.isMemberExpression(expr.callee)
|
|
659
|
-
&& !expr.callee.computed
|
|
660
|
-
&& t.isIdentifier(expr.callee.property)
|
|
661
|
-
&& PURE_BUILTIN_METHODS.has(expr.callee.property.name);
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
// Check if a call expression is a safe (non-reactive) global call
|
|
665
|
-
function isSafeGlobalCall(expr) {
|
|
666
|
-
if (!t.isCallExpression(expr)) return false;
|
|
667
|
-
const callee = expr.callee;
|
|
668
|
-
|
|
669
|
-
// Math.max(), Number.parseInt(), etc.
|
|
670
|
-
if (t.isMemberExpression(callee) && t.isIdentifier(callee.object)) {
|
|
671
|
-
return SAFE_GLOBAL_CALLS.has(callee.object.name);
|
|
672
|
-
}
|
|
673
|
-
|
|
674
|
-
// parseInt(), isNaN(), etc.
|
|
675
|
-
if (t.isIdentifier(callee)) {
|
|
676
|
-
return SAFE_GLOBAL_CALLS.has(callee.name);
|
|
677
|
-
}
|
|
678
|
-
|
|
679
|
-
return false;
|
|
680
|
-
}
|
|
681
|
-
|
|
682
|
-
// Check if an expression's reactivity is uncertain — e.g., a non-signal function call
|
|
683
|
-
// whose arguments happen to contain signal reads. The function itself may not produce
|
|
684
|
-
// a reactive result, so the compiler wraps it conservatively.
|
|
685
|
-
function isUncertainReactive(expr, signalNames, importedIds) {
|
|
686
|
-
if (!signalNames) return false;
|
|
687
|
-
if (t.isCallExpression(expr)) {
|
|
688
|
-
// Callee is a known signal — definitely reactive, not uncertain
|
|
689
|
-
if (t.isIdentifier(expr.callee) && isSignalIdentifier(expr.callee.name, signalNames)) {
|
|
690
|
-
return false;
|
|
691
|
-
}
|
|
692
|
-
// Imported identifier called as function — definitely reactive (not uncertain)
|
|
693
|
-
if (importedIds && t.isIdentifier(expr.callee) && importedIds.has(expr.callee.name) &&
|
|
694
|
-
!SAFE_GLOBAL_CALLS.has(expr.callee.name)) {
|
|
695
|
-
return false;
|
|
696
|
-
}
|
|
697
|
-
// Callee is a member of a known signal — definitely reactive
|
|
698
|
-
if (t.isMemberExpression(expr.callee) && t.isIdentifier(expr.callee.object) &&
|
|
699
|
-
isSignalIdentifier(expr.callee.object.name, signalNames)) {
|
|
700
|
-
return false;
|
|
701
|
-
}
|
|
702
|
-
// Safe global call (Math.max, etc.) with reactive args — still deterministic, not uncertain
|
|
703
|
-
if (isSafeGlobalCall(expr)) return false;
|
|
704
|
-
// Unknown function call — if args are reactive, the wrapping is uncertain
|
|
705
|
-
if (expr.arguments.some(arg => isPotentiallyReactive(arg, signalNames, importedIds))) {
|
|
706
|
-
return true;
|
|
707
|
-
}
|
|
708
|
-
}
|
|
709
|
-
return false;
|
|
710
|
-
}
|
|
711
|
-
|
|
712
|
-
// Check if an expression is potentially reactive (reads a signal)
|
|
713
|
-
// importedIds: Set of identifiers imported from other modules — any imported
|
|
714
|
-
// function call is conservatively treated as potentially reactive since the
|
|
715
|
-
// imported binding could be a signal from another file.
|
|
716
|
-
function isPotentiallyReactive(expr, signalNames, importedIds) {
|
|
717
|
-
if (!signalNames) signalNames = new Set();
|
|
718
|
-
|
|
719
|
-
if (t.isCallExpression(expr)) {
|
|
720
|
-
// If callee is a known signal identifier being called (signal read), it's reactive
|
|
721
|
-
if (t.isIdentifier(expr.callee) && isSignalIdentifier(expr.callee.name, signalNames)) {
|
|
722
|
-
return true;
|
|
723
|
-
}
|
|
724
|
-
// Imported identifier called as a function — conservatively reactive.
|
|
725
|
-
// Handles: import { count } from './store'; ... {count()} in JSX
|
|
726
|
-
if (importedIds && t.isIdentifier(expr.callee) && importedIds.has(expr.callee.name)) {
|
|
727
|
-
// Exclude known safe globals that happen to also be imported
|
|
728
|
-
if (!SAFE_GLOBAL_CALLS.has(expr.callee.name)) {
|
|
729
|
-
return true;
|
|
730
|
-
}
|
|
731
|
-
}
|
|
732
|
-
// member.call() — e.g., data(), isLoading()
|
|
733
|
-
if (t.isMemberExpression(expr.callee)) {
|
|
734
|
-
// Check if the object is a signal
|
|
735
|
-
if (t.isIdentifier(expr.callee.object) && isSignalIdentifier(expr.callee.object.name, signalNames)) {
|
|
736
|
-
return true;
|
|
737
|
-
}
|
|
738
|
-
}
|
|
739
|
-
// Safe global calls like Math.max — only reactive if their args are
|
|
740
|
-
if (isSafeGlobalCall(expr)) {
|
|
741
|
-
return expr.arguments.some(arg => isPotentiallyReactive(arg, signalNames, importedIds));
|
|
742
|
-
}
|
|
743
|
-
// Any other zero-argument call has the shape of an accessor read, so it
|
|
744
|
-
// is assumed to be one. `props.count()`, a plain parameter `count()` and
|
|
745
|
-
// `s()` from `const s = useThing()` are all opaque to the compiler: it
|
|
746
|
-
// knows only the names it watched being created. Assuming the narrow way
|
|
747
|
-
// round meant those three froze silently while the docs promised
|
|
748
|
-
// `{count()}` was reactive. Assuming this way round costs, when the call
|
|
749
|
-
// turns out to be constant, one effect that runs once and never again.
|
|
750
|
-
if (expr.arguments.length === 0 && !isPureBuiltinMethodCall(expr)) {
|
|
751
|
-
return true;
|
|
752
|
-
}
|
|
753
|
-
|
|
754
|
-
// Unknown call — check if callee or args contain signal reads
|
|
755
|
-
if (t.isIdentifier(expr.callee)) {
|
|
756
|
-
// Could be a function that reads signals internally
|
|
757
|
-
// Be conservative: if it's not a known safe call and not a signal, still check args
|
|
758
|
-
return expr.arguments.some(arg => isPotentiallyReactive(arg, signalNames, importedIds));
|
|
759
|
-
}
|
|
760
|
-
// For any other call expression, check recursively
|
|
761
|
-
return isPotentiallyReactive(expr.callee, signalNames, importedIds) ||
|
|
762
|
-
expr.arguments.some(arg => isPotentiallyReactive(arg, signalNames, importedIds));
|
|
763
|
-
}
|
|
764
|
-
|
|
765
|
-
if (t.isIdentifier(expr)) {
|
|
766
|
-
return isSignalIdentifier(expr.name, signalNames) ||
|
|
767
|
-
(importedIds && importedIds.has(expr.name));
|
|
768
|
-
}
|
|
769
|
-
|
|
770
|
-
if (t.isMemberExpression(expr)) {
|
|
771
|
-
return isPotentiallyReactive(expr.object, signalNames, importedIds);
|
|
772
|
-
}
|
|
773
|
-
|
|
774
|
-
if (t.isConditionalExpression(expr)) {
|
|
775
|
-
return isPotentiallyReactive(expr.test, signalNames, importedIds) ||
|
|
776
|
-
isPotentiallyReactive(expr.consequent, signalNames, importedIds) ||
|
|
777
|
-
isPotentiallyReactive(expr.alternate, signalNames, importedIds);
|
|
778
|
-
}
|
|
779
|
-
|
|
780
|
-
if (t.isBinaryExpression(expr) || t.isLogicalExpression(expr)) {
|
|
781
|
-
return isPotentiallyReactive(expr.left, signalNames, importedIds) ||
|
|
782
|
-
isPotentiallyReactive(expr.right, signalNames, importedIds);
|
|
783
|
-
}
|
|
784
|
-
|
|
785
|
-
if (t.isUnaryExpression(expr)) {
|
|
786
|
-
return isPotentiallyReactive(expr.argument, signalNames, importedIds);
|
|
787
|
-
}
|
|
788
|
-
|
|
789
|
-
if (t.isTemplateLiteral(expr)) {
|
|
790
|
-
return expr.expressions.some(e => isPotentiallyReactive(e, signalNames, importedIds));
|
|
791
|
-
}
|
|
792
|
-
|
|
793
|
-
if (t.isObjectExpression(expr)) {
|
|
794
|
-
return expr.properties.some(prop =>
|
|
795
|
-
t.isObjectProperty(prop) && isPotentiallyReactive(prop.value, signalNames, importedIds)
|
|
796
|
-
);
|
|
797
|
-
}
|
|
798
|
-
|
|
799
|
-
if (t.isArrayExpression(expr)) {
|
|
800
|
-
return expr.elements.some(el => el && isPotentiallyReactive(el, signalNames, importedIds));
|
|
801
|
-
}
|
|
802
|
-
|
|
803
|
-
if (t.isArrowFunctionExpression(expr) || t.isFunctionExpression(expr)) {
|
|
804
|
-
// Function expressions are not reactive themselves — they're callbacks
|
|
805
|
-
return false;
|
|
806
|
-
}
|
|
807
|
-
|
|
808
|
-
return false;
|
|
809
|
-
}
|
|
810
|
-
|
|
811
|
-
// Names bound by a parameter pattern. Destructuring counts, so
|
|
812
|
-
// `({ id }, i) => <li key={id}>` binds `id` and a key of `id` resolves fine.
|
|
813
|
-
function collectPatternNames(node, out) {
|
|
814
|
-
if (!node || typeof node !== 'object') return out;
|
|
815
|
-
switch (node.type) {
|
|
816
|
-
case 'Identifier': out.add(node.name); break;
|
|
817
|
-
case 'AssignmentPattern': collectPatternNames(node.left, out); break;
|
|
818
|
-
case 'RestElement': collectPatternNames(node.argument, out); break;
|
|
819
|
-
case 'ArrayPattern':
|
|
820
|
-
for (const el of node.elements) collectPatternNames(el, out);
|
|
821
|
-
break;
|
|
822
|
-
case 'ObjectPattern':
|
|
823
|
-
for (const p of node.properties) {
|
|
824
|
-
collectPatternNames(p.type === 'RestElement' ? p.argument : p.value, out);
|
|
825
|
-
}
|
|
826
|
-
break;
|
|
827
|
-
default: break;
|
|
828
|
-
}
|
|
829
|
-
return out;
|
|
830
|
-
}
|
|
831
|
-
|
|
832
|
-
// The key function is extracted OUT of the map callback and rebuilt as
|
|
833
|
-
// `(item) => keyExpr`, taking only the first parameter. So any name the key
|
|
834
|
-
// expression gets from somewhere else inside the callback becomes a free
|
|
835
|
-
// variable in the emitted code. This collects exactly those names: the
|
|
836
|
-
// parameters after the first, and everything declared in the callback body
|
|
837
|
-
// that is in scope at the return.
|
|
838
|
-
//
|
|
839
|
-
// Nested function bodies are deliberately not descended into. Their bindings
|
|
840
|
-
// cannot reach the return expression, so counting them would reject keys that
|
|
841
|
-
// are perfectly fine. A nested function's own name is hoisted, so that one
|
|
842
|
-
// is collected.
|
|
843
|
-
function namesInvisibleToKeyFn(mapFn) {
|
|
844
|
-
const out = new Set();
|
|
845
|
-
for (let i = 1; i < mapFn.params.length; i++) collectPatternNames(mapFn.params[i], out);
|
|
846
|
-
|
|
847
|
-
const visit = (node) => {
|
|
848
|
-
if (!node || typeof node !== 'object') return;
|
|
849
|
-
if (Array.isArray(node)) { node.forEach(visit); return; }
|
|
850
|
-
switch (node.type) {
|
|
851
|
-
case 'VariableDeclaration':
|
|
852
|
-
for (const d of node.declarations) collectPatternNames(d.id, out);
|
|
853
|
-
return;
|
|
854
|
-
case 'FunctionDeclaration':
|
|
855
|
-
case 'ClassDeclaration':
|
|
856
|
-
if (node.id) out.add(node.id.name);
|
|
857
|
-
return; // body is its own scope
|
|
858
|
-
case 'FunctionExpression':
|
|
859
|
-
case 'ArrowFunctionExpression':
|
|
860
|
-
case 'ClassExpression':
|
|
861
|
-
return; // own scope
|
|
862
|
-
case 'CatchClause':
|
|
863
|
-
collectPatternNames(node.param, out);
|
|
864
|
-
visit(node.body);
|
|
865
|
-
return;
|
|
866
|
-
case 'ForStatement':
|
|
867
|
-
case 'ForInStatement':
|
|
868
|
-
case 'ForOfStatement':
|
|
869
|
-
visit(node.init); visit(node.left); visit(node.body);
|
|
870
|
-
return;
|
|
871
|
-
default: break;
|
|
872
|
-
}
|
|
873
|
-
for (const k of Object.keys(node)) {
|
|
874
|
-
if (k === 'loc' || k === 'start' || k === 'end' || k === 'type' ||
|
|
875
|
-
k === 'leadingComments' || k === 'trailingComments' || k === 'innerComments') continue;
|
|
876
|
-
const v = node[k];
|
|
877
|
-
if (v && typeof v === 'object') visit(v);
|
|
878
|
-
}
|
|
879
|
-
};
|
|
880
|
-
|
|
881
|
-
if (t.isBlockStatement(mapFn.body)) visit(mapFn.body.body);
|
|
882
|
-
|
|
883
|
-
// The first parameter IS passed to the key function, so anything it binds
|
|
884
|
-
// stays visible even if a nested scope happens to reuse the name.
|
|
885
|
-
for (const name of collectPatternNames(mapFn.params[0], new Set())) out.delete(name);
|
|
886
|
-
return out;
|
|
887
|
-
}
|
|
888
|
-
|
|
889
|
-
// Does `node` reference any of `names` as a value? Property positions are
|
|
890
|
-
// skipped so `item.i` does not look like a use of `i`, but the check is
|
|
891
|
-
// otherwise deliberately generous: a false positive costs keyed
|
|
892
|
-
// reconciliation, a false negative ships a ReferenceError.
|
|
893
|
-
function referencesAny(node, names) {
|
|
894
|
-
if (names.size === 0) return null;
|
|
895
|
-
let found = null;
|
|
896
|
-
const visit = (n) => {
|
|
897
|
-
if (found || !n || typeof n !== 'object') return;
|
|
898
|
-
if (Array.isArray(n)) { n.forEach(visit); return; }
|
|
899
|
-
if (n.type === 'Identifier') {
|
|
900
|
-
if (names.has(n.name)) found = n.name;
|
|
901
|
-
return;
|
|
902
|
-
}
|
|
903
|
-
for (const k of Object.keys(n)) {
|
|
904
|
-
if (k === 'loc' || k === 'start' || k === 'end' || k === 'type' ||
|
|
905
|
-
k === 'leadingComments' || k === 'trailingComments' || k === 'innerComments') continue;
|
|
906
|
-
if (n.type === 'MemberExpression' && k === 'property' && !n.computed) continue;
|
|
907
|
-
if ((n.type === 'ObjectProperty' || n.type === 'ObjectMethod') && k === 'key' && !n.computed) continue;
|
|
908
|
-
const v = n[k];
|
|
909
|
-
if (v && typeof v === 'object') visit(v);
|
|
910
|
-
}
|
|
911
|
-
};
|
|
912
|
-
visit(node);
|
|
913
|
-
return found;
|
|
914
|
-
}
|
|
915
|
-
|
|
916
|
-
// --- Auto-lower .map() to mapArray ---
|
|
917
|
-
// Detects: source().map((item) => <Comp key={expr} .../>)
|
|
918
|
-
// or wrapped in an arrow: () => source().map(...)
|
|
919
|
-
// Also walks into ternary (cond ? a.map(...) : fallback) and
|
|
920
|
-
// logical (cond && a.map(...)) expressions so React-style
|
|
921
|
-
// conditional list patterns get keyed reconciliation.
|
|
922
|
-
// Produces: _$mapArray(source, (item) => <Comp .../>, { key: item => expr })
|
|
923
|
-
function tryLowerMapToMapArray(expr, state) {
|
|
924
|
-
// Unwrap arrow function: () => source().map(...)
|
|
925
|
-
let mapCall = expr;
|
|
926
|
-
let wrappedInArrow = false;
|
|
927
|
-
if (t.isArrowFunctionExpression(expr) && expr.params.length === 0) {
|
|
928
|
-
mapCall = expr.body;
|
|
929
|
-
wrappedInArrow = true;
|
|
930
|
-
}
|
|
931
|
-
|
|
932
|
-
// Walk into ternary: cond ? arr().map(...) : fallback
|
|
933
|
-
if (t.isConditionalExpression(mapCall)) {
|
|
934
|
-
const loweredCon = tryLowerMapCall(mapCall.consequent, state);
|
|
935
|
-
const loweredAlt = tryLowerMapCall(mapCall.alternate, state);
|
|
936
|
-
if (loweredCon || loweredAlt) {
|
|
937
|
-
const result = t.conditionalExpression(
|
|
938
|
-
mapCall.test,
|
|
939
|
-
loweredCon || mapCall.consequent,
|
|
940
|
-
loweredAlt || mapCall.alternate
|
|
941
|
-
);
|
|
942
|
-
return wrappedInArrow ? t.arrowFunctionExpression([], result) : result;
|
|
943
|
-
}
|
|
944
|
-
return null;
|
|
945
|
-
}
|
|
946
|
-
|
|
947
|
-
// Walk into logical: cond && arr().map(...)
|
|
948
|
-
if (t.isLogicalExpression(mapCall) && (mapCall.operator === '&&' || mapCall.operator === '||')) {
|
|
949
|
-
const loweredRight = tryLowerMapCall(mapCall.right, state);
|
|
950
|
-
if (loweredRight) {
|
|
951
|
-
const result = t.logicalExpression(mapCall.operator, mapCall.left, loweredRight);
|
|
952
|
-
return wrappedInArrow ? t.arrowFunctionExpression([], result) : result;
|
|
953
|
-
}
|
|
954
|
-
return null;
|
|
955
|
-
}
|
|
956
|
-
|
|
957
|
-
// Direct .map() call
|
|
958
|
-
const lowered = tryLowerMapCall(mapCall, state);
|
|
959
|
-
return lowered;
|
|
960
|
-
}
|
|
961
|
-
|
|
962
|
-
// Core .map() lowering — extracted so it can be called per-branch
|
|
963
|
-
function tryLowerMapCall(mapCall, state) {
|
|
964
|
-
// Check: something.map(fn)
|
|
965
|
-
if (!t.isCallExpression(mapCall)) return null;
|
|
966
|
-
if (!t.isMemberExpression(mapCall.callee)) return null;
|
|
967
|
-
if (!t.isIdentifier(mapCall.callee.property, { name: 'map' })) return null;
|
|
968
|
-
if (mapCall.arguments.length < 1) return null;
|
|
969
|
-
|
|
970
|
-
const mapFn = mapCall.arguments[0];
|
|
971
|
-
if (!t.isArrowFunctionExpression(mapFn) && !t.isFunctionExpression(mapFn)) return null;
|
|
972
|
-
|
|
973
|
-
// Get the map callback's return expression
|
|
974
|
-
/** @type {any} */
|
|
975
|
-
let returnExpr = null;
|
|
976
|
-
if (t.isArrowFunctionExpression(mapFn)) {
|
|
977
|
-
if (t.isExpression(mapFn.body)) {
|
|
978
|
-
returnExpr = mapFn.body;
|
|
979
|
-
} else if (t.isBlockStatement(mapFn.body)) {
|
|
980
|
-
const ret = mapFn.body.body.find(s => t.isReturnStatement(s));
|
|
981
|
-
if (ret) returnExpr = ret.argument;
|
|
982
|
-
}
|
|
983
|
-
} else if (t.isFunctionExpression(mapFn)) {
|
|
984
|
-
const ret = mapFn.body.body.find(s => t.isReturnStatement(s));
|
|
985
|
-
if (ret) returnExpr = ret.argument;
|
|
986
|
-
}
|
|
987
|
-
|
|
988
|
-
if (!returnExpr) return null;
|
|
989
|
-
|
|
990
|
-
// Check if the return is JSX with a `key` prop
|
|
991
|
-
if (!t.isJSXElement(returnExpr)) return null;
|
|
992
|
-
const attrs = returnExpr.openingElement.attributes;
|
|
993
|
-
/** @type {any} */
|
|
994
|
-
let keyAttr = null;
|
|
995
|
-
for (const attr of attrs) {
|
|
996
|
-
if (t.isJSXAttribute(attr) && getAttrName(attr) === 'key') {
|
|
997
|
-
keyAttr = attr;
|
|
998
|
-
break;
|
|
999
|
-
}
|
|
1000
|
-
}
|
|
1001
|
-
if (!keyAttr) {
|
|
1002
|
-
// JSX returned without a key — bail out, but warn at compile time so
|
|
1003
|
-
// users notice they're missing keyed reconciliation. Only warn in dev
|
|
1004
|
-
// (production builds are noiseless).
|
|
1005
|
-
//
|
|
1006
|
-
// The message names ERR_MISSING_KEY because that is the code the docs and
|
|
1007
|
-
// the MCP `what_fix` tool already publish for this exact mistake. Without
|
|
1008
|
-
// the code in the text there was nothing anywhere in the toolchain that
|
|
1009
|
-
// ever emitted it, so an agent reading the warning had no way to reach
|
|
1010
|
-
// the diagnosis and the worked example filed under that name. This is a
|
|
1011
|
-
// BUILD-time report, not a runtime one: whether a list has keys is
|
|
1012
|
-
// settled by the source, and the compiler is the only place that sees it.
|
|
1013
|
-
if (process.env.NODE_ENV !== 'production') {
|
|
1014
|
-
const loc = returnExpr.loc;
|
|
1015
|
-
const fileName = state.filename || state.file?.opts?.filename || '<unknown>';
|
|
1016
|
-
const lineInfo = loc ? `:${loc.start.line}:${loc.start.column}` : '';
|
|
1017
|
-
console.warn(
|
|
1018
|
-
`[what-compiler] ERR_MISSING_KEY: .map() returning JSX without a \`key\` prop at ${fileName}${lineInfo}. ` +
|
|
1019
|
-
`Without a key, the list cannot use keyed reconciliation — items are re-created on every update. ` +
|
|
1020
|
-
`Add key={...} to enable efficient updates. ` +
|
|
1021
|
-
`Run what_fix({ error: 'ERR_MISSING_KEY' }) for the worked example.`
|
|
1022
|
-
);
|
|
1023
|
-
}
|
|
1024
|
-
return null;
|
|
1025
|
-
}
|
|
1026
|
-
|
|
1027
|
-
// Extract the key expression
|
|
1028
|
-
const keyValue = getAttributeValue(keyAttr.value);
|
|
1029
|
-
if (!keyValue) return null;
|
|
1030
|
-
|
|
1031
|
-
// The key function is rebuilt as `(item) => keyExpr` and hoisted out of the
|
|
1032
|
-
// callback, so it only sees the first parameter. A key built from the index
|
|
1033
|
-
// (`key={i}`, the pattern the tutorial itself taught) compiled to
|
|
1034
|
-
// `key: t => i` with `i` free, and the failure was about as bad as it gets:
|
|
1035
|
-
// the list rendered correctly the first time, then the reconciler threw
|
|
1036
|
-
// `ReferenceError: i is not defined` inside its effect, the effect error
|
|
1037
|
-
// handler swallowed it to a single console.error, and the list stayed
|
|
1038
|
-
// frozen on its first render forever. Nothing visibly crashed. A key built
|
|
1039
|
-
// from a variable declared in the callback body failed the same way.
|
|
1040
|
-
//
|
|
1041
|
-
// Falling back is also the semantically right answer, not just the safe
|
|
1042
|
-
// one. A key derived from the index IS the position, so it carries no
|
|
1043
|
-
// identity across an update: an item that moves gets a different key and
|
|
1044
|
-
// reads as a different item. That is precisely what the unkeyed path
|
|
1045
|
-
// already does, correctly and more cheaply, so hand it that.
|
|
1046
|
-
const invisible = namesInvisibleToKeyFn(mapFn);
|
|
1047
|
-
const unreachable = referencesAny(keyValue, invisible);
|
|
1048
|
-
if (unreachable) {
|
|
1049
|
-
// A BARE index key (`key={i}`, exactly the second parameter and nothing
|
|
1050
|
-
// else) is deliberate and now behaves correctly, so it gets no warning.
|
|
1051
|
-
// The author wrote "position is identity", positional reconciliation is
|
|
1052
|
-
// precisely that, and there is no edit that would improve the output. The
|
|
1053
|
-
// framework's own tutorial keys a fixed nine-square board this way, where
|
|
1054
|
-
// it is not merely acceptable but the right answer, and a build-time
|
|
1055
|
-
// warning on step two of a beginner tutorial reads as something being
|
|
1056
|
-
// broken when nothing is.
|
|
1057
|
-
//
|
|
1058
|
-
// Everything else still warns, because everything else looks stable and is
|
|
1059
|
-
// not: `key={`${t.type}-${i}`}` reads like a composite identity but changes
|
|
1060
|
-
// the moment a row moves, and a key built from a variable declared in the
|
|
1061
|
-
// callback body would have been a ReferenceError before this fallback
|
|
1062
|
-
// existed. Those are worth interrupting someone over. A bare index is not.
|
|
1063
|
-
const isBareIndex = t.isIdentifier(keyValue)
|
|
1064
|
-
&& mapFn.params[1]
|
|
1065
|
-
&& t.isIdentifier(mapFn.params[1], { name: keyValue.name });
|
|
1066
|
-
|
|
1067
|
-
if (!isBareIndex && process.env.NODE_ENV !== 'production') {
|
|
1068
|
-
const loc = returnExpr.loc;
|
|
1069
|
-
const fileName = state.filename || state.file?.opts?.filename || '<unknown>';
|
|
1070
|
-
const lineInfo = loc ? `:${loc.start.line}:${loc.start.column}` : '';
|
|
1071
|
-
const usesIndex = mapFn.params[1] && t.isIdentifier(mapFn.params[1], { name: unreachable });
|
|
1072
|
-
console.warn(
|
|
1073
|
-
`[what-compiler] key={...} at ${fileName}${lineInfo} reads \`${unreachable}\`, which is not available ` +
|
|
1074
|
-
`to the key function (it only receives the item). ` +
|
|
1075
|
-
(usesIndex
|
|
1076
|
-
? `A key built from the index is the item's position, not its identity, so it cannot survive a reorder. `
|
|
1077
|
-
: `\`${unreachable}\` is declared inside the map callback. `) +
|
|
1078
|
-
`Falling back to positional reconciliation. Key by something stable on the item (key={item.id}) ` +
|
|
1079
|
-
`to get keyed reconciliation.`
|
|
1080
|
-
);
|
|
1081
|
-
}
|
|
1082
|
-
return null;
|
|
1083
|
-
}
|
|
1084
|
-
|
|
1085
|
-
// Remove the key prop from the JSX element (mapArray handles keying, not the DOM)
|
|
1086
|
-
returnExpr.openingElement.attributes = attrs.filter(a => a !== keyAttr);
|
|
1087
|
-
|
|
1088
|
-
// Build the source: the object before .map() — wrap in an arrow for reactive access
|
|
1089
|
-
const sourceObj = mapCall.callee.object;
|
|
1090
|
-
const source = t.arrowFunctionExpression([], sourceObj);
|
|
1091
|
-
|
|
1092
|
-
// Build the key function: (item) => keyExpr.
|
|
1093
|
-
// Clone both the parameter and the key expression — the parameter is shared
|
|
1094
|
-
// with the user's map callback AST and keyValue may be referenced elsewhere
|
|
1095
|
-
// in the tree. Cloning insulates this new arrow from later mutations.
|
|
1096
|
-
const itemParam = mapFn.params[0] ? t.cloneNode(mapFn.params[0], true) : t.identifier('_item');
|
|
1097
|
-
const keyFn = t.arrowFunctionExpression([itemParam], t.cloneNode(keyValue, true));
|
|
1098
|
-
|
|
1099
|
-
// Build: _$mapArray(source, mapFn, { key: keyFn, raw: true })
|
|
1100
|
-
// raw: true means mapFn receives the raw item value (not a signal accessor),
|
|
1101
|
-
// matching user-authored .map() semantics where `item.prop` accesses values directly.
|
|
1102
|
-
return t.callExpression(t.identifier('_$mapArray'), [
|
|
1103
|
-
source,
|
|
1104
|
-
mapFn,
|
|
1105
|
-
t.objectExpression([
|
|
1106
|
-
t.objectProperty(t.identifier('key'), keyFn),
|
|
1107
|
-
t.objectProperty(t.identifier('raw'), t.booleanLiteral(true))
|
|
1108
|
-
])
|
|
1109
|
-
]);
|
|
1110
|
-
}
|
|
1111
|
-
|
|
1112
|
-
// =====================================================
|
|
1113
|
-
// Fine-Grained Mode (template + insert + effect)
|
|
1114
|
-
// =====================================================
|
|
1115
|
-
|
|
1116
|
-
// Check if a JSX child is static (no expressions)
|
|
1117
|
-
function isStaticChild(child) {
|
|
1118
|
-
if (t.isJSXText(child)) return true;
|
|
1119
|
-
if (t.isJSXExpressionContainer(child)) return false;
|
|
1120
|
-
if (t.isJSXElement(child)) {
|
|
1121
|
-
const el = child.openingElement;
|
|
1122
|
-
if (isComponentElement(child)) return false;
|
|
1123
|
-
for (const attr of el.attributes) {
|
|
1124
|
-
if (t.isJSXSpreadAttribute(attr)) return false;
|
|
1125
|
-
const value = attr.value;
|
|
1126
|
-
if (t.isJSXExpressionContainer(value)) return false;
|
|
1127
|
-
}
|
|
1128
|
-
return child.children.every(isStaticChild);
|
|
1129
|
-
}
|
|
1130
|
-
return false;
|
|
1131
|
-
}
|
|
1132
|
-
|
|
1133
|
-
// Check if an attribute value is dynamic
|
|
1134
|
-
function isDynamicAttr(attr) {
|
|
1135
|
-
if (t.isJSXSpreadAttribute(attr)) return true;
|
|
1136
|
-
if (!attr.value) return false;
|
|
1137
|
-
return t.isJSXExpressionContainer(attr.value);
|
|
1138
|
-
}
|
|
1139
|
-
|
|
1140
|
-
// The child slots a fragment contributes to its parent, flattened.
|
|
1141
|
-
//
|
|
1142
|
-
// A fragment renders no node of its own, so each of its children takes a
|
|
1143
|
-
// sibling position in the parent exactly as if the fragment were not written.
|
|
1144
|
-
// extractStaticHTML() and applyDynamicChildren() both read this list, so the
|
|
1145
|
-
// markers baked into the template and the inserts emitted against them can
|
|
1146
|
-
// never disagree about how many positions the fragment occupies.
|
|
1147
|
-
//
|
|
1148
|
-
// Nested fragments flatten too: `<><>a</>b</>` is two slots in the parent.
|
|
1149
|
-
// Whitespace-only text and `{/* comment */}` contribute nothing, matching how
|
|
1150
|
-
// the same children are treated directly under an element.
|
|
1151
|
-
function fragmentSlots(fragmentNode, out = []) {
|
|
1152
|
-
for (const child of fragmentNode.children) {
|
|
1153
|
-
if (t.isJSXText(child)) {
|
|
1154
|
-
const text = normalizeJsxText(child.value);
|
|
1155
|
-
if (text) out.push({ kind: 'text', text });
|
|
1156
|
-
continue;
|
|
1157
|
-
}
|
|
1158
|
-
if (t.isJSXFragment(child)) {
|
|
1159
|
-
fragmentSlots(child, out);
|
|
1160
|
-
continue;
|
|
1161
|
-
}
|
|
1162
|
-
if (t.isJSXExpressionContainer(child)) {
|
|
1163
|
-
if (!t.isJSXEmptyExpression(child.expression)) out.push({ kind: 'expression', child });
|
|
1164
|
-
continue;
|
|
1165
|
-
}
|
|
1166
|
-
if (t.isJSXElement(child)) out.push({ kind: 'element', child });
|
|
1167
|
-
}
|
|
1168
|
-
return out;
|
|
1169
|
-
}
|
|
1170
|
-
|
|
1171
|
-
// Extract static HTML from JSX element for template()
|
|
1172
|
-
function extractStaticHTML(node) {
|
|
1173
|
-
if (t.isJSXText(node)) {
|
|
1174
|
-
const text = normalizeJsxText(node.value);
|
|
1175
|
-
return text ? escapeHTML(text) : '';
|
|
1176
|
-
}
|
|
1177
|
-
|
|
1178
|
-
if (t.isJSXExpressionContainer(node)) {
|
|
1179
|
-
if (t.isJSXEmptyExpression(node.expression)) return '';
|
|
1180
|
-
return '<!--$-->';
|
|
1181
|
-
}
|
|
1182
|
-
|
|
1183
|
-
if (!t.isJSXElement(node)) return '';
|
|
1184
|
-
|
|
1185
|
-
const el = node.openingElement;
|
|
1186
|
-
const tagName = el.name.name;
|
|
1187
|
-
|
|
1188
|
-
if (isComponentElement(node)) return '';
|
|
1189
|
-
|
|
1190
|
-
let html = `<${tagName}`;
|
|
1191
|
-
|
|
1192
|
-
// A static attribute written AFTER a spread cannot be baked into the
|
|
1193
|
-
// template. The template is applied first and the spread runs against the
|
|
1194
|
-
// finished element, so baking would let the spread overwrite an attribute
|
|
1195
|
-
// the author pinned after it: `<div {...{id:'a'}} id="b"/>` rendered id="a"
|
|
1196
|
-
// while the h() spelling of the same tree renders id="b". Everything from
|
|
1197
|
-
// the first spread onward is emitted as an ordered runtime set instead, in
|
|
1198
|
-
// applyDynamicAttrs.
|
|
1199
|
-
const firstSpread = el.attributes.findIndex(a => t.isJSXSpreadAttribute(a));
|
|
1200
|
-
|
|
1201
|
-
for (const [attrIndex, attr] of el.attributes.entries()) {
|
|
1202
|
-
if (t.isJSXSpreadAttribute(attr)) continue;
|
|
1203
|
-
if (firstSpread !== -1 && attrIndex > firstSpread) continue;
|
|
1204
|
-
if (isShadowedAttr(el.attributes, attrIndex)) continue;
|
|
1205
|
-
const name = getAttrName(attr);
|
|
1206
|
-
if (name === 'key') continue;
|
|
1207
|
-
// Case-insensitive: a static template is applied via innerHTML, so an
|
|
1208
|
-
// `ONCLICK="alert(1)"` baked into the string becomes a live handler.
|
|
1209
|
-
// Lowercase handlers are compiled separately; uppercase ones are dropped,
|
|
1210
|
-
// matching how the runtime and SSR paths treat them.
|
|
1211
|
-
if (isEventAttrName(name) || name.startsWith('bind:') || name.includes('|')) continue;
|
|
1212
|
-
|
|
1213
|
-
const domName = normalizeAttrName(name);
|
|
1214
|
-
|
|
1215
|
-
if (!attr.value) {
|
|
1216
|
-
html += ` ${domName}`;
|
|
1217
|
-
} else if (t.isStringLiteral(attr.value)) {
|
|
1218
|
-
html += ` ${domName}="${escapeAttr(attr.value.value)}"`;
|
|
1219
|
-
} else if (t.isJSXExpressionContainer(attr.value)) {
|
|
1220
|
-
continue; // Dynamic attr — set via effect
|
|
1221
|
-
}
|
|
1222
|
-
}
|
|
1223
|
-
|
|
1224
|
-
const selfClosing = node.openingElement.selfClosing;
|
|
1225
|
-
if (selfClosing && isVoidHtmlElement(tagName)) {
|
|
1226
|
-
html += '>';
|
|
1227
|
-
return html;
|
|
1228
|
-
}
|
|
1229
|
-
|
|
1230
|
-
if (selfClosing) {
|
|
1231
|
-
html += `></${tagName}>`;
|
|
1232
|
-
return html;
|
|
1233
|
-
}
|
|
1234
|
-
|
|
1235
|
-
html += '>';
|
|
1236
|
-
|
|
1237
|
-
for (const child of node.children) {
|
|
1238
|
-
if (t.isJSXText(child)) {
|
|
1239
|
-
const text = normalizeJsxText(child.value);
|
|
1240
|
-
if (text) html += escapeHTML(text);
|
|
1241
|
-
} else if (t.isJSXExpressionContainer(child)) {
|
|
1242
|
-
if (!t.isJSXEmptyExpression(child.expression)) {
|
|
1243
|
-
html += '<!--$-->';
|
|
1244
|
-
}
|
|
1245
|
-
} else if (t.isJSXElement(child)) {
|
|
1246
|
-
if (isComponentElement(child)) {
|
|
1247
|
-
html += '<!--$-->';
|
|
1248
|
-
} else {
|
|
1249
|
-
html += extractStaticHTML(child);
|
|
1250
|
-
}
|
|
1251
|
-
} else if (t.isJSXFragment(child)) {
|
|
1252
|
-
// One marker PER fragment slot, not one for the whole fragment. A
|
|
1253
|
-
// fragment is not a DOM boundary, so its children are siblings of the
|
|
1254
|
-
// fragment's siblings and each needs its own anchor to keep its place.
|
|
1255
|
-
// With a single shared anchor the order held at mount and then broke on
|
|
1256
|
-
// the first re-run: reconcileInsert re-places a reactive region before
|
|
1257
|
-
// that anchor, which puts it after every sibling that had been inserted
|
|
1258
|
-
// before the same anchor earlier.
|
|
1259
|
-
html += '<!--$-->'.repeat(fragmentSlots(child).length);
|
|
1260
|
-
}
|
|
1261
|
-
}
|
|
1262
|
-
|
|
1263
|
-
html += `</${tagName}>`;
|
|
1264
|
-
return html;
|
|
1265
|
-
}
|
|
1266
|
-
|
|
1267
|
-
function escapeHTML(str) {
|
|
1268
|
-
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
1269
|
-
}
|
|
1270
|
-
|
|
1271
|
-
function escapeAttr(str) {
|
|
1272
|
-
return str.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
|
|
1273
|
-
}
|
|
1274
|
-
|
|
1275
|
-
// Analyze JSX tree and generate fine-grained output
|
|
1276
|
-
function transformElementFineGrained(path, state) {
|
|
1277
|
-
const { node } = path;
|
|
1278
|
-
const openingElement = node.openingElement;
|
|
1279
|
-
const tagName = openingElement.name.name;
|
|
1280
|
-
|
|
1281
|
-
// Control flow components, checked before generic isComponent since they start uppercase.
|
|
1282
|
-
// A tag imported from somewhere other than What is that package's component,
|
|
1283
|
-
// whatever it is called, so it goes to the component path untouched, unless
|
|
1284
|
-
// its own arms prove otherwise.
|
|
1285
|
-
if (!isForeignTag(tagName, state)) {
|
|
1286
|
-
if (tagName === 'For') {
|
|
1287
|
-
return transformForFineGrained(path, state);
|
|
1288
|
-
}
|
|
1289
|
-
if (tagName === 'Show') {
|
|
1290
|
-
return transformShowFineGrained(path, state);
|
|
1291
|
-
}
|
|
1292
|
-
}
|
|
1293
|
-
if (tagName === 'Switch' && (!isForeignTag(tagName, state) || hasLiteralMatchArms(node))) {
|
|
1294
|
-
return transformSwitchFineGrained(path, state);
|
|
1295
|
-
}
|
|
1296
|
-
|
|
1297
|
-
if (isComponentElement(node)) {
|
|
1298
|
-
return transformComponentFineGrained(path, state);
|
|
1299
|
-
}
|
|
1300
|
-
|
|
1301
|
-
const attributes = openingElement.attributes;
|
|
1302
|
-
const children = node.children;
|
|
1303
|
-
|
|
1304
|
-
// Check if this entire subtree is purely static
|
|
1305
|
-
const allChildrenStatic = children.every(isStaticChild);
|
|
1306
|
-
const allAttrsStatic = attributes.every(attr => !isDynamicAttr(attr));
|
|
1307
|
-
const noEvents = attributes.every(attr => {
|
|
1308
|
-
if (t.isJSXSpreadAttribute(attr)) return false;
|
|
1309
|
-
const name = getAttrName(attr);
|
|
1310
|
-
return !name?.startsWith('on') && !name?.startsWith('bind:');
|
|
1311
|
-
});
|
|
1312
|
-
|
|
1313
|
-
if (allChildrenStatic && allAttrsStatic && noEvents) {
|
|
1314
|
-
// Fully static element — extract to template, return clone call
|
|
1315
|
-
const html = extractStaticHTML(node);
|
|
1316
|
-
if (html) {
|
|
1317
|
-
const tmplId = getOrCreateTemplate(state, html);
|
|
1318
|
-
state.needsTemplate = true;
|
|
1319
|
-
return t.callExpression(t.identifier(tmplId), []);
|
|
1320
|
-
}
|
|
1321
|
-
}
|
|
1322
|
-
|
|
1323
|
-
// Mixed static/dynamic element — extract template, add effects for dynamic parts
|
|
1324
|
-
const html = extractStaticHTML(node);
|
|
1325
|
-
if (!html) {
|
|
1326
|
-
// Template extraction failed — emit a detailed compile warning and use h() as fallback
|
|
1327
|
-
const loc = node.loc;
|
|
1328
|
-
const fileName = state.filename || state.file?.opts?.filename || '<unknown>';
|
|
1329
|
-
const lineInfo = loc ? `:${loc.start.line}:${loc.start.column}` : '';
|
|
1330
|
-
console.warn(
|
|
1331
|
-
`[what-compiler] Could not extract template for <${tagName}> at ${fileName}${lineInfo}. ` +
|
|
1332
|
-
`Falling back to h() for this element. ` +
|
|
1333
|
-
`This element could not be statically analyzed. Consider simplifying the JSX.`
|
|
1334
|
-
);
|
|
1335
|
-
state.needsH = true;
|
|
1336
|
-
return transformElementAsH(path, state);
|
|
1337
|
-
}
|
|
1338
|
-
|
|
1339
|
-
const tmplId = getOrCreateTemplate(state, html);
|
|
1340
|
-
state.needsTemplate = true;
|
|
1341
|
-
|
|
1342
|
-
const elId = state.nextVarId();
|
|
1343
|
-
|
|
1344
|
-
// Build statements: _el$ = _tmpl$1()
|
|
1345
|
-
// NO IIFE wrapping — statements are inlined into the containing function
|
|
1346
|
-
const statements = [
|
|
1347
|
-
t.variableDeclaration('const', [
|
|
1348
|
-
t.variableDeclarator(t.identifier(elId), t.callExpression(t.identifier(tmplId), []))
|
|
1349
|
-
])
|
|
1350
|
-
];
|
|
1351
|
-
|
|
1352
|
-
// Apply dynamic attributes and events
|
|
1353
|
-
applyDynamicAttrs(statements, elId, attributes, state, tagName);
|
|
1354
|
-
|
|
1355
|
-
// Handle dynamic children
|
|
1356
|
-
applyDynamicChildren(statements, elId, children, node, state);
|
|
1357
|
-
|
|
1358
|
-
// Instead of wrapping in an IIFE, store setup statements for hoisting.
|
|
1359
|
-
// The JSXElement visitor will insert them before the enclosing statement.
|
|
1360
|
-
if (!state._pendingSetup) state._pendingSetup = [];
|
|
1361
|
-
state._pendingSetup.push(...statements);
|
|
1362
|
-
return t.identifier(elId);
|
|
1363
|
-
}
|
|
1364
|
-
|
|
1365
|
-
// Fallback: transform element using h() when template extraction fails
|
|
1366
|
-
function transformElementAsH(path, state) {
|
|
1367
|
-
const { node } = path;
|
|
1368
|
-
const openingElement = node.openingElement;
|
|
1369
|
-
const tagName = openingElement.name.name;
|
|
1370
|
-
const attributes = openingElement.attributes;
|
|
1371
|
-
const children = node.children;
|
|
1372
|
-
|
|
1373
|
-
const props = [];
|
|
1374
|
-
for (const attr of attributes) {
|
|
1375
|
-
if (t.isJSXSpreadAttribute(attr)) continue;
|
|
1376
|
-
const attrName = getAttrName(attr);
|
|
1377
|
-
const value = getAttributeValue(attr.value);
|
|
1378
|
-
let domAttrName = normalizeAttrName(attrName);
|
|
1379
|
-
props.push(
|
|
1380
|
-
t.objectProperty(
|
|
1381
|
-
/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(domAttrName)
|
|
1382
|
-
? t.identifier(domAttrName)
|
|
1383
|
-
: t.stringLiteral(domAttrName),
|
|
1384
|
-
value
|
|
1385
|
-
)
|
|
1386
|
-
);
|
|
1387
|
-
}
|
|
1388
|
-
|
|
1389
|
-
const transformedChildren = [];
|
|
1390
|
-
for (const child of children) {
|
|
1391
|
-
if (t.isJSXText(child)) {
|
|
1392
|
-
const text = normalizeJsxText(child.value);
|
|
1393
|
-
if (text) transformedChildren.push(t.stringLiteral(text));
|
|
1394
|
-
} else if (t.isJSXExpressionContainer(child)) {
|
|
1395
|
-
if (!t.isJSXEmptyExpression(child.expression)) {
|
|
1396
|
-
transformedChildren.push(child.expression);
|
|
1397
|
-
}
|
|
1398
|
-
} else if (t.isJSXElement(child)) {
|
|
1399
|
-
transformedChildren.push(transformElementFineGrained({ node: child }, state));
|
|
1400
|
-
} else if (t.isJSXFragment(child)) {
|
|
1401
|
-
transformedChildren.push(transformFragmentFineGrained({ node: child }, state));
|
|
1402
|
-
}
|
|
1403
|
-
}
|
|
1404
|
-
|
|
1405
|
-
const propsExpr = props.length > 0 ? t.objectExpression(props) : t.nullLiteral();
|
|
1406
|
-
return t.callExpression(t.identifier('h'), [t.stringLiteral(tagName), propsExpr, ...transformedChildren]);
|
|
1407
|
-
}
|
|
1408
|
-
|
|
1409
|
-
// Tags where `value` / `checked` are live DOM properties the user expects a
|
|
1410
|
-
// dynamic binding to drive (input.value, select.value, input.checked, ...).
|
|
1411
|
-
// Other tags keep the generic setProp path (e.g. <div value={x}> sets an
|
|
1412
|
-
// attribute, <li value={n}> hits the `key in el` property branch).
|
|
1413
|
-
const VALUE_PROP_TAGS = new Set(['input', 'textarea', 'select', 'option']);
|
|
1414
|
-
|
|
1415
|
-
function applyDynamicAttrs(statements, elId, attributes, state, tagName) {
|
|
1416
|
-
// Specialized monomorphic setters for statically-known attribute names
|
|
1417
|
-
// (SPRINT v0.11 C2). The generic _$setProp re-dispatches on the key string
|
|
1418
|
-
// (ref/key/url/class/style/innerHTML/boolean/...) on EVERY reactive update;
|
|
1419
|
-
// when the compiler knows the name it emits the direct helper instead.
|
|
1420
|
-
// SECURITY: URL attributes (href/src/action/formaction) and innerHTML/
|
|
1421
|
-
// dangerouslySetInnerHTML intentionally fall through to _$setProp — URL
|
|
1422
|
-
// sanitization and the { __html } enforcement live there.
|
|
1423
|
-
function buildSetPropCall(propName, valueExpr) {
|
|
1424
|
-
if (propName === 'class') {
|
|
1425
|
-
// normalizeAttrName already mapped className → class
|
|
1426
|
-
state.needsSetClass = true;
|
|
1427
|
-
return t.callExpression(t.identifier('_$setClass'), [t.identifier(elId), valueExpr]);
|
|
1428
|
-
}
|
|
1429
|
-
if (propName === 'style') {
|
|
1430
|
-
state.needsSetStyle = true;
|
|
1431
|
-
return t.callExpression(t.identifier('_$setStyle'), [t.identifier(elId), valueExpr]);
|
|
1432
|
-
}
|
|
1433
|
-
if (propName === 'value' && tagName && VALUE_PROP_TAGS.has(tagName)) {
|
|
1434
|
-
state.needsSetValue = true;
|
|
1435
|
-
return t.callExpression(t.identifier('_$setValue'), [t.identifier(elId), valueExpr]);
|
|
1436
|
-
}
|
|
1437
|
-
if (propName === 'checked' && tagName === 'input') {
|
|
1438
|
-
// Live property write — matches bind:checked semantics. (The old
|
|
1439
|
-
// setAttribute('checked') path only set the DEFAULT-checked state,
|
|
1440
|
-
// which stops reflecting once the user has toggled the input.)
|
|
1441
|
-
// A helper (not a raw `.checked =`) so function values still get
|
|
1442
|
-
// reactive-accessor treatment, like every other setter.
|
|
1443
|
-
state.needsSetChecked = true;
|
|
1444
|
-
return t.callExpression(t.identifier('_$setChecked'), [t.identifier(elId), valueExpr]);
|
|
1445
|
-
}
|
|
1446
|
-
if (propName.startsWith('data-') || propName.startsWith('aria-')) {
|
|
1447
|
-
state.needsSetAttr = true;
|
|
1448
|
-
return t.callExpression(t.identifier('_$setAttr'), [
|
|
1449
|
-
t.identifier(elId),
|
|
1450
|
-
t.stringLiteral(propName),
|
|
1451
|
-
valueExpr
|
|
1452
|
-
]);
|
|
1453
|
-
}
|
|
1454
|
-
state.needsSetProp = true;
|
|
1455
|
-
return t.callExpression(t.identifier('_$setProp'), [
|
|
1456
|
-
t.identifier(elId),
|
|
1457
|
-
t.stringLiteral(propName),
|
|
1458
|
-
valueExpr
|
|
1459
|
-
]);
|
|
1460
|
-
}
|
|
1461
|
-
|
|
1462
|
-
// Lazy delegation init (C6): the first element of a module that assigns a
|
|
1463
|
-
// delegated `$$event` handler also calls the once-guarded _$delegate$()
|
|
1464
|
-
// helper at construction time. Emitted at most once per element.
|
|
1465
|
-
let delegateInitEmitted = false;
|
|
1466
|
-
function emitDelegateInit() {
|
|
1467
|
-
if (delegateInitEmitted) return;
|
|
1468
|
-
delegateInitEmitted = true;
|
|
1469
|
-
statements.push(
|
|
1470
|
-
t.expressionStatement(t.callExpression(t.identifier('_$delegate$'), []))
|
|
1471
|
-
);
|
|
1472
|
-
}
|
|
1473
|
-
|
|
1474
|
-
// Static attributes before the first spread are already in the template.
|
|
1475
|
-
// Ones after it are not, because the template is applied before _$spread
|
|
1476
|
-
// runs and would lose to it; they are set here instead, in source order, so
|
|
1477
|
-
// the last write for a key wins exactly as it does in the h() call.
|
|
1478
|
-
let seenSpread = false;
|
|
1479
|
-
|
|
1480
|
-
for (const [attrIndex, attr] of attributes.entries()) {
|
|
1481
|
-
if (t.isJSXSpreadAttribute(attr)) {
|
|
1482
|
-
seenSpread = true;
|
|
1483
|
-
state.needsSpread = true;
|
|
1484
|
-
statements.push(
|
|
1485
|
-
t.expressionStatement(
|
|
1486
|
-
t.callExpression(t.identifier('_$spread'), [t.identifier(elId), attr.argument])
|
|
1487
|
-
)
|
|
1488
|
-
);
|
|
1489
|
-
continue;
|
|
1490
|
-
}
|
|
1491
|
-
|
|
1492
|
-
// A later attribute of the same name is the only writer that matters.
|
|
1493
|
-
// Emitting this one too would apply it after the template and let it win.
|
|
1494
|
-
if (isShadowedAttr(attributes, attrIndex)) continue;
|
|
1495
|
-
|
|
1496
|
-
const attrName = getAttrName(attr);
|
|
1497
|
-
|
|
1498
|
-
// Strip key prop — WhatFW has no virtual DOM, so key is meaningless (issue #6)
|
|
1499
|
-
if (attrName === 'key') continue;
|
|
1500
|
-
|
|
1501
|
-
// Ref handling — assign element to ref object/callback
|
|
1502
|
-
if (attrName === 'ref') {
|
|
1503
|
-
const refExpr = getAttributeValue(attr.value);
|
|
1504
|
-
// Generate: typeof ref === 'function' ? ref(el) : ref.current = el
|
|
1505
|
-
statements.push(
|
|
1506
|
-
t.expressionStatement(
|
|
1507
|
-
t.conditionalExpression(
|
|
1508
|
-
t.binaryExpression('===',
|
|
1509
|
-
t.unaryExpression('typeof', refExpr),
|
|
1510
|
-
t.stringLiteral('function')
|
|
1511
|
-
),
|
|
1512
|
-
t.callExpression(t.cloneNode(refExpr), [t.identifier(elId)]),
|
|
1513
|
-
t.assignmentExpression('=',
|
|
1514
|
-
t.memberExpression(t.cloneNode(refExpr), t.identifier('current')),
|
|
1515
|
-
t.identifier(elId)
|
|
1516
|
-
)
|
|
1517
|
-
)
|
|
1518
|
-
)
|
|
1519
|
-
);
|
|
1520
|
-
continue;
|
|
1521
|
-
}
|
|
1522
|
-
|
|
1523
|
-
// Event handlers
|
|
1524
|
-
if (attrName.startsWith('on') && !attrName.includes('|') && !hasEventModifiers(attrName, state)) {
|
|
1525
|
-
const event = attrName.slice(2).toLowerCase();
|
|
1526
|
-
const handler = getAttributeValue(attr.value);
|
|
1527
|
-
|
|
1528
|
-
if (DELEGATED_EVENTS.has(event)) {
|
|
1529
|
-
// Use event delegation: el.$$click = handler (matches runtime lookup)
|
|
1530
|
-
state.needsDelegation = true;
|
|
1531
|
-
if (!state.delegatedEvents) state.delegatedEvents = new Set();
|
|
1532
|
-
state.delegatedEvents.add(event);
|
|
1533
|
-
emitDelegateInit();
|
|
1534
|
-
statements.push(
|
|
1535
|
-
t.expressionStatement(
|
|
1536
|
-
t.assignmentExpression('=',
|
|
1537
|
-
t.memberExpression(
|
|
1538
|
-
t.identifier(elId),
|
|
1539
|
-
t.identifier(`$$${event}`)
|
|
1540
|
-
),
|
|
1541
|
-
handler
|
|
1542
|
-
)
|
|
1543
|
-
)
|
|
1544
|
-
);
|
|
1545
|
-
} else {
|
|
1546
|
-
// Non-delegated: use per-element addEventListener
|
|
1547
|
-
statements.push(
|
|
1548
|
-
t.expressionStatement(
|
|
1549
|
-
t.callExpression(
|
|
1550
|
-
t.memberExpression(t.identifier(elId), t.identifier('addEventListener')),
|
|
1551
|
-
[t.stringLiteral(event), handler]
|
|
1552
|
-
)
|
|
1553
|
-
)
|
|
1554
|
-
);
|
|
1555
|
-
}
|
|
1556
|
-
continue;
|
|
1557
|
-
}
|
|
1558
|
-
|
|
1559
|
-
// Event with modifiers (pipe '|' or JSX-safe double underscore '__')
|
|
1560
|
-
if (attrName.startsWith('on') && (attrName.includes('|') || hasEventModifiers(attrName, state))) {
|
|
1561
|
-
const { eventName, modifiers } = parseEventModifiers(attrName);
|
|
1562
|
-
const handler = getAttributeValue(attr.value);
|
|
1563
|
-
const wrappedHandler = createEventHandler(handler, modifiers);
|
|
1564
|
-
const event = eventName.slice(2).toLowerCase();
|
|
1565
|
-
|
|
1566
|
-
const optionMods = modifiers.filter(m => EVENT_OPTION_MODIFIERS.has(m));
|
|
1567
|
-
const addEventArgs = [t.stringLiteral(event), wrappedHandler];
|
|
1568
|
-
if (optionMods.length > 0) {
|
|
1569
|
-
const optsProps = optionMods.map(m =>
|
|
1570
|
-
t.objectProperty(t.identifier(m), t.booleanLiteral(true))
|
|
1571
|
-
);
|
|
1572
|
-
addEventArgs.push(t.objectExpression(optsProps));
|
|
1573
|
-
}
|
|
1574
|
-
|
|
1575
|
-
statements.push(
|
|
1576
|
-
t.expressionStatement(
|
|
1577
|
-
t.callExpression(
|
|
1578
|
-
t.memberExpression(t.identifier(elId), t.identifier('addEventListener')),
|
|
1579
|
-
addEventArgs
|
|
1580
|
-
)
|
|
1581
|
-
)
|
|
1582
|
-
);
|
|
1583
|
-
continue;
|
|
1584
|
-
}
|
|
1585
|
-
|
|
1586
|
-
// Binding
|
|
1587
|
-
if (isBindingAttribute(attrName)) {
|
|
1588
|
-
const bindProp = getBindingProperty(attrName);
|
|
1589
|
-
const signalExpr = attr.value.expression;
|
|
1590
|
-
state.needsEffect = true;
|
|
1591
|
-
|
|
1592
|
-
if (bindProp === 'value') {
|
|
1593
|
-
statements.push(
|
|
1594
|
-
t.expressionStatement(
|
|
1595
|
-
t.callExpression(t.identifier('_$effect'), [
|
|
1596
|
-
t.arrowFunctionExpression([], t.assignmentExpression('=',
|
|
1597
|
-
t.memberExpression(t.identifier(elId), t.identifier('value')),
|
|
1598
|
-
t.callExpression(t.cloneNode(signalExpr), [])
|
|
1599
|
-
))
|
|
1600
|
-
])
|
|
1601
|
-
)
|
|
1602
|
-
);
|
|
1603
|
-
statements.push(
|
|
1604
|
-
t.expressionStatement(
|
|
1605
|
-
t.callExpression(
|
|
1606
|
-
t.memberExpression(t.identifier(elId), t.identifier('addEventListener')),
|
|
1607
|
-
[
|
|
1608
|
-
t.stringLiteral('input'),
|
|
1609
|
-
t.arrowFunctionExpression(
|
|
1610
|
-
[t.identifier('e')],
|
|
1611
|
-
t.callExpression(
|
|
1612
|
-
t.memberExpression(t.cloneNode(signalExpr), t.identifier('set')),
|
|
1613
|
-
[t.memberExpression(
|
|
1614
|
-
t.memberExpression(t.identifier('e'), t.identifier('target')),
|
|
1615
|
-
t.identifier('value')
|
|
1616
|
-
)]
|
|
1617
|
-
)
|
|
1618
|
-
)
|
|
1619
|
-
]
|
|
1620
|
-
)
|
|
1621
|
-
)
|
|
1622
|
-
);
|
|
1623
|
-
} else if (bindProp === 'checked') {
|
|
1624
|
-
state.needsEffect = true;
|
|
1625
|
-
statements.push(
|
|
1626
|
-
t.expressionStatement(
|
|
1627
|
-
t.callExpression(t.identifier('_$effect'), [
|
|
1628
|
-
t.arrowFunctionExpression([], t.assignmentExpression('=',
|
|
1629
|
-
t.memberExpression(t.identifier(elId), t.identifier('checked')),
|
|
1630
|
-
t.callExpression(t.cloneNode(signalExpr), [])
|
|
1631
|
-
))
|
|
1632
|
-
])
|
|
1633
|
-
)
|
|
1634
|
-
);
|
|
1635
|
-
statements.push(
|
|
1636
|
-
t.expressionStatement(
|
|
1637
|
-
t.callExpression(
|
|
1638
|
-
t.memberExpression(t.identifier(elId), t.identifier('addEventListener')),
|
|
1639
|
-
[
|
|
1640
|
-
t.stringLiteral('change'),
|
|
1641
|
-
t.arrowFunctionExpression(
|
|
1642
|
-
[t.identifier('e')],
|
|
1643
|
-
t.callExpression(
|
|
1644
|
-
t.memberExpression(t.cloneNode(signalExpr), t.identifier('set')),
|
|
1645
|
-
[t.memberExpression(
|
|
1646
|
-
t.memberExpression(t.identifier('e'), t.identifier('target')),
|
|
1647
|
-
t.identifier('checked')
|
|
1648
|
-
)]
|
|
1649
|
-
)
|
|
1650
|
-
)
|
|
1651
|
-
]
|
|
1652
|
-
)
|
|
1653
|
-
)
|
|
1654
|
-
);
|
|
1655
|
-
}
|
|
1656
|
-
continue;
|
|
1657
|
-
}
|
|
1658
|
-
|
|
1659
|
-
// Dynamic attribute (expression)
|
|
1660
|
-
if (t.isJSXExpressionContainer(attr.value)) {
|
|
1661
|
-
const expr = attr.value.expression;
|
|
1662
|
-
const domName = normalizeAttrName(attrName);
|
|
1663
|
-
|
|
1664
|
-
if (isPotentiallyReactive(expr, state.signalNames, state.importedIdentifiers)) {
|
|
1665
|
-
state.needsEffect = true;
|
|
1666
|
-
// Auto-invoke a bare identifier only when it is a PROVEN signal:
|
|
1667
|
-
// value={count} -> count() for a local `const count = signal(...)`.
|
|
1668
|
-
//
|
|
1669
|
-
// Never a destructured prop or an import. Either one can hold any
|
|
1670
|
-
// value: a prop is whatever the parent passed, and an import is
|
|
1671
|
-
// whatever the other module exported (`href={DOCS_URL}` with a string
|
|
1672
|
-
// constant is the common case). Calling one of those threw
|
|
1673
|
-
// "X is not a function". The runtime setters resolve a function value
|
|
1674
|
-
// as a reactive accessor themselves, exactly as h() does, so the
|
|
1675
|
-
// uncalled identifier is correct for a plain value AND keeps an
|
|
1676
|
-
// imported signal live.
|
|
1677
|
-
const fromProps = state.signalNames && state.signalNames.fromDestructuredProps;
|
|
1678
|
-
const valueExpr = t.isIdentifier(expr) &&
|
|
1679
|
-
!(fromProps && fromProps.has(expr.name)) &&
|
|
1680
|
-
isSignalIdentifier(expr.name, state.signalNames)
|
|
1681
|
-
? t.callExpression(expr, [])
|
|
1682
|
-
: expr;
|
|
1683
|
-
const effectCall = t.callExpression(t.identifier('_$effect'), [
|
|
1684
|
-
t.arrowFunctionExpression([], buildSetPropCall(domName, valueExpr))
|
|
1685
|
-
]);
|
|
1686
|
-
// In dev mode, add a leading comment when the effect wrapping is uncertain
|
|
1687
|
-
// (non-signal function call whose args happen to contain signal reads)
|
|
1688
|
-
if (isUncertainReactive(expr, state.signalNames, state.importedIdentifiers)) {
|
|
1689
|
-
t.addComment(effectCall, 'leading',
|
|
1690
|
-
' @what-dev: effect wrapping may be unnecessary — expression contains a non-signal function call with reactive args ',
|
|
1691
|
-
false
|
|
1692
|
-
);
|
|
1693
|
-
}
|
|
1694
|
-
statements.push(t.expressionStatement(effectCall));
|
|
1695
|
-
} else {
|
|
1696
|
-
// Static expression (no signal calls) — set once
|
|
1697
|
-
statements.push(t.expressionStatement(buildSetPropCall(domName, expr)));
|
|
1698
|
-
}
|
|
1699
|
-
continue;
|
|
1700
|
-
}
|
|
1701
|
-
|
|
1702
|
-
// A literal attribute that follows a spread. Everything before the first
|
|
1703
|
-
// spread is in the template; this one is not, so re-apply it here to
|
|
1704
|
-
// restore the order the author wrote. A valueless attribute is `true` in
|
|
1705
|
-
// JSX, which is what the h() spelling passes.
|
|
1706
|
-
if (seenSpread) {
|
|
1707
|
-
statements.push(
|
|
1708
|
-
t.expressionStatement(
|
|
1709
|
-
buildSetPropCall(normalizeAttrName(attrName), getAttributeValue(attr.value))
|
|
1710
|
-
)
|
|
1711
|
-
);
|
|
1712
|
-
}
|
|
1713
|
-
}
|
|
1714
|
-
}
|
|
1715
|
-
|
|
1716
|
-
// =====================================================
|
|
1717
|
-
// Branch Memoization (SPRINT v0.11 C1)
|
|
1718
|
-
// =====================================================
|
|
1719
|
-
// `_$insert(el, () => cond() ? <A/> : <B/>)` re-creates the taken branch's
|
|
1720
|
-
// DOM tree (and re-registers every effect inside it) on EVERY re-evaluation
|
|
1721
|
-
// of the insert effect — including writes to signals read by the condition
|
|
1722
|
-
// that do NOT flip which branch is taken (e.g. `count() > 5` while count
|
|
1723
|
-
// goes 6 → 7). Solid solves this by memoizing the condition: route the
|
|
1724
|
-
// condition through an eager, equality-gated memo so the insert effect
|
|
1725
|
-
// depends on the *memo* instead of the raw signals:
|
|
1726
|
-
//
|
|
1727
|
-
// const _c$0 = _$memo(() => !!(count() > 5));
|
|
1728
|
-
// _$insert(_el$, () => _c$0() ? <A/> : <B/>, marker);
|
|
1729
|
-
//
|
|
1730
|
-
// The memo re-evaluates on every count write, but only NOTIFIES when its
|
|
1731
|
-
// value changes — so branch DOM is recreated exactly on real flips.
|
|
1732
|
-
//
|
|
1733
|
-
// Semantics preserved:
|
|
1734
|
-
// - Ternary tests only matter for truthiness → memoize `!!test`.
|
|
1735
|
-
// - `a && b` / `a || b` render the LEFT operand's VALUE when it
|
|
1736
|
-
// short-circuits (`{0 && <div/>}` renders "0"), so the left side is
|
|
1737
|
-
// memoized by value (Object.is) — never coerced.
|
|
1738
|
-
// - Branch-internal reactivity (signals read inside <A/>) is fine-grained
|
|
1739
|
-
// and unaffected; plain-value branches read in the insert arrow are
|
|
1740
|
-
// still tracked by the insert effect directly.
|
|
1741
|
-
|
|
1742
|
-
// Does this expression produce DOM when evaluated? (raw JSX still present at
|
|
1743
|
-
// this stage, or an already-lowered _$mapArray list). Only then is branch
|
|
1744
|
-
// memoization worth the extra memo node.
|
|
1745
|
-
function buildsDOM(node) {
|
|
1746
|
-
if (!node || typeof node !== 'object') return false;
|
|
1747
|
-
if (Array.isArray(node)) return node.some(buildsDOM);
|
|
1748
|
-
if (node.type === 'JSXElement' || node.type === 'JSXFragment') return true;
|
|
1749
|
-
if (node.type === 'CallExpression' && node.callee &&
|
|
1750
|
-
node.callee.type === 'Identifier' &&
|
|
1751
|
-
(node.callee.name === '_$mapArray' || node.callee.name === 'mapArray')) {
|
|
1752
|
-
return true;
|
|
1753
|
-
}
|
|
1754
|
-
for (const key of Object.keys(node)) {
|
|
1755
|
-
if (key === 'loc' || key === 'start' || key === 'end' || key === 'leadingComments' ||
|
|
1756
|
-
key === 'trailingComments' || key === 'innerComments') continue;
|
|
1757
|
-
const v = node[key];
|
|
1758
|
-
if (v && typeof v === 'object' && buildsDOM(v)) return true;
|
|
1759
|
-
}
|
|
1760
|
-
return false;
|
|
1761
|
-
}
|
|
1762
|
-
|
|
1763
|
-
// Does `path` sit in a slot its parent only evaluates SOMETIMES?
|
|
1764
|
-
//
|
|
1765
|
-
// Used to decide whether a JSX root's setup statements may be hoisted out to
|
|
1766
|
-
// the enclosing statement. Anything in one of these slots must not be: the
|
|
1767
|
-
// source deliberately said "only build this when the guard opens", and the
|
|
1768
|
-
// hoist turns that into "always build this".
|
|
1769
|
-
//
|
|
1770
|
-
// Only the slots that are genuinely skipped count. A logical expression's
|
|
1771
|
-
// LEFT operand and a ternary's TEST always run, so JSX there is not guarded
|
|
1772
|
-
// and keeps the cheaper hoist.
|
|
1773
|
-
function isConditionallyEvaluated(path) {
|
|
1774
|
-
const parent = path.parent;
|
|
1775
|
-
if (!parent) return false;
|
|
1776
|
-
if (t.isLogicalExpression(parent)) return path.key === 'right';
|
|
1777
|
-
if (t.isConditionalExpression(parent)) {
|
|
1778
|
-
return path.key === 'consequent' || path.key === 'alternate';
|
|
1779
|
-
}
|
|
1780
|
-
// `maybe?.render(<jsx/>)` skips its whole argument list when the chain
|
|
1781
|
-
// short-circuits, so an argument is guarded; the callee/object is not.
|
|
1782
|
-
if (t.isOptionalCallExpression(parent) || t.isOptionalMemberExpression(parent)) {
|
|
1783
|
-
return path.key !== 'callee' && path.key !== 'object';
|
|
1784
|
-
}
|
|
1785
|
-
return false;
|
|
1786
|
-
}
|
|
1787
|
-
|
|
1788
|
-
// If `expr` is a conditional (ternary / && / ||) with a reactive test and a
|
|
1789
|
-
// DOM-producing branch, hoist the test into `const _c$N = _$memo(...)` (pushed
|
|
1790
|
-
// onto `statements`) and return the expression rewritten to read the memo.
|
|
1791
|
-
// Otherwise returns `expr` unchanged.
|
|
1792
|
-
function memoizeBranchCondition(expr, statements, state) {
|
|
1793
|
-
let testExpr = null;
|
|
1794
|
-
let isTernary = false;
|
|
1795
|
-
if (t.isConditionalExpression(expr)) {
|
|
1796
|
-
testExpr = expr.test;
|
|
1797
|
-
isTernary = true;
|
|
1798
|
-
} else if (t.isLogicalExpression(expr) && (expr.operator === '&&' || expr.operator === '||')) {
|
|
1799
|
-
testExpr = expr.left;
|
|
1800
|
-
} else {
|
|
1801
|
-
return expr;
|
|
1802
|
-
}
|
|
1803
|
-
|
|
1804
|
-
if (!isPotentiallyReactive(testExpr, state.signalNames, state.importedIdentifiers)) return expr;
|
|
1805
|
-
|
|
1806
|
-
const branches = isTernary ? [expr.consequent, expr.alternate] : [expr.right];
|
|
1807
|
-
if (!branches.some(buildsDOM)) return expr;
|
|
1808
|
-
|
|
1809
|
-
const condId = state.nextMemoId();
|
|
1810
|
-
state.needsMemo = true;
|
|
1811
|
-
// Ternary: only truthiness matters in test position → gate on !!test so
|
|
1812
|
-
// value changes that don't flip truthiness (5 → 6) never notify.
|
|
1813
|
-
// Logical: the left VALUE is rendered on short-circuit → gate on the value.
|
|
1814
|
-
const memoBody = isTernary
|
|
1815
|
-
? t.unaryExpression('!', t.unaryExpression('!', testExpr))
|
|
1816
|
-
: testExpr;
|
|
1817
|
-
statements.push(
|
|
1818
|
-
t.variableDeclaration('const', [
|
|
1819
|
-
t.variableDeclarator(
|
|
1820
|
-
t.identifier(condId),
|
|
1821
|
-
t.callExpression(t.identifier('_$memo'), [
|
|
1822
|
-
t.arrowFunctionExpression([], memoBody)
|
|
1823
|
-
])
|
|
1824
|
-
)
|
|
1825
|
-
])
|
|
1826
|
-
);
|
|
1827
|
-
|
|
1828
|
-
const condRead = t.callExpression(t.identifier(condId), []);
|
|
1829
|
-
return isTernary
|
|
1830
|
-
? t.conditionalExpression(condRead, expr.consequent, expr.alternate)
|
|
1831
|
-
: t.logicalExpression(expr.operator, condRead, expr.right);
|
|
1832
|
-
}
|
|
1833
|
-
|
|
1834
|
-
function applyDynamicChildren(statements, elId, children, parentNode, state) {
|
|
1835
|
-
// Two-pass approach: first collect all children needing DOM references,
|
|
1836
|
-
// then pre-capture markers before any _$insert() calls shift indices.
|
|
1837
|
-
// This fixes issue #1: childNodes index shifting with multiple dynamic children.
|
|
1838
|
-
|
|
1839
|
-
// --- Pass 1: Scan children and collect entries ---
|
|
1840
|
-
const entries = [];
|
|
1841
|
-
let childIndex = 0;
|
|
1842
|
-
|
|
1843
|
-
for (const child of children) {
|
|
1844
|
-
if (t.isJSXText(child)) {
|
|
1845
|
-
const text = normalizeJsxText(child.value);
|
|
1846
|
-
if (text) childIndex++;
|
|
1847
|
-
continue;
|
|
1848
|
-
}
|
|
1849
|
-
|
|
1850
|
-
if (t.isJSXExpressionContainer(child)) {
|
|
1851
|
-
if (t.isJSXEmptyExpression(child.expression)) continue;
|
|
1852
|
-
entries.push({ type: 'expression', child, childIndex });
|
|
1853
|
-
childIndex++;
|
|
1854
|
-
continue;
|
|
1855
|
-
}
|
|
1856
|
-
|
|
1857
|
-
if (t.isJSXElement(child)) {
|
|
1858
|
-
const childTag = child.openingElement.name.name;
|
|
1859
|
-
if (isComponentElement(child) || childTag === 'For' || childTag === 'Show') {
|
|
1860
|
-
entries.push({ type: 'component', child, childIndex });
|
|
1861
|
-
childIndex++;
|
|
1862
|
-
} else {
|
|
1863
|
-
const hasAnythingDynamic = child.openingElement.attributes.some(isDynamicAttr) ||
|
|
1864
|
-
child.openingElement.attributes.some(a => !t.isJSXSpreadAttribute(a) && getAttrName(a)?.startsWith('on')) ||
|
|
1865
|
-
!child.children.every(isStaticChild);
|
|
1866
|
-
|
|
1867
|
-
entries.push({ type: 'static', child, childIndex, hasAnythingDynamic });
|
|
1868
|
-
childIndex++;
|
|
1869
|
-
}
|
|
1870
|
-
continue;
|
|
1871
|
-
}
|
|
1872
|
-
|
|
1873
|
-
if (t.isJSXFragment(child)) {
|
|
1874
|
-
// Flattened: every slot the fragment contributes gets its own marker and
|
|
1875
|
-
// its own entry, so it is handled exactly like a child written directly
|
|
1876
|
-
// under this element. That is what keeps document order stable across
|
|
1877
|
-
// re-runs, and it also means fragment children now get the treatments
|
|
1878
|
-
// the old single-anchor branch reimplemented without: keyed .map()
|
|
1879
|
-
// lowering, branch memoization and per-element dynamic attributes.
|
|
1880
|
-
for (const slot of fragmentSlots(child)) {
|
|
1881
|
-
if (slot.kind === 'text') {
|
|
1882
|
-
entries.push({ type: 'fragmentText', text: slot.text, childIndex });
|
|
1883
|
-
} else if (slot.kind === 'expression') {
|
|
1884
|
-
entries.push({ type: 'expression', child: slot.child, childIndex });
|
|
1885
|
-
} else {
|
|
1886
|
-
// The template holds only a marker here, so the element is built at
|
|
1887
|
-
// runtime and inserted before it, which is the 'component' slot shape.
|
|
1888
|
-
entries.push({ type: 'component', child: slot.child, childIndex });
|
|
1889
|
-
}
|
|
1890
|
-
childIndex++;
|
|
1891
|
-
}
|
|
1892
|
-
}
|
|
1893
|
-
}
|
|
1894
|
-
|
|
1895
|
-
// --- Pre-capture marker references if needed ---
|
|
1896
|
-
// When there are multiple entries needing DOM refs and at least one _$insert(),
|
|
1897
|
-
// capture all markers upfront to avoid index shifting after DOM mutations.
|
|
1898
|
-
const entriesNeedingRef = entries.filter(e =>
|
|
1899
|
-
e.type === 'expression' || e.type === 'component' || e.type === 'fragmentText' ||
|
|
1900
|
-
(e.type === 'static' && e.hasAnythingDynamic)
|
|
1901
|
-
);
|
|
1902
|
-
// Pre-capture whenever 2+ children need a DOM ref. Beyond preventing index
|
|
1903
|
-
// shift after insert() mutations, the shared O(n) cursor walk below replaces
|
|
1904
|
-
// per-child `el.firstChild.nextSibling…`-from-root access, which was O(n²) in
|
|
1905
|
-
// both compile time and emitted size for elements with many dynamic
|
|
1906
|
-
// children. (AUDIT-2026-06-06 H2)
|
|
1907
|
-
const needsPreCapture = entriesNeedingRef.length >= 2;
|
|
1908
|
-
|
|
1909
|
-
const markerVars = new Map(); // childIndex → variable name
|
|
1910
|
-
if (needsPreCapture) {
|
|
1911
|
-
// Chain each marker from the PREVIOUS captured cursor instead of
|
|
1912
|
-
// re-walking `el.firstChild.nextSibling…` from the root for every child.
|
|
1913
|
-
// entriesNeedingRef is in ascending childIndex order, so the per-marker
|
|
1914
|
-
// deltas sum to O(n) total instead of O(n²). This was the dominant
|
|
1915
|
-
// quadratic in compile time and emitted-bundle size for large elements.
|
|
1916
|
-
// (AUDIT-2026-06-06 H2)
|
|
1917
|
-
let prevVar = null;
|
|
1918
|
-
let prevIndex = 0;
|
|
1919
|
-
for (const entry of entriesNeedingRef) {
|
|
1920
|
-
const idx = /** @type {number} */ (entry.childIndex);
|
|
1921
|
-
const markerVar = state.nextVarId();
|
|
1922
|
-
markerVars.set(idx, markerVar);
|
|
1923
|
-
let init;
|
|
1924
|
-
if (prevVar === null) {
|
|
1925
|
-
init = buildChildAccess(elId, idx);
|
|
1926
|
-
} else {
|
|
1927
|
-
init = t.identifier(prevVar);
|
|
1928
|
-
for (let i = prevIndex; i < idx; i++) {
|
|
1929
|
-
init = t.memberExpression(init, t.identifier('nextSibling'));
|
|
1930
|
-
}
|
|
1931
|
-
}
|
|
1932
|
-
statements.push(
|
|
1933
|
-
t.variableDeclaration('const', [
|
|
1934
|
-
t.variableDeclarator(t.identifier(markerVar), init)
|
|
1935
|
-
])
|
|
1936
|
-
);
|
|
1937
|
-
prevVar = markerVar;
|
|
1938
|
-
prevIndex = idx;
|
|
1939
|
-
}
|
|
1940
|
-
}
|
|
1941
|
-
|
|
1942
|
-
// Helper: get a marker reference (pre-captured var or inline access)
|
|
1943
|
-
function getMarker(idx) {
|
|
1944
|
-
if (markerVars.has(idx)) {
|
|
1945
|
-
return t.identifier(markerVars.get(idx));
|
|
1946
|
-
}
|
|
1947
|
-
return buildChildAccess(elId, idx);
|
|
1948
|
-
}
|
|
1949
|
-
|
|
1950
|
-
// --- Pass 2: Generate code using stable references ---
|
|
1951
|
-
for (const entry of entries) {
|
|
1952
|
-
if (entry.type === 'expression') {
|
|
1953
|
-
let expr = entry.child.expression;
|
|
1954
|
-
const marker = getMarker(entry.childIndex);
|
|
1955
|
-
state.needsInsert = true;
|
|
1956
|
-
|
|
1957
|
-
// Auto-lower .map() to mapArray when the callback returns keyed JSX.
|
|
1958
|
-
// Pattern: source().map(item => <Comp key={...} />) or source().map((item, i) => ...)
|
|
1959
|
-
let mapResult = tryLowerMapToMapArray(expr, state);
|
|
1960
|
-
if (mapResult) {
|
|
1961
|
-
state.needsMapArray = true;
|
|
1962
|
-
// A bare _$mapArray(...) call is a self-managing inserter (it tracks
|
|
1963
|
-
// its source internally) and an arrow is already reactive — pass both
|
|
1964
|
-
// raw. But when lowering produced a ternary/logical wrapping the call
|
|
1965
|
-
// (e.g. cond ? _$mapArray(...) : fallback), the surrounding condition
|
|
1966
|
-
// must stay reactive, so wrap the whole expression in () => and let
|
|
1967
|
-
// _$insert re-evaluate it on change. Without this the condition is read
|
|
1968
|
-
// exactly once and never re-tracks. (AUDIT-2026-06-06 H1)
|
|
1969
|
-
const isBareMapArray = t.isCallExpression(mapResult) && t.isIdentifier(mapResult.callee) &&
|
|
1970
|
-
(mapResult.callee.name === '_$mapArray' || mapResult.callee.name === 'mapArray');
|
|
1971
|
-
const isArrowAlready = t.isArrowFunctionExpression(mapResult);
|
|
1972
|
-
// Branch memoization (C1): when the lowered result is a conditional
|
|
1973
|
-
// around the list (cond ? _$mapArray(...) : fallback), memoize the
|
|
1974
|
-
// condition so non-flip writes don't tear down and recreate the
|
|
1975
|
-
// entire list inserter.
|
|
1976
|
-
if (isArrowAlready && t.isExpression(mapResult.body)) {
|
|
1977
|
-
mapResult.body = memoizeBranchCondition(mapResult.body, statements, state);
|
|
1978
|
-
} else if (!isBareMapArray && !isArrowAlready) {
|
|
1979
|
-
mapResult = memoizeBranchCondition(mapResult, statements, state);
|
|
1980
|
-
}
|
|
1981
|
-
const insertArg = (isBareMapArray || isArrowAlready)
|
|
1982
|
-
? mapResult
|
|
1983
|
-
: t.arrowFunctionExpression([], mapResult);
|
|
1984
|
-
statements.push(
|
|
1985
|
-
t.expressionStatement(
|
|
1986
|
-
t.callExpression(t.identifier('_$insert'), [
|
|
1987
|
-
t.identifier(elId),
|
|
1988
|
-
insertArg,
|
|
1989
|
-
marker
|
|
1990
|
-
])
|
|
1991
|
-
)
|
|
1992
|
-
);
|
|
1993
|
-
continue;
|
|
1994
|
-
}
|
|
1995
|
-
|
|
1996
|
-
// mapArray() calls return self-managing inserters — pass directly, never wrap in () =>
|
|
1997
|
-
const isMapArrayCall = t.isCallExpression(expr) && t.isIdentifier(expr.callee) &&
|
|
1998
|
-
(expr.callee.name === 'mapArray' || expr.callee.name === '_$mapArray');
|
|
1999
|
-
if (isMapArrayCall) {
|
|
2000
|
-
state.needsMapArray = true;
|
|
2001
|
-
if (expr.callee.name === 'mapArray') expr.callee.name = '_$mapArray';
|
|
2002
|
-
statements.push(
|
|
2003
|
-
t.expressionStatement(
|
|
2004
|
-
t.callExpression(t.identifier('_$insert'), [
|
|
2005
|
-
t.identifier(elId),
|
|
2006
|
-
expr,
|
|
2007
|
-
marker
|
|
2008
|
-
])
|
|
2009
|
-
)
|
|
2010
|
-
);
|
|
2011
|
-
continue;
|
|
2012
|
-
}
|
|
2013
|
-
|
|
2014
|
-
if (isPotentiallyReactive(expr, state.signalNames, state.importedIdentifiers)) {
|
|
2015
|
-
// Branch memoization (C1): conditional children only rebuild branch
|
|
2016
|
-
// DOM when the condition actually flips.
|
|
2017
|
-
expr = memoizeBranchCondition(expr, statements, state);
|
|
2018
|
-
const insertCall = t.callExpression(t.identifier('_$insert'), [
|
|
2019
|
-
t.identifier(elId),
|
|
2020
|
-
t.arrowFunctionExpression([], expr),
|
|
2021
|
-
marker
|
|
2022
|
-
]);
|
|
2023
|
-
if (isUncertainReactive(expr, state.signalNames, state.importedIdentifiers)) {
|
|
2024
|
-
t.addComment(insertCall, 'leading',
|
|
2025
|
-
' @what-dev: reactive wrapping may be unnecessary — expression contains a non-signal function call with reactive args ',
|
|
2026
|
-
false
|
|
2027
|
-
);
|
|
2028
|
-
}
|
|
2029
|
-
statements.push(t.expressionStatement(insertCall));
|
|
2030
|
-
} else {
|
|
2031
|
-
statements.push(
|
|
2032
|
-
t.expressionStatement(
|
|
2033
|
-
t.callExpression(t.identifier('_$insert'), [
|
|
2034
|
-
t.identifier(elId),
|
|
2035
|
-
expr,
|
|
2036
|
-
marker
|
|
2037
|
-
])
|
|
2038
|
-
)
|
|
2039
|
-
);
|
|
2040
|
-
}
|
|
2041
|
-
continue;
|
|
2042
|
-
}
|
|
2043
|
-
|
|
2044
|
-
if (entry.type === 'component') {
|
|
2045
|
-
const transformed = transformElementFineGrained({ node: entry.child }, state);
|
|
2046
|
-
const marker = getMarker(entry.childIndex);
|
|
2047
|
-
state.needsInsert = true;
|
|
2048
|
-
statements.push(
|
|
2049
|
-
t.expressionStatement(
|
|
2050
|
-
t.callExpression(t.identifier('_$insert'), [
|
|
2051
|
-
t.identifier(elId),
|
|
2052
|
-
transformed,
|
|
2053
|
-
marker
|
|
2054
|
-
])
|
|
2055
|
-
)
|
|
2056
|
-
);
|
|
2057
|
-
continue;
|
|
2058
|
-
}
|
|
2059
|
-
|
|
2060
|
-
if (entry.type === 'static' && entry.hasAnythingDynamic) {
|
|
2061
|
-
// Static child with dynamic content — get element reference
|
|
2062
|
-
let childElRef;
|
|
2063
|
-
if (markerVars.has(entry.childIndex)) {
|
|
2064
|
-
childElRef = markerVars.get(entry.childIndex);
|
|
2065
|
-
} else {
|
|
2066
|
-
childElRef = state.nextVarId();
|
|
2067
|
-
statements.push(
|
|
2068
|
-
t.variableDeclaration('const', [
|
|
2069
|
-
t.variableDeclarator(
|
|
2070
|
-
t.identifier(childElRef),
|
|
2071
|
-
buildChildAccess(elId, entry.childIndex)
|
|
2072
|
-
)
|
|
2073
|
-
])
|
|
2074
|
-
);
|
|
2075
|
-
}
|
|
2076
|
-
applyDynamicAttrs(statements, childElRef, entry.child.openingElement.attributes, state, entry.child.openingElement.name.name);
|
|
2077
|
-
applyDynamicChildren(statements, childElRef, entry.child.children, entry.child, state);
|
|
2078
|
-
continue;
|
|
2079
|
-
}
|
|
2080
|
-
|
|
2081
|
-
if (entry.type === 'fragmentText') {
|
|
2082
|
-
state.needsInsert = true;
|
|
2083
|
-
statements.push(
|
|
2084
|
-
t.expressionStatement(
|
|
2085
|
-
t.callExpression(t.identifier('_$insert'), [
|
|
2086
|
-
t.identifier(elId),
|
|
2087
|
-
t.stringLiteral(entry.text),
|
|
2088
|
-
getMarker(entry.childIndex),
|
|
2089
|
-
])
|
|
2090
|
-
)
|
|
2091
|
-
);
|
|
2092
|
-
continue;
|
|
2093
|
-
}
|
|
2094
|
-
}
|
|
2095
|
-
}
|
|
2096
|
-
|
|
2097
|
-
function buildChildAccess(elId, index) {
|
|
2098
|
-
// Use firstChild/nextSibling chains instead of childNodes[N]
|
|
2099
|
-
// This is more robust with whitespace text nodes
|
|
2100
|
-
if (index === 0) {
|
|
2101
|
-
return t.memberExpression(t.identifier(elId), t.identifier('firstChild'));
|
|
2102
|
-
}
|
|
2103
|
-
// Chain .nextSibling for subsequent indices
|
|
2104
|
-
let expr = t.memberExpression(t.identifier(elId), t.identifier('firstChild'));
|
|
2105
|
-
for (let i = 0; i < index; i++) {
|
|
2106
|
-
expr = t.memberExpression(expr, t.identifier('nextSibling'));
|
|
2107
|
-
}
|
|
2108
|
-
return expr;
|
|
2109
|
-
}
|
|
2110
|
-
|
|
2111
|
-
function transformComponentFineGrained(path, state) {
|
|
2112
|
-
const { node } = path;
|
|
2113
|
-
const openingElement = node.openingElement;
|
|
2114
|
-
const componentRef = componentCallee(openingElement.name);
|
|
2115
|
-
const attributes = openingElement.attributes;
|
|
2116
|
-
const children = node.children;
|
|
2117
|
-
|
|
2118
|
-
// Check for client: directive (islands)
|
|
2119
|
-
/** @type {{ type: string, value?: any } | null} */
|
|
2120
|
-
let clientDirective = null;
|
|
2121
|
-
const filteredAttrs = [];
|
|
2122
|
-
|
|
2123
|
-
for (const attr of attributes) {
|
|
2124
|
-
if (t.isJSXAttribute(attr)) {
|
|
2125
|
-
// Handle both simple names and namespaced names (client:idle)
|
|
2126
|
-
let name;
|
|
2127
|
-
if (t.isJSXNamespacedName(attr.name)) {
|
|
2128
|
-
name = `${attr.name.namespace.name}:${attr.name.name.name}`;
|
|
2129
|
-
} else {
|
|
2130
|
-
name = attr.name.name;
|
|
2131
|
-
}
|
|
2132
|
-
if (name && typeof name === 'string' && name.startsWith('client:')) {
|
|
2133
|
-
const mode = name.slice(7);
|
|
2134
|
-
if (attr.value) {
|
|
2135
|
-
clientDirective = { type: mode, value: attr.value.value };
|
|
2136
|
-
} else {
|
|
2137
|
-
clientDirective = { type: mode };
|
|
2138
|
-
}
|
|
2139
|
-
continue;
|
|
2140
|
-
}
|
|
2141
|
-
}
|
|
2142
|
-
filteredAttrs.push(attr);
|
|
2143
|
-
}
|
|
2144
|
-
|
|
2145
|
-
// Transform children.
|
|
2146
|
-
// Element children build their DOM at the call site, i.e. before the parent
|
|
2147
|
-
// component ever runs, so a <Provider> publishes its context value too late
|
|
2148
|
-
// for its own subtree. Collect the element setup and emit it behind a
|
|
2149
|
-
// zero-arg factory instead; the runtime calls the factory while the parent
|
|
2150
|
-
// is on the component stack. An expression child is deferred for the same
|
|
2151
|
-
// reason: it is the shape a wrapper forwards its own children through, and
|
|
2152
|
-
// reading it while the argument list is built happens before the component
|
|
2153
|
-
// it is being handed to has run. Text children have nothing to defer.
|
|
2154
|
-
//
|
|
2155
|
-
// Shared by the island branch and the regular component branch: an island is
|
|
2156
|
-
// still a component, and `<Panel client:visible>...</Panel>` must keep its
|
|
2157
|
-
// children rather than silently dropping them.
|
|
2158
|
-
function transformComponentChildren() {
|
|
2159
|
-
const setupMark = state._pendingSetup ? state._pendingSetup.length : 0;
|
|
2160
|
-
const transformedChildren = [];
|
|
2161
|
-
let deferChildren = false;
|
|
2162
|
-
for (const child of children) {
|
|
2163
|
-
if (t.isJSXText(child)) {
|
|
2164
|
-
const text = normalizeJsxText(child.value);
|
|
2165
|
-
if (text) transformedChildren.push(t.stringLiteral(text));
|
|
2166
|
-
} else if (t.isJSXExpressionContainer(child)) {
|
|
2167
|
-
if (!t.isJSXEmptyExpression(child.expression)) {
|
|
2168
|
-
deferChildren = true;
|
|
2169
|
-
// The same lowering an element child and a fragment child get.
|
|
2170
|
-
// Without it `<Box>{count()}</Box>` was evaluated once and never
|
|
2171
|
-
// again, while `<div>{count()}</div>` right beside it stayed live —
|
|
2172
|
-
// the auto-thunk docs/GOTCHAS.md section 2 promises for "any call
|
|
2173
|
-
// with no arguments" reached every JSX position EXCEPT this one.
|
|
2174
|
-
//
|
|
2175
|
-
// Nothing about it is component-specific: a component's children
|
|
2176
|
-
// are built into an array with no host element to _$insert into,
|
|
2177
|
-
// which is exactly the situation lowerFragmentExprChild exists for,
|
|
2178
|
-
// and it is where `.map()` picks up keyed reconciliation too.
|
|
2179
|
-
transformedChildren.push(lowerFragmentExprChild(child.expression, state));
|
|
2180
|
-
}
|
|
2181
|
-
} else if (t.isJSXElement(child)) {
|
|
2182
|
-
// <For>/<Show>/<Switch> lower to an inserter or a thunk (already lazy).
|
|
2183
|
-
const childTag = child.openingElement.name.name;
|
|
2184
|
-
if (childTag !== 'For' && childTag !== 'Show' && childTag !== 'Switch') deferChildren = true;
|
|
2185
|
-
transformedChildren.push(transformElementFineGrained({ node: child }, state));
|
|
2186
|
-
} else if (t.isJSXFragment(child)) {
|
|
2187
|
-
deferChildren = true;
|
|
2188
|
-
transformedChildren.push(transformFragmentFineGrained({ node: child }, state));
|
|
2189
|
-
}
|
|
2190
|
-
}
|
|
2191
|
-
|
|
2192
|
-
let childrenArg = t.arrayExpression(transformedChildren);
|
|
2193
|
-
if (deferChildren) {
|
|
2194
|
-
// Hoisted element setup emitted while transforming these children belongs
|
|
2195
|
-
// inside the factory, not before the enclosing statement.
|
|
2196
|
-
const setup = state._pendingSetup ? state._pendingSetup.splice(setupMark) : [];
|
|
2197
|
-
childrenArg = t.arrowFunctionExpression(
|
|
2198
|
-
[],
|
|
2199
|
-
setup.length > 0
|
|
2200
|
-
? t.blockStatement([...setup, t.returnStatement(childrenArg)])
|
|
2201
|
-
: childrenArg
|
|
2202
|
-
);
|
|
2203
|
-
}
|
|
2204
|
-
return childrenArg;
|
|
2205
|
-
}
|
|
2206
|
-
|
|
2207
|
-
if (clientDirective) {
|
|
2208
|
-
state.needsCreateComponent = true;
|
|
2209
|
-
state.needsIsland = true;
|
|
2210
|
-
|
|
2211
|
-
// The directive's own machinery, kept apart from user data because it is
|
|
2212
|
-
// always applied LAST: `component` comes from the tag and `mode` from the
|
|
2213
|
-
// directive, so nothing a caller spreads in can reach either one.
|
|
2214
|
-
const directiveProps = [
|
|
2215
|
-
t.objectProperty(t.identifier('component'), componentRef),
|
|
2216
|
-
t.objectProperty(t.identifier('mode'), t.stringLiteral(clientDirective.type)),
|
|
2217
|
-
];
|
|
2218
|
-
|
|
2219
|
-
if (clientDirective.value) {
|
|
2220
|
-
directiveProps.push(
|
|
2221
|
-
t.objectProperty(t.identifier('mediaQuery'), t.stringLiteral(clientDirective.value))
|
|
2222
|
-
);
|
|
2223
|
-
}
|
|
2224
|
-
|
|
2225
|
-
// User props in source order — same rule, and the same reasons, as the
|
|
2226
|
-
// regular component path below. An island IS a component, so
|
|
2227
|
-
// `<Chart client:load {...a} {...b} />` has to mean `{ ...a, ...b }` for
|
|
2228
|
-
// exactly the reason `<Chart {...a} {...b} />` does.
|
|
2229
|
-
const islandParts = [];
|
|
2230
|
-
let islandUserProps = [];
|
|
2231
|
-
const flushIslandUserProps = () => {
|
|
2232
|
-
if (islandUserProps.length > 0) {
|
|
2233
|
-
islandParts.push(t.objectExpression(islandUserProps));
|
|
2234
|
-
islandUserProps = [];
|
|
2235
|
-
}
|
|
2236
|
-
};
|
|
2237
|
-
|
|
2238
|
-
for (const attr of filteredAttrs) {
|
|
2239
|
-
if (t.isJSXSpreadAttribute(attr)) {
|
|
2240
|
-
// A spread used to be dropped on the floor here, so
|
|
2241
|
-
// `<Chart client:visible {...config} />` lost every prop in `config`.
|
|
2242
|
-
// Then only the LAST spread was kept, which lost every key an earlier
|
|
2243
|
-
// spread carried and the last one did not.
|
|
2244
|
-
flushIslandUserProps();
|
|
2245
|
-
islandParts.push(attr.argument);
|
|
2246
|
-
continue;
|
|
2247
|
-
}
|
|
2248
|
-
const attrName = getAttrName(attr);
|
|
2249
|
-
if (attrName === 'key') continue;
|
|
2250
|
-
const value = getAttributeValue(attr.value);
|
|
2251
|
-
// `data-x` and `aria-label` are not identifiers. Emitting one as a bare
|
|
2252
|
-
// key produced `{data-x: "1"}`, which is a SYNTAX ERROR: babel does not
|
|
2253
|
-
// validate what its builders are handed, so the compiler exited 0 and
|
|
2254
|
-
// wrote a file that no parser would accept. `<Chart client:load
|
|
2255
|
-
// aria-label="..." />` is an ordinary thing to write, and it took the
|
|
2256
|
-
// whole build down with an error pointing at generated output.
|
|
2257
|
-
//
|
|
2258
|
-
// The regular component branch below has always tested the name first;
|
|
2259
|
-
// this branch is the copy that did not.
|
|
2260
|
-
islandUserProps.push(t.objectProperty(propKey(attrName), value));
|
|
2261
|
-
}
|
|
2262
|
-
|
|
2263
|
-
let islandPropsExpr;
|
|
2264
|
-
if (islandParts.length === 0) {
|
|
2265
|
-
// No spread anywhere: one object literal, directive keys written last so
|
|
2266
|
-
// they still win. This is the shape nearly every island has, and keeping
|
|
2267
|
-
// it a literal keeps the emitted output byte-identical to before.
|
|
2268
|
-
islandPropsExpr = t.objectExpression([...islandUserProps, ...directiveProps]);
|
|
2269
|
-
} else {
|
|
2270
|
-
flushIslandUserProps();
|
|
2271
|
-
islandPropsExpr = t.callExpression(
|
|
2272
|
-
t.memberExpression(t.identifier('Object'), t.identifier('assign')),
|
|
2273
|
-
[t.objectExpression([]), ...islandParts, t.objectExpression(directiveProps)]
|
|
2274
|
-
);
|
|
2275
|
-
}
|
|
2276
|
-
|
|
2277
|
-
return t.callExpression(
|
|
2278
|
-
t.identifier('_$createComponent'),
|
|
2279
|
-
[t.identifier('Island'), islandPropsExpr, transformComponentChildren()]
|
|
2280
|
-
);
|
|
2281
|
-
}
|
|
2282
|
-
|
|
2283
|
-
// Regular component — use _$createComponent to instantiate, component runs once.
|
|
2284
|
-
// Unless this element IS the tree handed to hydrate(), in which case it has
|
|
2285
|
-
// to arrive unbuilt: see isHydrateRootArgument.
|
|
2286
|
-
//
|
|
2287
|
-
// The root, and only the root. A host element lowers to a template clone, so
|
|
2288
|
-
// "unbuilt" is not something the children of an arbitrary tree can inherit —
|
|
2289
|
-
// <App><p>hi</p></App> would still build the <p>, and pushing the choice down
|
|
2290
|
-
// through component children only would produce a tree that hydrates in
|
|
2291
|
-
// patches. The root is the one position where the answer is unambiguous and
|
|
2292
|
-
// it is where the documented entry point lives.
|
|
2293
|
-
const isHydrateRoot = isHydrateRootArgument(path);
|
|
2294
|
-
if (isHydrateRoot) state.needsComponentVNode = true;
|
|
2295
|
-
else state.needsCreateComponent = true;
|
|
2296
|
-
|
|
2297
|
-
// Props resolve in SOURCE order. `<Box a {...s} b />` is one spelling of
|
|
2298
|
-
// `{ a, ...s, b }`, which is what h(), the JSX runtime, every other JSX
|
|
2299
|
-
// toolchain, and (since #65) this compiler's own ELEMENT path all produce.
|
|
2300
|
-
// `parts` is that argument list: runs of explicit attributes, separated by
|
|
2301
|
-
// the spreads written between them.
|
|
2302
|
-
//
|
|
2303
|
-
// Keeping a single `spreadExpr` and appending every explicit prop last, the
|
|
2304
|
-
// way this used to, got both halves wrong. `<Box {...a} {...b} />` kept only
|
|
2305
|
-
// `b`, so every key `a` carried and `b` did not vanished completely — data
|
|
2306
|
-
// loss, not merely precedence — and an attribute written BEFORE a spread
|
|
2307
|
-
// beat it, which no other JSX implementation does.
|
|
2308
|
-
//
|
|
2309
|
-
// The merge is a shallow copy, deliberately: a prop is reactive here when
|
|
2310
|
-
// its VALUE is an accessor, and Object.assign copies that function through
|
|
2311
|
-
// untouched. A lone non-literal spread is copied too, the same
|
|
2312
|
-
// Object.assign path a multi-prop merge already used, so two
|
|
2313
|
-
// `<Box {...reused}>` sites do not share one identity. createComponent
|
|
2314
|
-
// (dom.js) copies again before the component sees the props.
|
|
2315
|
-
const parts = [];
|
|
2316
|
-
let props = [];
|
|
2317
|
-
const flushProps = () => {
|
|
2318
|
-
if (props.length > 0) {
|
|
2319
|
-
parts.push(t.objectExpression(props));
|
|
2320
|
-
props = [];
|
|
2321
|
-
}
|
|
2322
|
-
};
|
|
2323
|
-
|
|
2324
|
-
for (const attr of filteredAttrs) {
|
|
2325
|
-
if (t.isJSXSpreadAttribute(attr)) {
|
|
2326
|
-
flushProps();
|
|
2327
|
-
parts.push(attr.argument);
|
|
2328
|
-
continue;
|
|
2329
|
-
}
|
|
2330
|
-
|
|
2331
|
-
const attrName = getAttrName(attr);
|
|
2332
|
-
|
|
2333
|
-
// Strip key prop — WhatFW has no virtual DOM, so key is meaningless (issue #6)
|
|
2334
|
-
if (attrName === 'key') continue;
|
|
2335
|
-
|
|
2336
|
-
// Handle bind: attributes for components
|
|
2337
|
-
if (isBindingAttribute(attrName)) {
|
|
2338
|
-
const bindProp = getBindingProperty(attrName);
|
|
2339
|
-
const signalExpr = attr.value.expression;
|
|
2340
|
-
|
|
2341
|
-
if (bindProp === 'value') {
|
|
2342
|
-
props.push(
|
|
2343
|
-
t.objectProperty(t.identifier('value'), t.callExpression(t.cloneNode(signalExpr), []))
|
|
2344
|
-
);
|
|
2345
|
-
props.push(
|
|
2346
|
-
t.objectProperty(
|
|
2347
|
-
t.identifier('onInput'),
|
|
2348
|
-
t.arrowFunctionExpression(
|
|
2349
|
-
[t.identifier('e')],
|
|
2350
|
-
t.callExpression(
|
|
2351
|
-
t.memberExpression(t.cloneNode(signalExpr), t.identifier('set')),
|
|
2352
|
-
[t.memberExpression(
|
|
2353
|
-
t.memberExpression(t.identifier('e'), t.identifier('target')),
|
|
2354
|
-
t.identifier('value')
|
|
2355
|
-
)]
|
|
2356
|
-
)
|
|
2357
|
-
)
|
|
2358
|
-
)
|
|
2359
|
-
);
|
|
2360
|
-
} else if (bindProp === 'checked') {
|
|
2361
|
-
props.push(
|
|
2362
|
-
t.objectProperty(t.identifier('checked'), t.callExpression(t.cloneNode(signalExpr), []))
|
|
2363
|
-
);
|
|
2364
|
-
props.push(
|
|
2365
|
-
t.objectProperty(
|
|
2366
|
-
t.identifier('onChange'),
|
|
2367
|
-
t.arrowFunctionExpression(
|
|
2368
|
-
[t.identifier('e')],
|
|
2369
|
-
t.callExpression(
|
|
2370
|
-
t.memberExpression(t.cloneNode(signalExpr), t.identifier('set')),
|
|
2371
|
-
[t.memberExpression(
|
|
2372
|
-
t.memberExpression(t.identifier('e'), t.identifier('target')),
|
|
2373
|
-
t.identifier('checked')
|
|
2374
|
-
)]
|
|
2375
|
-
)
|
|
2376
|
-
)
|
|
2377
|
-
)
|
|
2378
|
-
);
|
|
2379
|
-
}
|
|
2380
|
-
continue;
|
|
2381
|
-
}
|
|
2382
|
-
|
|
2383
|
-
// Handle event modifiers on components
|
|
2384
|
-
if (attrName.startsWith('on') && (attrName.includes('|') || hasEventModifiers(attrName, state))) {
|
|
2385
|
-
const { eventName, modifiers } = parseEventModifiers(attrName);
|
|
2386
|
-
const handler = getAttributeValue(attr.value);
|
|
2387
|
-
const wrappedHandler = createEventHandler(handler, modifiers);
|
|
2388
|
-
props.push(t.objectProperty(t.identifier(eventName), wrappedHandler));
|
|
2389
|
-
continue;
|
|
2390
|
-
}
|
|
2391
|
-
|
|
2392
|
-
const value = getAttributeValue(attr.value);
|
|
2393
|
-
|
|
2394
|
-
props.push(t.objectProperty(propKey(attrName), value));
|
|
2395
|
-
}
|
|
2396
|
-
|
|
2397
|
-
flushProps();
|
|
2398
|
-
|
|
2399
|
-
let propsExpr;
|
|
2400
|
-
if (parts.length === 0) {
|
|
2401
|
-
propsExpr = t.nullLiteral();
|
|
2402
|
-
} else if (parts.length === 1 && t.isObjectExpression(parts[0])) {
|
|
2403
|
-
// A lone object literal (no spread, or an inline `{...}`) is already a
|
|
2404
|
-
// fresh props object. A lone identifier/member/call spread is the
|
|
2405
|
-
// CALLER'S object and must go through the copy below.
|
|
2406
|
-
propsExpr = parts[0];
|
|
2407
|
-
} else {
|
|
2408
|
-
propsExpr = t.callExpression(
|
|
2409
|
-
t.memberExpression(t.identifier('Object'), t.identifier('assign')),
|
|
2410
|
-
[t.objectExpression([]), ...parts]
|
|
2411
|
-
);
|
|
2412
|
-
}
|
|
2413
|
-
|
|
2414
|
-
const childrenArg = transformComponentChildren();
|
|
2415
|
-
|
|
2416
|
-
return t.callExpression(
|
|
2417
|
-
t.identifier(isHydrateRoot ? '_$componentVNode' : '_$createComponent'),
|
|
2418
|
-
[componentRef, propsExpr, childrenArg]
|
|
2419
|
-
);
|
|
2420
|
-
}
|
|
2421
|
-
|
|
2422
|
-
function transformForFineGrained(path, state) {
|
|
2423
|
-
const { node } = path;
|
|
2424
|
-
const attributes = node.openingElement.attributes;
|
|
2425
|
-
const children = node.children;
|
|
2426
|
-
|
|
2427
|
-
// <For each={data} key={item => item.id}>{(item) => <Row />}</For>
|
|
2428
|
-
// → mapArray(data, (item) => ..., { key: item => item.id })
|
|
2429
|
-
//
|
|
2430
|
-
// NOTE: <For> is supported but .map() with a key prop is the preferred
|
|
2431
|
-
// pattern for list rendering. The compiler auto-lowers .map() to
|
|
2432
|
-
// _$mapArray with raw mode, which is simpler and matches JS idioms.
|
|
2433
|
-
// <For> is useful when you need signal-wrapped item accessors (keyed
|
|
2434
|
-
// mode without raw), so that item updates don't recreate DOM nodes.
|
|
2435
|
-
if (process.env.NODE_ENV !== 'production') {
|
|
2436
|
-
const fileName = state.filename || state.file?.opts?.filename || '<unknown>';
|
|
2437
|
-
if (!_forInfoWarned.has(fileName)) {
|
|
2438
|
-
_forInfoWarned.add(fileName);
|
|
2439
|
-
const loc = node.loc;
|
|
2440
|
-
const lineInfo = loc ? `:${loc.start.line}:${loc.start.column}` : '';
|
|
2441
|
-
console.info(
|
|
2442
|
-
`[what-compiler] <For> at ${fileName}${lineInfo}: consider using .map() with a key prop instead. ` +
|
|
2443
|
-
`The compiler auto-lowers .map() to efficient keyed reconciliation. ` +
|
|
2444
|
-
`<For> is only needed for signal-wrapped item accessors (advanced).`
|
|
2445
|
-
);
|
|
2446
|
-
}
|
|
2447
|
-
}
|
|
2448
|
-
|
|
2449
|
-
let eachExpr = null;
|
|
2450
|
-
let keyExpr = null;
|
|
2451
|
-
let fallbackExpr = null;
|
|
2452
|
-
for (const attr of attributes) {
|
|
2453
|
-
if (t.isJSXAttribute(attr)) {
|
|
2454
|
-
const name = getAttrName(attr);
|
|
2455
|
-
if (name === 'each') eachExpr = getAttributeValue(attr.value);
|
|
2456
|
-
else if (name === 'key') keyExpr = getAttributeValue(attr.value);
|
|
2457
|
-
else if (name === 'fallback') fallbackExpr = getAttributeValue(attr.value);
|
|
2458
|
-
}
|
|
2459
|
-
}
|
|
2460
|
-
|
|
2461
|
-
if (!eachExpr) {
|
|
2462
|
-
console.warn('[what-compiler] <For> element missing "each" attribute.');
|
|
2463
|
-
state.needsH = true;
|
|
2464
|
-
return transformElementAsH(path, state);
|
|
2465
|
-
}
|
|
2466
|
-
|
|
2467
|
-
let renderFn = null;
|
|
2468
|
-
for (const child of children) {
|
|
2469
|
-
if (t.isJSXExpressionContainer(child) && !t.isJSXEmptyExpression(child.expression)) {
|
|
2470
|
-
renderFn = child.expression;
|
|
2471
|
-
break;
|
|
2472
|
-
}
|
|
2473
|
-
}
|
|
2474
|
-
|
|
2475
|
-
if (!renderFn) {
|
|
2476
|
-
console.warn('[what-compiler] <For> element missing render function child.');
|
|
2477
|
-
state.needsH = true;
|
|
2478
|
-
return transformElementAsH(path, state);
|
|
2479
|
-
}
|
|
2480
|
-
|
|
2481
|
-
state.needsMapArray = true;
|
|
2482
|
-
|
|
2483
|
-
// `_$mapArray(source, renderFn[, { key }])` — built from whichever source
|
|
2484
|
-
// expression the caller wants, because the fallback lowering below has to
|
|
2485
|
-
// read the source twice and therefore binds it to a const first.
|
|
2486
|
-
const buildMapArrayCall = (sourceExpr) => {
|
|
2487
|
-
const args = [sourceExpr, renderFn];
|
|
2488
|
-
if (keyExpr) {
|
|
2489
|
-
args.push(t.objectExpression([
|
|
2490
|
-
t.objectProperty(t.identifier('key'), keyExpr)
|
|
2491
|
-
]));
|
|
2492
|
-
}
|
|
2493
|
-
return t.callExpression(t.identifier('_$mapArray'), args);
|
|
2494
|
-
};
|
|
2495
|
-
|
|
2496
|
-
if (!fallbackExpr) {
|
|
2497
|
-
return buildMapArrayCall(eachExpr);
|
|
2498
|
-
}
|
|
2499
|
-
|
|
2500
|
-
// `fallback` used to be read by nobody: the loop above only looked at
|
|
2501
|
-
// `each` and `key`, so the attribute was silently discarded. The RUNTIME
|
|
2502
|
-
// For (packages/core/src/components.js) does implement it, so an app that
|
|
2503
|
-
// moved from a buildless setup to the Vite compiler lost its empty state
|
|
2504
|
-
// with nothing on the console.
|
|
2505
|
-
//
|
|
2506
|
-
// mapArray has no fallback of its own, and the obvious lowering — gate the
|
|
2507
|
-
// WHOLE thing on emptiness, `() => empty() ? _$mapArray(...) : fallback` —
|
|
2508
|
-
// is a trap. `insert()` has a fast path for a mapArray inserter: it
|
|
2509
|
-
// recognises `child._mapArray` and installs the list ONCE for the life of
|
|
2510
|
-
// the component. A thunk is not that, so the gated form falls through to
|
|
2511
|
-
// the generic reactive branch, whose effect calls the thunk again on every
|
|
2512
|
-
// flip and gets a BRAND NEW inserter each time. Nothing disposes the old
|
|
2513
|
-
// one, so it stays subscribed to the source forever: every empty -> fill
|
|
2514
|
-
// cycle permanently adds one more live list. Measured row-render-fn calls
|
|
2515
|
-
// per two writes, over successive cycles, went 2 -> 9 -> 16 -> 23 while
|
|
2516
|
-
// logging "NotFoundError: The child can not be found in the parent" from
|
|
2517
|
-
// the orphans reconciling against the detached fragment they captured. The
|
|
2518
|
-
// DOM stayed correct, which is why it looked fine.
|
|
2519
|
-
//
|
|
2520
|
-
// So keep the list permanent and give the fallback its OWN inserter beside
|
|
2521
|
-
// it, both anchored to the same marker:
|
|
2522
|
-
// _$insert(el, _$mapArray(each, fn), marker) // permanent
|
|
2523
|
-
// _$insert(el, () => empty() ? null : fallback, marker)
|
|
2524
|
-
// Only one of the two ever has content, and each reconciles independently.
|
|
2525
|
-
//
|
|
2526
|
-
// This function has to return a single expression, and a <For> can land in
|
|
2527
|
-
// a component's return, an element child, a component prop or a fragment.
|
|
2528
|
-
// Rather than teach all of those to emit two inserts, wrap the pair in one
|
|
2529
|
-
// inserter that performs both when it is mounted, and copy the list's own
|
|
2530
|
-
// marker properties onto it with Object.assign so it IS a mapArray inserter
|
|
2531
|
-
// to every consumer: `insert`, `createDOM`, `hydrateNode` and the server's
|
|
2532
|
-
// `_mapArrayToArray` all key off `_mapArray` and the `_mapArraySource` /
|
|
2533
|
-
// `_mapArrayFn` / `_mapArrayKeyed` trio. Object.assign copies exactly the
|
|
2534
|
-
// own enumerable properties mapArray sets, so this keeps working if the
|
|
2535
|
-
// runtime adds another one.
|
|
2536
|
-
//
|
|
2537
|
-
// Two more things this has to get right:
|
|
2538
|
-
// - The source expression is evaluated ONCE and shared, so the list and
|
|
2539
|
-
// the emptiness test can never disagree about which list they see.
|
|
2540
|
-
// - The emptiness test is MEMOIZED, so a write that leaves the list
|
|
2541
|
-
// non-empty does not re-run the fallback thunk and rebuild its DOM.
|
|
2542
|
-
if (!state._pendingSetup) state._pendingSetup = [];
|
|
2543
|
-
const forIndex = state.nextForIndex();
|
|
2544
|
-
const eachId = `_each$${forIndex}`;
|
|
2545
|
-
const listId = `_for$${forIndex}`;
|
|
2546
|
-
const fallbackId = `_fb$${forIndex}`;
|
|
2547
|
-
const emptyId = state.nextMemoId();
|
|
2548
|
-
state.needsMemo = true;
|
|
2549
|
-
state.needsInsert = true;
|
|
2550
|
-
|
|
2551
|
-
// `each` has to be a signal, or some other accessor. The typeof guard below
|
|
2552
|
-
// is NOT plain-array support and must not be read as advertising any: it
|
|
2553
|
-
// only keeps this memo total. `_$mapArray` calls its source, so
|
|
2554
|
-
// `each={["a","b"]}` throws "source is not a function" the moment the list
|
|
2555
|
-
// mounts — identically to the no-fallback lowering above, which hands the
|
|
2556
|
-
// same value straight to `_$mapArray`. The guard is here so that failure
|
|
2557
|
-
// arrives from the list, with that message, instead of from the emptiness
|
|
2558
|
-
// test first with a less obvious one.
|
|
2559
|
-
const resolvedId = path.scope
|
|
2560
|
-
? path.scope.generateUidIdentifier('list')
|
|
2561
|
-
: t.identifier('_list');
|
|
2562
|
-
const resolveList = t.conditionalExpression(
|
|
2563
|
-
t.binaryExpression('===',
|
|
2564
|
-
t.unaryExpression('typeof', t.identifier(eachId)),
|
|
2565
|
-
t.stringLiteral('function')
|
|
2566
|
-
),
|
|
2567
|
-
t.callExpression(t.identifier(eachId), []),
|
|
2568
|
-
t.identifier(eachId)
|
|
2569
|
-
);
|
|
2570
|
-
|
|
2571
|
-
state._pendingSetup.push(
|
|
2572
|
-
t.variableDeclaration('const', [
|
|
2573
|
-
t.variableDeclarator(t.identifier(eachId), eachExpr)
|
|
2574
|
-
]),
|
|
2575
|
-
t.variableDeclaration('const', [
|
|
2576
|
-
t.variableDeclarator(
|
|
2577
|
-
t.identifier(emptyId),
|
|
2578
|
-
t.callExpression(t.identifier('_$memo'), [
|
|
2579
|
-
t.arrowFunctionExpression([], t.blockStatement([
|
|
2580
|
-
t.variableDeclaration('const', [
|
|
2581
|
-
t.variableDeclarator(resolvedId, resolveList)
|
|
2582
|
-
]),
|
|
2583
|
-
t.returnStatement(
|
|
2584
|
-
t.unaryExpression('!', t.unaryExpression('!',
|
|
2585
|
-
t.logicalExpression('&&',
|
|
2586
|
-
t.cloneNode(resolvedId),
|
|
2587
|
-
t.memberExpression(t.cloneNode(resolvedId), t.identifier('length'))
|
|
2588
|
-
)
|
|
2589
|
-
))
|
|
2590
|
-
)
|
|
2591
|
-
]))
|
|
2592
|
-
])
|
|
2593
|
-
)
|
|
2594
|
-
]),
|
|
2595
|
-
t.variableDeclaration('const', [
|
|
2596
|
-
t.variableDeclarator(t.identifier(listId), buildMapArrayCall(t.identifier(eachId)))
|
|
2597
|
-
]),
|
|
2598
|
-
// The fallback thunk is hoisted rather than written inline in the
|
|
2599
|
-
// inserter below so that the inserter's body mentions no user code at
|
|
2600
|
-
// all. Its parameters can then be given fixed names without any risk of
|
|
2601
|
-
// capturing an identifier the fallback expression wanted from an outer
|
|
2602
|
-
// scope — this function is also called with a synthetic `{ node }` path
|
|
2603
|
-
// that carries no scope to generate a unique name from.
|
|
2604
|
-
t.variableDeclaration('const', [
|
|
2605
|
-
t.variableDeclarator(
|
|
2606
|
-
t.identifier(fallbackId),
|
|
2607
|
-
t.arrowFunctionExpression([], t.conditionalExpression(
|
|
2608
|
-
t.callExpression(t.identifier(emptyId), []),
|
|
2609
|
-
t.nullLiteral(),
|
|
2610
|
-
fallbackExpr
|
|
2611
|
-
))
|
|
2612
|
-
)
|
|
2613
|
-
])
|
|
2614
|
-
);
|
|
2615
|
-
|
|
2616
|
-
const parentParam = t.identifier('_parent');
|
|
2617
|
-
const markerParam = t.identifier('_marker');
|
|
2618
|
-
const endId = t.identifier('_end');
|
|
2619
|
-
return t.callExpression(
|
|
2620
|
-
t.memberExpression(t.identifier('Object'), t.identifier('assign')),
|
|
2621
|
-
[
|
|
2622
|
-
t.arrowFunctionExpression(
|
|
2623
|
-
[parentParam, markerParam],
|
|
2624
|
-
t.blockStatement([
|
|
2625
|
-
// The list goes in first so its `<!--/list-->` end marker sits
|
|
2626
|
-
// BEFORE the fallback: rows render above the empty state, and the
|
|
2627
|
-
// return value stays the end marker every other mapArray inserter
|
|
2628
|
-
// hands back.
|
|
2629
|
-
t.variableDeclaration('const', [
|
|
2630
|
-
t.variableDeclarator(endId, t.callExpression(t.identifier(listId), [
|
|
2631
|
-
t.cloneNode(parentParam),
|
|
2632
|
-
t.cloneNode(markerParam)
|
|
2633
|
-
]))
|
|
2634
|
-
]),
|
|
2635
|
-
// The thunk is wrapped in an ARRAY on purpose. `insert()` has two
|
|
2636
|
-
// ways to mount a function and only one of them survives here:
|
|
2637
|
-
// - passed bare, it takes insert's own reactive branch, whose
|
|
2638
|
-
// effect closes over the `parent` it was handed. When this
|
|
2639
|
-
// inserter is mounted through createDOM (a <For> as a component's
|
|
2640
|
-
// return value, at a fragment root, or inside a <Show> arm)
|
|
2641
|
-
// that parent is a throwaway DocumentFragment which is emptied
|
|
2642
|
-
// into the real container straight after. Every later run then
|
|
2643
|
-
// reconciles against a detached node, so the fallback was never
|
|
2644
|
-
// removed once rows arrived and stayed on screen underneath them.
|
|
2645
|
-
// - wrapped in an array, it goes through valuesToNodes -> createDOM,
|
|
2646
|
-
// whose reactive branch re-reads `endMarker.parentNode` on every
|
|
2647
|
-
// run. That is the same live-parent resolution mapArray does for
|
|
2648
|
-
// exactly this reason, so both halves survive being moved.
|
|
2649
|
-
t.expressionStatement(t.callExpression(t.identifier('_$insert'), [
|
|
2650
|
-
t.cloneNode(parentParam),
|
|
2651
|
-
t.arrayExpression([t.identifier(fallbackId)]),
|
|
2652
|
-
t.cloneNode(markerParam)
|
|
2653
|
-
])),
|
|
2654
|
-
t.returnStatement(t.cloneNode(endId))
|
|
2655
|
-
])
|
|
2656
|
-
),
|
|
2657
|
-
t.identifier(listId)
|
|
2658
|
-
]
|
|
2659
|
-
);
|
|
2660
|
-
}
|
|
2661
|
-
|
|
2662
|
-
function transformShowFineGrained(path, state) {
|
|
2663
|
-
// <Show when={cond} fallback={alt}>{content}</Show>
|
|
2664
|
-
// → () => cond() ? content : (fallback || null)
|
|
2665
|
-
// This compiles to a reactive expression that insert() wraps in an effect.
|
|
2666
|
-
const { node } = path;
|
|
2667
|
-
const attributes = node.openingElement.attributes;
|
|
2668
|
-
const children = node.children;
|
|
2669
|
-
|
|
2670
|
-
let whenExpr = null;
|
|
2671
|
-
let fallbackExpr = null;
|
|
2672
|
-
for (const attr of attributes) {
|
|
2673
|
-
if (t.isJSXAttribute(attr)) {
|
|
2674
|
-
const name = getAttrName(attr);
|
|
2675
|
-
if (name === 'when') whenExpr = getAttributeValue(attr.value);
|
|
2676
|
-
else if (name === 'fallback') fallbackExpr = getAttributeValue(attr.value);
|
|
2677
|
-
}
|
|
2678
|
-
}
|
|
2679
|
-
|
|
2680
|
-
if (!whenExpr) {
|
|
2681
|
-
// <Show> without a when prop has no defined semantics — fail loudly at
|
|
2682
|
-
// build time so the user fixes their source instead of seeing runtime
|
|
2683
|
-
// confusion. compileError pins the message to the JSX location from
|
|
2684
|
-
// either a real NodePath or the synthetic `{ node }` a parent transform
|
|
2685
|
-
// passes; calling path.buildCodeFrameError directly crashed on the
|
|
2686
|
-
// second, which is the shape almost every real <Show> arrives as.
|
|
2687
|
-
throw compileError(
|
|
2688
|
-
path,
|
|
2689
|
-
state,
|
|
2690
|
-
'<Show> requires a "when" prop. Example: <Show when={isOpen} fallback={null}>...</Show>'
|
|
2691
|
-
);
|
|
2692
|
-
}
|
|
2693
|
-
|
|
2694
|
-
// Extract the content — either a render function child or static JSX children
|
|
2695
|
-
let contentExpr = null;
|
|
2696
|
-
for (const child of children) {
|
|
2697
|
-
if (t.isJSXExpressionContainer(child) && !t.isJSXEmptyExpression(child.expression)) {
|
|
2698
|
-
// Render function: {() => <div>...</div>} or {(value) => <div>{value}</div>}
|
|
2699
|
-
contentExpr = child.expression;
|
|
2700
|
-
break;
|
|
2701
|
-
}
|
|
2702
|
-
}
|
|
2703
|
-
|
|
2704
|
-
if (!contentExpr) {
|
|
2705
|
-
// Static children — collect and transform them.
|
|
2706
|
-
//
|
|
2707
|
-
// The arm's element setup belongs INSIDE the arm, exactly as it does for
|
|
2708
|
-
// a <Match> arm (see the identical splice in transformSwitchFineGrained).
|
|
2709
|
-
// transformElementFineGrained pushes `const _el$N = _tmpl$X()` and every
|
|
2710
|
-
// binding it needs into state._pendingSetup, and _pendingSetup is drained
|
|
2711
|
-
// next to the thunk this function returns. So without the splice the arm
|
|
2712
|
-
// was built, and its bindings ran, alongside the enclosing component:
|
|
2713
|
-
// <Show when={user}><p>{() => user().name}</p></Show>
|
|
2714
|
-
// threw at first render with a null user, and logged an uncaught effect
|
|
2715
|
-
// error on every transition back to falsy because the binding stayed
|
|
2716
|
-
// subscribed. Uncompiled, the same JSX is lazy — children of the runtime
|
|
2717
|
-
// Show really are deferred — so this was a compiled-vs-runtime
|
|
2718
|
-
// divergence, not just a bug.
|
|
2719
|
-
if (!state._pendingSetup) state._pendingSetup = [];
|
|
2720
|
-
const setupMark = state._pendingSetup.length;
|
|
2721
|
-
const transformedChildren = [];
|
|
2722
|
-
for (const child of children) {
|
|
2723
|
-
if (t.isJSXText(child)) {
|
|
2724
|
-
const text = normalizeJsxText(child.value);
|
|
2725
|
-
if (text) transformedChildren.push(t.stringLiteral(text));
|
|
2726
|
-
} else if (t.isJSXElement(child)) {
|
|
2727
|
-
transformedChildren.push(transformElementFineGrained({ node: child }, state));
|
|
2728
|
-
}
|
|
2729
|
-
}
|
|
2730
|
-
if (transformedChildren.length === 1) {
|
|
2731
|
-
contentExpr = transformedChildren[0];
|
|
2732
|
-
} else if (transformedChildren.length > 1) {
|
|
2733
|
-
contentExpr = t.arrayExpression(transformedChildren);
|
|
2734
|
-
} else {
|
|
2735
|
-
contentExpr = t.nullLiteral();
|
|
2736
|
-
}
|
|
2737
|
-
const setup = state._pendingSetup.splice(setupMark);
|
|
2738
|
-
if (setup.length > 0) {
|
|
2739
|
-
contentExpr = t.callExpression(
|
|
2740
|
-
t.arrowFunctionExpression([], t.blockStatement([...setup, t.returnStatement(contentExpr)])),
|
|
2741
|
-
[]
|
|
2742
|
-
);
|
|
2743
|
-
}
|
|
2744
|
-
}
|
|
2745
|
-
|
|
2746
|
-
// Build:
|
|
2747
|
-
// () => { const _v = <condition>; return _v ? <consequent> : <alternate>; }
|
|
2748
|
-
// Hoisting into a local prevents double-evaluation of the `when` signal
|
|
2749
|
-
// (the consequent's render callback also needs the resolved value).
|
|
2750
|
-
let condition = buildWhenCondition(whenExpr, state);
|
|
2751
|
-
|
|
2752
|
-
const vId = path.scope
|
|
2753
|
-
? path.scope.generateUidIdentifier('v')
|
|
2754
|
-
: t.identifier('_v');
|
|
2755
|
-
|
|
2756
|
-
const contentIsFn = t.isFunction(contentExpr);
|
|
2757
|
-
const consequent = contentIsFn
|
|
2758
|
-
? t.callExpression(contentExpr, [t.cloneNode(vId)])
|
|
2759
|
-
: contentExpr;
|
|
2760
|
-
const alternate = fallbackExpr || t.nullLiteral();
|
|
2761
|
-
|
|
2762
|
-
// Branch memoization (SPRINT v0.11 C1): route a reactive `when` through an
|
|
2763
|
-
// equality-gated memo so the insert effect only re-fires (recreating the
|
|
2764
|
-
// taken branch's DOM) when the condition actually changes — not on every
|
|
2765
|
-
// write to a signal the condition happens to read.
|
|
2766
|
-
// - Render-function children receive the resolved value (`{v => ...}`),
|
|
2767
|
-
// so the memo is VALUE-gated (Object.is): identity changes re-render,
|
|
2768
|
-
// matching pre-memo semantics.
|
|
2769
|
-
// - Static children only use the value for truthiness → gate on !!cond
|
|
2770
|
-
// so e.g. `when={items().length}` doesn't re-render on 2 → 3.
|
|
2771
|
-
if (isPotentiallyReactive(condition, state.signalNames, state.importedIdentifiers)) {
|
|
2772
|
-
const condId = state.nextMemoId();
|
|
2773
|
-
state.needsMemo = true;
|
|
2774
|
-
const memoBody = contentIsFn
|
|
2775
|
-
? condition
|
|
2776
|
-
: t.unaryExpression('!', t.unaryExpression('!', condition));
|
|
2777
|
-
if (!state._pendingSetup) state._pendingSetup = [];
|
|
2778
|
-
state._pendingSetup.push(
|
|
2779
|
-
t.variableDeclaration('const', [
|
|
2780
|
-
t.variableDeclarator(
|
|
2781
|
-
t.identifier(condId),
|
|
2782
|
-
t.callExpression(t.identifier('_$memo'), [
|
|
2783
|
-
t.arrowFunctionExpression([], memoBody)
|
|
2784
|
-
])
|
|
2785
|
-
)
|
|
2786
|
-
])
|
|
2787
|
-
);
|
|
2788
|
-
condition = t.callExpression(t.identifier(condId), []);
|
|
2789
|
-
}
|
|
2790
|
-
|
|
2791
|
-
return t.arrowFunctionExpression([], t.blockStatement([
|
|
2792
|
-
t.variableDeclaration('const', [
|
|
2793
|
-
t.variableDeclarator(vId, condition)
|
|
2794
|
-
]),
|
|
2795
|
-
t.returnStatement(
|
|
2796
|
-
t.conditionalExpression(t.cloneNode(vId), consequent, alternate)
|
|
2797
|
-
)
|
|
2798
|
-
]));
|
|
2799
|
-
}
|
|
2800
|
-
|
|
2801
|
-
// A `when` prop's shape determines how the condition is formed:
|
|
2802
|
-
// - call expression → use as-is when={cond()}
|
|
2803
|
-
// - arrow w/ expression body → use the body when={() => x > 5}
|
|
2804
|
-
// - a proven local signal → invoke it: isOpen() when={isOpen}
|
|
2805
|
-
// - an import or a destructured prop, bare or as the root of a plain
|
|
2806
|
-
// member chain when={FLAG}, when={ns.open}
|
|
2807
|
-
// → resolve it at runtime, exactly as the Show
|
|
2808
|
-
// and Match components do for h():
|
|
2809
|
-
// typeof X === 'function' ? X() : X
|
|
2810
|
-
// Either one can hold a boolean or an accessor
|
|
2811
|
-
// and only the runtime knows which. Calling it
|
|
2812
|
-
// unconditionally threw on a boolean.
|
|
2813
|
-
// - anything else (member, literal, logical, etc.) when={user.isAdmin}
|
|
2814
|
-
// → use the raw expression. Do NOT invoke it:
|
|
2815
|
-
// non-functions would throw at runtime.
|
|
2816
|
-
function buildWhenCondition(whenExpr, state) {
|
|
2817
|
-
if (t.isCallExpression(whenExpr)) return whenExpr;
|
|
2818
|
-
if (t.isArrowFunctionExpression(whenExpr) && t.isExpression(whenExpr.body)) return whenExpr.body;
|
|
2819
|
-
const fromProps = state.signalNames && state.signalNames.fromDestructuredProps;
|
|
2820
|
-
const isUnprovenBinding = name =>
|
|
2821
|
-
(fromProps && fromProps.has(name)) ||
|
|
2822
|
-
(state.importedIdentifiers && state.importedIdentifiers.has(name));
|
|
2823
|
-
if (t.isIdentifier(whenExpr)) {
|
|
2824
|
-
if (isUnprovenBinding(whenExpr.name)) return resolveAccessorAtRuntime(whenExpr);
|
|
2825
|
-
if (state.signalNames && isSignalIdentifier(whenExpr.name, state.signalNames)) {
|
|
2826
|
-
return t.callExpression(whenExpr, []);
|
|
2827
|
-
}
|
|
2828
|
-
return whenExpr;
|
|
2829
|
-
}
|
|
2830
|
-
const root = plainMemberChainRoot(whenExpr);
|
|
2831
|
-
if (root && isUnprovenBinding(root.name)) return resolveAccessorAtRuntime(whenExpr);
|
|
2832
|
-
return whenExpr;
|
|
2833
|
-
}
|
|
2834
|
-
|
|
2835
|
-
// The root identifier of `a.b.c` with no computed keys, else null. Reading
|
|
2836
|
-
// such a chain twice is a pure lookup, so the runtime check below may
|
|
2837
|
-
// evaluate it more than once.
|
|
2838
|
-
function plainMemberChainRoot(expr) {
|
|
2839
|
-
if (!t.isMemberExpression(expr)) return null;
|
|
2840
|
-
let node = expr;
|
|
2841
|
-
while (t.isMemberExpression(node)) {
|
|
2842
|
-
if (node.computed || !t.isIdentifier(node.property)) return null;
|
|
2843
|
-
node = node.object;
|
|
2844
|
-
}
|
|
2845
|
-
return t.isIdentifier(node) ? node : null;
|
|
2846
|
-
}
|
|
2847
|
-
|
|
2848
|
-
function resolveAccessorAtRuntime(ref) {
|
|
2849
|
-
return t.conditionalExpression(
|
|
2850
|
-
t.binaryExpression('===', t.unaryExpression('typeof', ref), t.stringLiteral('function')),
|
|
2851
|
-
t.callExpression(t.cloneNode(ref), []),
|
|
2852
|
-
t.cloneNode(ref)
|
|
2853
|
-
);
|
|
2854
|
-
}
|
|
2855
|
-
|
|
2856
|
-
function collectControlFlowContent(children, state) {
|
|
2857
|
-
const parts = [];
|
|
2858
|
-
for (const child of children) {
|
|
2859
|
-
if (t.isJSXText(child)) {
|
|
2860
|
-
const text = normalizeJsxText(child.value);
|
|
2861
|
-
if (text) parts.push(t.stringLiteral(text));
|
|
2862
|
-
} else if (t.isJSXExpressionContainer(child)) {
|
|
2863
|
-
if (!t.isJSXEmptyExpression(child.expression)) parts.push(child.expression);
|
|
2864
|
-
} else if (t.isJSXElement(child)) {
|
|
2865
|
-
parts.push(transformElementFineGrained({ node: child }, state));
|
|
2866
|
-
} else if (t.isJSXFragment(child)) {
|
|
2867
|
-
parts.push(transformFragmentFineGrained({ node: child }, state));
|
|
2868
|
-
}
|
|
2869
|
-
}
|
|
2870
|
-
if (parts.length === 0) return t.nullLiteral();
|
|
2871
|
-
if (parts.length === 1) return parts[0];
|
|
2872
|
-
return t.arrayExpression(parts);
|
|
2873
|
-
}
|
|
2874
|
-
|
|
2875
|
-
function transformSwitchFineGrained(path, state) {
|
|
2876
|
-
// <Switch fallback={alt}><Match when={a}>A</Match><Match when={b}>B</Match></Switch>
|
|
2877
|
-
// → () => a ? A : b ? B : alt
|
|
2878
|
-
//
|
|
2879
|
-
// Same reactive-thunk shape <Show> lowers to, for the same reason: the
|
|
2880
|
-
// component runs once, so the arm has to be picked inside a thunk that
|
|
2881
|
-
// insert() re-evaluates. The runtime Switch matches on Match marker vnodes,
|
|
2882
|
-
// which _$createComponent never produces (calling Match instead recurses),
|
|
2883
|
-
// so compiled JSX has no working runtime path.
|
|
2884
|
-
//
|
|
2885
|
-
// A <Switch> is provably What's when either its binding was imported from
|
|
2886
|
-
// What or it has literal <Match> arms; anything else with the same tag name
|
|
2887
|
-
// is somebody else's component and goes to the component path untouched.
|
|
2888
|
-
// Once it is provably ours, a shape whose arms cannot be read statically has
|
|
2889
|
-
// nowhere to go, since the runtime component would render its fallback and
|
|
2890
|
-
// nothing else forever. Fail that build rather than emit a silent blank.
|
|
2891
|
-
const { node } = path;
|
|
2892
|
-
|
|
2893
|
-
// A <Switch> that got here on its arms alone came from the same foreign
|
|
2894
|
-
// specifier its arms did, so its <Match> is ours by the same reasoning.
|
|
2895
|
-
const armsProveIt = isForeignTag(node.openingElement.name.name, state);
|
|
2896
|
-
const isMatch = (child) =>
|
|
2897
|
-
t.isJSXElement(child) && t.isJSXIdentifier(child.openingElement.name, { name: 'Match' }) &&
|
|
2898
|
-
(armsProveIt || !isForeignTag('Match', state));
|
|
2899
|
-
if (!node.children.some(isMatch) && !isWhatTag(node.openingElement.name.name, state)) {
|
|
2900
|
-
return transformComponentFineGrained(path, state);
|
|
2901
|
-
}
|
|
2902
|
-
|
|
2903
|
-
const unsupported = (why) => {
|
|
2904
|
-
// The guard this used to carry (`path.buildCodeFrameError ? … : new
|
|
2905
|
-
// Error(…)`) did keep the message reaching the developer from a
|
|
2906
|
-
// synthetic path, but dropped the file and the line with it. compileError
|
|
2907
|
-
// keeps both.
|
|
2908
|
-
throw compileError(
|
|
2909
|
-
path,
|
|
2910
|
-
state,
|
|
2911
|
-
`<Switch> ${why}. The compiler needs to read its arms statically. ` +
|
|
2912
|
-
'Write them out: <Switch fallback={...}><Match when={a}>…</Match><Match when={b}>…</Match></Switch>'
|
|
2913
|
-
);
|
|
2914
|
-
};
|
|
2915
|
-
|
|
2916
|
-
let fallbackExpr = null;
|
|
2917
|
-
for (const attr of node.openingElement.attributes) {
|
|
2918
|
-
if (t.isJSXSpreadAttribute(attr)) unsupported('cannot take a spread attribute');
|
|
2919
|
-
if (getAttrName(attr) === 'fallback') fallbackExpr = getAttributeValue(attr.value);
|
|
2920
|
-
}
|
|
2921
|
-
|
|
2922
|
-
const arms = [];
|
|
2923
|
-
for (const child of node.children) {
|
|
2924
|
-
if (t.isJSXText(child)) {
|
|
2925
|
-
if (normalizeJsxText(child.value)) unsupported('cannot mix text with its <Match> arms');
|
|
2926
|
-
continue;
|
|
2927
|
-
}
|
|
2928
|
-
if (t.isJSXExpressionContainer(child)) {
|
|
2929
|
-
if (t.isJSXEmptyExpression(child.expression)) continue;
|
|
2930
|
-
unsupported('cannot read its arms from an expression child');
|
|
2931
|
-
}
|
|
2932
|
-
if (!isMatch(child)) {
|
|
2933
|
-
unsupported('cannot mix other elements with its <Match> arms');
|
|
2934
|
-
}
|
|
2935
|
-
arms.push(child);
|
|
2936
|
-
}
|
|
2937
|
-
|
|
2938
|
-
if (arms.length === 0) unsupported('has no <Match> arms');
|
|
2939
|
-
|
|
2940
|
-
if (!state._pendingSetup) state._pendingSetup = [];
|
|
2941
|
-
const branches = [];
|
|
2942
|
-
|
|
2943
|
-
for (const arm of arms) {
|
|
2944
|
-
let whenExpr = null;
|
|
2945
|
-
for (const attr of arm.openingElement.attributes) {
|
|
2946
|
-
if (t.isJSXAttribute(attr) && getAttrName(attr) === 'when') whenExpr = getAttributeValue(attr.value);
|
|
2947
|
-
}
|
|
2948
|
-
if (!whenExpr) {
|
|
2949
|
-
unsupported('has a <Match> with no "when" prop');
|
|
2950
|
-
}
|
|
2951
|
-
|
|
2952
|
-
// An arm's element setup belongs inside the arm. Hoisting it next to the
|
|
2953
|
-
// thunk, the way a lone element does, would build every arm's DOM on the
|
|
2954
|
-
// way to picking one.
|
|
2955
|
-
const setupMark = state._pendingSetup.length;
|
|
2956
|
-
let content = collectControlFlowContent(arm.children, state);
|
|
2957
|
-
const setup = state._pendingSetup.splice(setupMark);
|
|
2958
|
-
if (setup.length > 0) {
|
|
2959
|
-
content = t.callExpression(
|
|
2960
|
-
t.arrowFunctionExpression([], t.blockStatement([...setup, t.returnStatement(content)])),
|
|
2961
|
-
[]
|
|
2962
|
-
);
|
|
2963
|
-
}
|
|
2964
|
-
|
|
2965
|
-
branches.push([buildWhenCondition(whenExpr, state), content]);
|
|
2966
|
-
}
|
|
2967
|
-
|
|
2968
|
-
const anyReactive = branches.some(([condition]) =>
|
|
2969
|
-
isPotentiallyReactive(condition, state.signalNames, state.importedIdentifiers));
|
|
2970
|
-
|
|
2971
|
-
const fallback = fallbackExpr || t.nullLiteral();
|
|
2972
|
-
|
|
2973
|
-
if (!anyReactive) {
|
|
2974
|
-
let expr = fallback;
|
|
2975
|
-
for (let i = branches.length - 1; i >= 0; i--) {
|
|
2976
|
-
expr = t.conditionalExpression(branches[i][0], branches[i][1], expr);
|
|
2977
|
-
}
|
|
2978
|
-
return t.arrowFunctionExpression([], expr);
|
|
2979
|
-
}
|
|
2980
|
-
|
|
2981
|
-
// ONE memo over the whole chain, not one per arm. _$memo evaluates its body
|
|
2982
|
-
// immediately, so a memo per arm would evaluate every arm's `when` up front,
|
|
2983
|
-
// while the runtime Switch stops at the first match. A single memo that
|
|
2984
|
-
// resolves to the winning arm's index keeps that short-circuit (`when` props
|
|
2985
|
-
// after the first truthy one are never read) and still gates re-rendering on
|
|
2986
|
-
// the selected arm actually changing.
|
|
2987
|
-
let selector = t.numericLiteral(-1);
|
|
2988
|
-
for (let i = branches.length - 1; i >= 0; i--) {
|
|
2989
|
-
selector = t.conditionalExpression(branches[i][0], t.numericLiteral(i), selector);
|
|
2990
|
-
}
|
|
2991
|
-
|
|
2992
|
-
const armId = state.nextMemoId();
|
|
2993
|
-
state.needsMemo = true;
|
|
2994
|
-
state._pendingSetup.push(
|
|
2995
|
-
t.variableDeclaration('const', [
|
|
2996
|
-
t.variableDeclarator(
|
|
2997
|
-
t.identifier(armId),
|
|
2998
|
-
t.callExpression(t.identifier('_$memo'), [t.arrowFunctionExpression([], selector)])
|
|
2999
|
-
)
|
|
3000
|
-
])
|
|
3001
|
-
);
|
|
3002
|
-
|
|
3003
|
-
let expr = fallback;
|
|
3004
|
-
for (let i = branches.length - 1; i >= 0; i--) {
|
|
3005
|
-
expr = t.conditionalExpression(
|
|
3006
|
-
t.binaryExpression('===', t.callExpression(t.identifier(armId), []), t.numericLiteral(i)),
|
|
3007
|
-
branches[i][1],
|
|
3008
|
-
expr
|
|
3009
|
-
);
|
|
3010
|
-
}
|
|
3011
|
-
return t.arrowFunctionExpression([], expr);
|
|
3012
|
-
}
|
|
3013
|
-
|
|
3014
|
-
// A fragment-as-root returns an array (or single value) that the runtime
|
|
3015
|
-
// mounts element-by-element (createDOM / insert). Unlike the element-child
|
|
3016
|
-
// path there's no host element to _$insert into with a marker, so reactive
|
|
3017
|
-
// children must instead be emitted as `() => expr` arrows — the runtime's
|
|
3018
|
-
// createDOM/insert treat a function array-item as a reactive binding (it
|
|
3019
|
-
// wraps it in an effect with comment markers). Without this, a bare dynamic
|
|
3020
|
-
// expression like `{count()}` is evaluated exactly once and never updates.
|
|
3021
|
-
//
|
|
3022
|
-
// This applies the SAME lowering the element-child expression path uses:
|
|
3023
|
-
// - tryLowerMapToMapArray for keyed `items().map(...)` → _$mapArray
|
|
3024
|
-
// - memoizeBranchCondition for reactive ternary/&&/|| (node-identity stable
|
|
3025
|
-
// branches: the taken branch's DOM is only rebuilt when the condition
|
|
3026
|
-
// actually flips, not on every read of a signal the condition touches)
|
|
3027
|
-
// - reactive expressions wrapped in `() =>` so the runtime tracks them
|
|
3028
|
-
// Memo (_$memo) declarations are pushed into state._pendingSetup, which
|
|
3029
|
-
// transformJsxRoot drains into the enclosing scope. (SPRINT v0.11)
|
|
3030
|
-
function lowerFragmentExprChild(expr, state) {
|
|
3031
|
-
if (!state._pendingSetup) state._pendingSetup = [];
|
|
3032
|
-
const setup = state._pendingSetup;
|
|
3033
|
-
|
|
3034
|
-
// Auto-lower .map() to mapArray when the callback returns keyed JSX.
|
|
3035
|
-
const mapResult = tryLowerMapToMapArray(expr, state);
|
|
3036
|
-
if (mapResult) {
|
|
3037
|
-
state.needsMapArray = true;
|
|
3038
|
-
// A bare _$mapArray(...) is a self-managing inserter and an arrow is
|
|
3039
|
-
// already reactive — emit as-is. A ternary/logical wrapping the call
|
|
3040
|
-
// keeps its condition reactive via a () => wrapper (and memoization).
|
|
3041
|
-
const isBareMapArray = t.isCallExpression(mapResult) && t.isIdentifier(mapResult.callee) &&
|
|
3042
|
-
(mapResult.callee.name === '_$mapArray' || mapResult.callee.name === 'mapArray');
|
|
3043
|
-
const isArrowAlready = t.isArrowFunctionExpression(mapResult);
|
|
3044
|
-
if (isArrowAlready && t.isExpression(mapResult.body)) {
|
|
3045
|
-
mapResult.body = memoizeBranchCondition(mapResult.body, setup, state);
|
|
3046
|
-
return mapResult;
|
|
3047
|
-
}
|
|
3048
|
-
if (isBareMapArray) return mapResult;
|
|
3049
|
-
const memoized = memoizeBranchCondition(mapResult, setup, state);
|
|
3050
|
-
return t.arrowFunctionExpression([], memoized);
|
|
3051
|
-
}
|
|
3052
|
-
|
|
3053
|
-
// mapArray() calls are self-managing inserters — pass directly.
|
|
3054
|
-
const isMapArrayCall = t.isCallExpression(expr) && t.isIdentifier(expr.callee) &&
|
|
3055
|
-
(expr.callee.name === 'mapArray' || expr.callee.name === '_$mapArray');
|
|
3056
|
-
if (isMapArrayCall) {
|
|
3057
|
-
state.needsMapArray = true;
|
|
3058
|
-
if (expr.callee.name === 'mapArray') expr.callee.name = '_$mapArray';
|
|
3059
|
-
return expr;
|
|
3060
|
-
}
|
|
3061
|
-
|
|
3062
|
-
if (isPotentiallyReactive(expr, state.signalNames, state.importedIdentifiers)) {
|
|
3063
|
-
// Branch memoization (C1): conditional/logical children only rebuild the
|
|
3064
|
-
// taken branch's DOM when the condition actually flips.
|
|
3065
|
-
expr = memoizeBranchCondition(expr, setup, state);
|
|
3066
|
-
return t.arrowFunctionExpression([], expr);
|
|
3067
|
-
}
|
|
3068
|
-
|
|
3069
|
-
// Static — emit verbatim.
|
|
3070
|
-
return expr;
|
|
3071
|
-
}
|
|
3072
|
-
|
|
3073
|
-
function transformFragmentFineGrained(path, state) {
|
|
3074
|
-
const { node } = path;
|
|
3075
|
-
const children = node.children;
|
|
3076
|
-
|
|
3077
|
-
const transformed = [];
|
|
3078
|
-
for (const child of children) {
|
|
3079
|
-
if (t.isJSXText(child)) {
|
|
3080
|
-
const text = normalizeJsxText(child.value);
|
|
3081
|
-
if (text) transformed.push(t.stringLiteral(text));
|
|
3082
|
-
} else if (t.isJSXExpressionContainer(child)) {
|
|
3083
|
-
if (!t.isJSXEmptyExpression(child.expression)) {
|
|
3084
|
-
transformed.push(lowerFragmentExprChild(child.expression, state));
|
|
3085
|
-
}
|
|
3086
|
-
} else if (t.isJSXElement(child)) {
|
|
3087
|
-
transformed.push(transformElementFineGrained({ node: child }, state));
|
|
3088
|
-
} else if (t.isJSXFragment(child)) {
|
|
3089
|
-
transformed.push(transformFragmentFineGrained({ node: child }, state));
|
|
3090
|
-
}
|
|
3091
|
-
}
|
|
3092
|
-
|
|
3093
|
-
if (transformed.length === 1) return transformed[0];
|
|
3094
|
-
return t.arrayExpression(transformed);
|
|
3095
|
-
}
|
|
3096
|
-
|
|
3097
|
-
// Template deduplication: same HTML string → same module-level const
|
|
3098
|
-
function getOrCreateTemplate(state, html) {
|
|
3099
|
-
if (state.templateMap.has(html)) {
|
|
3100
|
-
return state.templateMap.get(html);
|
|
3101
|
-
}
|
|
3102
|
-
const id = `_tmpl$${state.templateCount++}`;
|
|
3103
|
-
state.templateMap.set(html, id);
|
|
3104
|
-
state.templates.push({ id, html });
|
|
3105
|
-
return id;
|
|
3106
|
-
}
|
|
3107
|
-
|
|
3108
|
-
// Shared driver for top-level JSX roots (elements AND fragments).
|
|
3109
|
-
//
|
|
3110
|
-
// transformElementFineGrained does NOT emit IIFEs: it pushes setup
|
|
3111
|
-
// statements (`const _el$N = _tmpl$X(); _el$N.$$click = ...; _$insert(...)`)
|
|
3112
|
-
// into state._pendingSetup and returns the bare `_el$N` identifier. Whoever
|
|
3113
|
-
// visits the JSX root is responsible for draining _pendingSetup and placing
|
|
3114
|
-
// those statements somewhere the returned reference can see them.
|
|
3115
|
-
//
|
|
3116
|
-
// The JSXElement visitor always did this; the JSXFragment visitor did not,
|
|
3117
|
-
// so fragments whose element children had dynamic parts (event handlers,
|
|
3118
|
-
// dynamic attrs/children) compiled to references to _el$N variables that
|
|
3119
|
-
// were never declared — a runtime ReferenceError. Both visitors now share
|
|
3120
|
-
// this driver. (SPRINT v0.11: composes with C1 branch memoization and C2
|
|
3121
|
-
// specialized setters — memo/setter statements ride in _pendingSetup too.)
|
|
3122
|
-
function transformJsxRoot(path, state, transform) {
|
|
3123
|
-
// FIX-1: Use scope-aware signal detection instead of file-global.
|
|
3124
|
-
// Memoize per Babel scope: every JSX root in the same scope yields the
|
|
3125
|
-
// same signal-name set, so without this the full scope-chain walk ran
|
|
3126
|
-
// once per element — O(n²) compile time for a large single component.
|
|
3127
|
-
// (AUDIT-2026-06-06 H2)
|
|
3128
|
-
const scope = path.scope;
|
|
3129
|
-
let cache = state._signalNamesCache;
|
|
3130
|
-
if (!cache) cache = state._signalNamesCache = new WeakMap();
|
|
3131
|
-
let names = cache.get(scope);
|
|
3132
|
-
if (!names) {
|
|
3133
|
-
names = collectSignalNamesFromScope(path);
|
|
3134
|
-
cache.set(scope, names);
|
|
3135
|
-
}
|
|
3136
|
-
state.signalNames = names;
|
|
3137
|
-
state._pendingSetup = [];
|
|
3138
|
-
const transformed = transform(path, state);
|
|
3139
|
-
const pending = state._pendingSetup;
|
|
3140
|
-
state._pendingSetup = [];
|
|
3141
|
-
|
|
3142
|
-
if (pending.length > 0) {
|
|
3143
|
-
// Find the enclosing statement to hoist setup before it,
|
|
3144
|
-
// but only if it's in the SAME function scope. Crossing into
|
|
3145
|
-
// an inner arrow/function (e.g., .map(item => <JSX/>)) would
|
|
3146
|
-
// hoist references to closure variables out of scope.
|
|
3147
|
-
let stmtPath = path;
|
|
3148
|
-
let crossedFunctionBoundary = false;
|
|
3149
|
-
// Setup hoisted out of a guard runs whether the guard opens or not.
|
|
3150
|
-
// `return user() && <p>{user().name}</p>` is the React shape everybody
|
|
3151
|
-
// writes, and hoisting built the <p> and ran `() => user().name` at
|
|
3152
|
-
// mount, so the very first render threw on a null user. Same for a
|
|
3153
|
-
// ternary arm and for a guarded arm sitting in a component prop.
|
|
3154
|
-
// A guarded arm has to be CONSTRUCTED INSIDE its guard, which is exactly
|
|
3155
|
-
// what the IIFE path below does.
|
|
3156
|
-
let crossedGuard = false;
|
|
3157
|
-
while (stmtPath && !stmtPath.isStatement()) {
|
|
3158
|
-
if (stmtPath.isArrowFunctionExpression() || stmtPath.isFunctionExpression()) {
|
|
3159
|
-
crossedFunctionBoundary = true;
|
|
3160
|
-
}
|
|
3161
|
-
if (isConditionallyEvaluated(stmtPath)) crossedGuard = true;
|
|
3162
|
-
stmtPath = stmtPath.parentPath;
|
|
3163
|
-
}
|
|
3164
|
-
// We can safely hoist setup as siblings of `stmtPath` ONLY if
|
|
3165
|
-
// `stmtPath` lives inside a statement list (BlockStatement.body or
|
|
3166
|
-
// Program.body). For single-statement positions like
|
|
3167
|
-
// `if (cond) return <jsx/>;` or `while (x) return <jsx/>;`,
|
|
3168
|
-
// Babel's `insertBefore` wraps the parent into a block lazily and
|
|
3169
|
-
// multi-statement inserts end up split across scopes, leaving the
|
|
3170
|
-
// `_$insert(_el$N, ...)` call outside the block that declares
|
|
3171
|
-
// `const _el$N`. This is a TDZ/ReferenceError at runtime.
|
|
3172
|
-
//
|
|
3173
|
-
// To guarantee that ALL setup statements and the returned reference
|
|
3174
|
-
// share one lexical block, require that `stmtPath.listKey` points
|
|
3175
|
-
// at a statement list. Otherwise fall through to the IIFE path,
|
|
3176
|
-
// which is always safe.
|
|
3177
|
-
const inStatementList =
|
|
3178
|
-
stmtPath
|
|
3179
|
-
&& stmtPath.isStatement()
|
|
3180
|
-
&& (stmtPath.listKey === 'body' || stmtPath.listKey === 'consequent')
|
|
3181
|
-
&& Array.isArray(stmtPath.container);
|
|
3182
|
-
if (inStatementList && !crossedFunctionBoundary && !crossedGuard) {
|
|
3183
|
-
// Same function scope — safe to hoist setup before the enclosing
|
|
3184
|
-
// statement. Works for return statements too: `insertBefore`
|
|
3185
|
-
// places setup above `return <jsx/>` without wrapping in an IIFE.
|
|
3186
|
-
stmtPath.insertBefore(pending);
|
|
3187
|
-
path.replaceWith(transformed);
|
|
3188
|
-
} else {
|
|
3189
|
-
// Crossed a function boundary or a guard, or no enclosing statement
|
|
3190
|
-
// was found — fall back to IIFE, which keeps closure variables in
|
|
3191
|
-
// scope AND keeps the construction where the source put it.
|
|
3192
|
-
pending.push(t.returnStatement(transformed));
|
|
3193
|
-
path.replaceWith(
|
|
3194
|
-
t.callExpression(
|
|
3195
|
-
t.arrowFunctionExpression([], t.blockStatement(pending)),
|
|
3196
|
-
[]
|
|
3197
|
-
)
|
|
3198
|
-
);
|
|
3199
|
-
}
|
|
3200
|
-
} else {
|
|
3201
|
-
path.replaceWith(transformed);
|
|
3202
|
-
}
|
|
3203
|
-
}
|
|
3204
|
-
|
|
3205
|
-
function actionBindingName(callPath) {
|
|
3206
|
-
const parent = callPath.parentPath;
|
|
3207
|
-
if (parent?.isVariableDeclarator() && t.isIdentifier(parent.node.id)) {
|
|
3208
|
-
return parent.node.id.name;
|
|
3209
|
-
}
|
|
3210
|
-
if (parent?.isAssignmentExpression() && t.isIdentifier(parent.node.left)) {
|
|
3211
|
-
return parent.node.left.name;
|
|
3212
|
-
}
|
|
3213
|
-
if (parent?.isExportDefaultDeclaration()) return 'default';
|
|
3214
|
-
if (parent?.isObjectProperty() && !parent.node.computed) {
|
|
3215
|
-
if (t.isIdentifier(parent.node.key)) return parent.node.key.name;
|
|
3216
|
-
if (t.isStringLiteral(parent.node.key)) return parent.node.key.value;
|
|
3217
|
-
}
|
|
3218
|
-
return null;
|
|
3219
|
-
}
|
|
3220
|
-
|
|
3221
|
-
function isServerActionCall(callPath, state) {
|
|
3222
|
-
const callee = callPath.node.callee;
|
|
3223
|
-
if (t.isIdentifier(callee)) return state.serverActionBindings.has(callee.name);
|
|
3224
|
-
return t.isMemberExpression(callee)
|
|
3225
|
-
&& !callee.computed
|
|
3226
|
-
&& t.isIdentifier(callee.object)
|
|
3227
|
-
&& t.isIdentifier(callee.property, { name: 'action' })
|
|
3228
|
-
&& state.serverActionNamespaces.has(callee.object.name);
|
|
3229
|
-
}
|
|
3230
|
-
|
|
3231
|
-
function staticActionId(optionsNode) {
|
|
3232
|
-
if (!t.isObjectExpression(optionsNode)) return { property: null, value: null };
|
|
3233
|
-
for (const property of optionsNode.properties) {
|
|
3234
|
-
if (!t.isObjectProperty(property)) continue;
|
|
3235
|
-
const key = t.isIdentifier(property.key) && !property.computed ? property.key.name
|
|
3236
|
-
: t.isStringLiteral(property.key) ? property.key.value
|
|
3237
|
-
: null;
|
|
3238
|
-
if (key !== 'id') continue;
|
|
3239
|
-
if (t.isStringLiteral(property.value)) return { property, value: property.value.value };
|
|
3240
|
-
if (t.isTemplateLiteral(property.value) && property.value.expressions.length === 0) {
|
|
3241
|
-
return { property, value: property.value.quasis[0]?.value.cooked || '' };
|
|
3242
|
-
}
|
|
3243
|
-
return { property, value: null };
|
|
3244
|
-
}
|
|
3245
|
-
return { property: null, value: null };
|
|
3246
|
-
}
|
|
3247
|
-
|
|
3248
|
-
function registerActionId(callPath, state, id, bindingName, relativeFilename) {
|
|
3249
|
-
const loc = callPath.node.loc?.start || { line: 0, column: 0 };
|
|
3250
|
-
const source = `${relativeFilename}:${loc.line}:${loc.column + 1}`;
|
|
3251
|
-
const key = `${relativeFilename}#${bindingName}`;
|
|
3252
|
-
const existing = state.serverActionIds.get(id);
|
|
3253
|
-
if (existing) {
|
|
3254
|
-
throw callPath.buildCodeFrameError(
|
|
3255
|
-
`Duplicate server action ID "${id}". ` +
|
|
3256
|
-
`First declared by "${existing.bindingName}" at ${existing.source}; ` +
|
|
3257
|
-
`conflicts with "${bindingName}" at ${source}.`
|
|
3258
|
-
);
|
|
3259
|
-
}
|
|
3260
|
-
const metadata = { id, key, bindingName, filename: relativeFilename, source, loc };
|
|
3261
|
-
state.serverActionIds.set(id, metadata);
|
|
3262
|
-
if (typeof state.opts?.onActionId === 'function') {
|
|
3263
|
-
try {
|
|
3264
|
-
state.opts.onActionId(metadata);
|
|
3265
|
-
} catch (error) {
|
|
3266
|
-
throw callPath.buildCodeFrameError(error instanceof Error ? error.message : String(error));
|
|
3267
|
-
}
|
|
3268
|
-
}
|
|
3269
|
-
}
|
|
3270
|
-
|
|
3271
|
-
function transformServerAction(callPath, state) {
|
|
3272
|
-
if (!isServerActionCall(callPath, state)) return;
|
|
3273
|
-
|
|
3274
|
-
const bindingName = actionBindingName(callPath);
|
|
3275
|
-
if (!bindingName) {
|
|
3276
|
-
if (!state.opts?.production) {
|
|
3277
|
-
console.warn(
|
|
3278
|
-
`[what-compiler] Could not derive a stable server action ID at ` +
|
|
3279
|
-
`${state.serverActionFilename}:${callPath.node.loc?.start.line || 0}. ` +
|
|
3280
|
-
'Assign action(...) to a named local or export, or pass { id } explicitly.'
|
|
3281
|
-
);
|
|
3282
|
-
}
|
|
3283
|
-
return;
|
|
3284
|
-
}
|
|
3285
|
-
|
|
3286
|
-
const optionsNode = callPath.node.arguments[1];
|
|
3287
|
-
const explicit = staticActionId(optionsNode);
|
|
3288
|
-
if (explicit.property) {
|
|
3289
|
-
if (explicit.value !== null) {
|
|
3290
|
-
registerActionId(callPath, state, explicit.value, bindingName, state.serverActionFilename);
|
|
3291
|
-
}
|
|
3292
|
-
return;
|
|
3293
|
-
}
|
|
3294
|
-
|
|
3295
|
-
const id = `wa1_${stableActionHash(`${state.serverActionFilename}#${bindingName}`)}`;
|
|
3296
|
-
registerActionId(callPath, state, id, bindingName, state.serverActionFilename);
|
|
3297
|
-
const idProperty = t.objectProperty(t.identifier('id'), t.stringLiteral(id));
|
|
3298
|
-
|
|
3299
|
-
if (!optionsNode) {
|
|
3300
|
-
callPath.node.arguments.push(t.objectExpression([idProperty]));
|
|
3301
|
-
} else if (t.isObjectExpression(optionsNode)) {
|
|
3302
|
-
optionsNode.properties.unshift(idProperty);
|
|
3303
|
-
} else {
|
|
3304
|
-
// Put the generated default before the caller's dynamic options so a
|
|
3305
|
-
// runtime `options.id` remains authoritative.
|
|
3306
|
-
callPath.node.arguments[1] = t.objectExpression([
|
|
3307
|
-
idProperty,
|
|
3308
|
-
t.spreadElement(optionsNode),
|
|
3309
|
-
]);
|
|
3310
|
-
}
|
|
3311
|
-
}
|
|
3312
|
-
|
|
3313
|
-
// =====================================================
|
|
3314
|
-
// Plugin entry
|
|
3315
|
-
// =====================================================
|
|
86
|
+
export default function whatBabelPlugin({ types }) {
|
|
87
|
+
setTypes(types);
|
|
3316
88
|
|
|
3317
89
|
return {
|
|
3318
90
|
name: 'what-jsx-transform',
|
|
@@ -3320,41 +92,22 @@ export default function whatBabelPlugin({ types: t }) {
|
|
|
3320
92
|
visitor: {
|
|
3321
93
|
Program: {
|
|
3322
94
|
enter(path, state) {
|
|
3323
|
-
|
|
3324
|
-
|
|
3325
|
-
state.
|
|
3326
|
-
|
|
3327
|
-
|
|
3328
|
-
|
|
3329
|
-
state.
|
|
3330
|
-
state
|
|
3331
|
-
|
|
3332
|
-
|
|
3333
|
-
|
|
3334
|
-
|
|
3335
|
-
|
|
3336
|
-
state.
|
|
3337
|
-
state.
|
|
3338
|
-
state
|
|
3339
|
-
state.needsFragment = false;
|
|
3340
|
-
state.needsIsland = false;
|
|
3341
|
-
state.needsDelegation = false;
|
|
3342
|
-
state.delegatedEvents = new Set();
|
|
3343
|
-
state.templates = [];
|
|
3344
|
-
state.templateMap = new Map(); // html → template id (deduplication)
|
|
3345
|
-
state.templateCount = 0;
|
|
3346
|
-
state._varCounter = 0;
|
|
3347
|
-
state._memoCounter = 0;
|
|
3348
|
-
// Separate counter from nextVarId: a <For each> source is not an
|
|
3349
|
-
// element, and calling it _el$N would make the emitted code lie.
|
|
3350
|
-
// One index names the whole group a <For fallback> lowers to, so the
|
|
3351
|
-
// source (_each$N), the list inserter (_for$N) it feeds and the
|
|
3352
|
-
// fallback thunk (_fb$N) beside it are visibly the same <For>.
|
|
3353
|
-
state._listCounter = 0;
|
|
3354
|
-
state._pendingSetup = [];
|
|
3355
|
-
state.nextVarId = () => `_el$${state._varCounter++}`;
|
|
3356
|
-
state.nextMemoId = () => `_c$${state._memoCounter++}`;
|
|
3357
|
-
state.nextForIndex = () => state._listCounter++;
|
|
95
|
+
const mismatch = fileRuntimeMismatch(state.file?.opts?.filename);
|
|
96
|
+
if (mismatch) throw mismatch;
|
|
97
|
+
const generate = state.opts?.generate ?? 'dom';
|
|
98
|
+
if (generate !== 'dom' && generate !== 'ssr') {
|
|
99
|
+
throw new Error(`[what-compiler] Unknown "generate" option ${JSON.stringify(generate)}: use "dom" or "ssr".`);
|
|
100
|
+
}
|
|
101
|
+
state.ssr = generate === 'ssr';
|
|
102
|
+
initFileState(state);
|
|
103
|
+
// A file one of What's own packages publishes is the framework, not
|
|
104
|
+
// the app (framework-files.js): only its JSX is compiled. No
|
|
105
|
+
// development names on its signal() and h() calls, no server action
|
|
106
|
+
// ids, and a function of it with no JSX is never a component
|
|
107
|
+
// (common.js "Which functions are components").
|
|
108
|
+
state.frameworkFile = state.opts?.appSource !== true && isFrameworkModule(state.file?.opts?.filename);
|
|
109
|
+
if (state.ssr) initSsrState(state);
|
|
110
|
+
else initDomState(state);
|
|
3358
111
|
|
|
3359
112
|
state.serverActionBindings = new Set();
|
|
3360
113
|
state.serverActionNamespaces = new Set();
|
|
@@ -3364,9 +117,6 @@ export default function whatBabelPlugin({ types: t }) {
|
|
|
3364
117
|
state.opts?.projectRoot || state.file?.opts?.cwd
|
|
3365
118
|
);
|
|
3366
119
|
|
|
3367
|
-
// Collect signal names for smart reactivity detection
|
|
3368
|
-
state.signalNames = new Set();
|
|
3369
|
-
|
|
3370
120
|
// --- Imported Signal Tracking ---
|
|
3371
121
|
// Only mark imports as potentially reactive if they come from known
|
|
3372
122
|
// reactive sources: what-framework, what-framework/*, relative paths
|
|
@@ -3379,6 +129,12 @@ export default function whatBabelPlugin({ types: t }) {
|
|
|
3379
129
|
// control flow apart from a third party's by provenance instead.
|
|
3380
130
|
state.whatImports = new Set();
|
|
3381
131
|
state.foreignImports = new Set();
|
|
132
|
+
// what-react translate mode's spread through React's host rules
|
|
133
|
+
// (common.js unwrapHostSpreads), by its local names.
|
|
134
|
+
const hostProps = new Set();
|
|
135
|
+
// And the calls that mark and hand over a component it made native
|
|
136
|
+
// (dom.js isPlainFunctionComponent), by their local names.
|
|
137
|
+
state.translatedMarks = new Set();
|
|
3382
138
|
for (const node of path.node.body) {
|
|
3383
139
|
if (t.isImportDeclaration(node)) {
|
|
3384
140
|
const source = node.source.value;
|
|
@@ -3398,6 +154,11 @@ export default function whatBabelPlugin({ types: t }) {
|
|
|
3398
154
|
localName = spec.local.name;
|
|
3399
155
|
}
|
|
3400
156
|
|
|
157
|
+
if (localName && source === 'what-react/translated' && t.isImportSpecifier(spec)) {
|
|
158
|
+
const imported = spec.imported.name ?? spec.imported.value;
|
|
159
|
+
if (imported === '_$hostProps') hostProps.add(localName);
|
|
160
|
+
else if (TRANSLATED_MARKS.has(imported)) state.translatedMarks.add(localName);
|
|
161
|
+
}
|
|
3401
162
|
if (localName) {
|
|
3402
163
|
// Mark as reactive if from a reactive source, or if the name
|
|
3403
164
|
// matches use*/create* conventions (hooks/signal creators)
|
|
@@ -3425,239 +186,96 @@ export default function whatBabelPlugin({ types: t }) {
|
|
|
3425
186
|
}
|
|
3426
187
|
}
|
|
3427
188
|
|
|
189
|
+
unwrapHostSpreads(path, hostProps);
|
|
190
|
+
|
|
191
|
+
// Every name the file already spells, so a generated name never
|
|
192
|
+
// collides with one.
|
|
193
|
+
t.traverseFast(path.node, (node) => {
|
|
194
|
+
if (node.type === 'Identifier' || node.type === 'JSXIdentifier') recordName(state, node.name);
|
|
195
|
+
});
|
|
196
|
+
// A client never builds a <noscript>'s content: with scripts on, the
|
|
197
|
+
// browser parses it as text, so there is nothing of it to create or
|
|
198
|
+
// to hydrate (React's rule). The server writes it.
|
|
199
|
+
if (!state.ssr) {
|
|
200
|
+
t.traverseFast(path.node, (node) => {
|
|
201
|
+
if (node.type === 'JSXElement' && t.isJSXIdentifier(node.openingElement.name, { name: 'noscript' })) node.children = [];
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
// A tag held in a constant the file spells (`const Tag = 'select'`)
|
|
205
|
+
// is that element, as React renders it: written as the element, it
|
|
206
|
+
// is lowered as one on both targets (its namespace, a select's code,
|
|
207
|
+
// hydration). A tag the compiler cannot read is a component call,
|
|
208
|
+
// which what-core renders as the element at run time.
|
|
209
|
+
path.traverse({
|
|
210
|
+
JSXElement(elPath) {
|
|
211
|
+
markRowKey(elPath, state);
|
|
212
|
+
const tag = constantTag(elPath);
|
|
213
|
+
// Whether a component call can build a tag held in a binding,
|
|
214
|
+
// which SVG and MathML places are told of (dom.js _$inNs).
|
|
215
|
+
if (tag === null && !state.ssr && isComponentElement(elPath.node)) elPath.node._whatMayBuildTag = mayBuildTag(elPath.scope, elPath.node.openingElement.name);
|
|
216
|
+
if (tag === null) return;
|
|
217
|
+
elPath.node.openingElement.name = t.jsxIdentifier(tag);
|
|
218
|
+
if (elPath.node.closingElement) elPath.node.closingElement.name = t.jsxIdentifier(tag);
|
|
219
|
+
},
|
|
220
|
+
});
|
|
221
|
+
// Before any JSX is lowered: placed props, server action ids,
|
|
222
|
+
// development names and what each call's callee reads, all read
|
|
223
|
+
// against the original source.
|
|
224
|
+
const calls = [];
|
|
3428
225
|
path.traverse({
|
|
3429
226
|
Function(fnPath) {
|
|
3430
|
-
|
|
227
|
+
if (isReactFunction(fnPath)) {
|
|
228
|
+
fnPath.node.body.directives = fnPath.node.body.directives.filter((d) => d.value.value !== REACT_DIRECTIVE);
|
|
229
|
+
fnPath.skip();
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
// Before deferPlacedProps rewrites destructured props as
|
|
233
|
+
// `props.<key>` reads, so it names them as they are written.
|
|
234
|
+
markHookResults(fnPath, state);
|
|
235
|
+
warnLiveCleanup(fnPath, state);
|
|
236
|
+
memoLiveLets(fnPath, state);
|
|
237
|
+
memoBranchValues(fnPath, state);
|
|
238
|
+
warnDerivedPropOnce(fnPath, state);
|
|
239
|
+
lowerLiveReturns(fnPath, state);
|
|
240
|
+
deferPlacedProps(fnPath, state);
|
|
241
|
+
liveHelperArgs(fnPath, state);
|
|
242
|
+
keepCleanupValues(fnPath, state);
|
|
243
|
+
warnStateReadOnce(fnPath, state);
|
|
244
|
+
markPropFieldReads(fnPath, state);
|
|
3431
245
|
},
|
|
3432
246
|
CallExpression(callPath) {
|
|
3433
|
-
|
|
3434
|
-
|
|
3435
|
-
|
|
3436
|
-
const init = declPath.node.init;
|
|
3437
|
-
if (!init || !t.isCallExpression(init)) return;
|
|
3438
|
-
|
|
3439
|
-
const callee = init.callee;
|
|
3440
|
-
let calleeName = '';
|
|
3441
|
-
if (t.isIdentifier(callee)) {
|
|
3442
|
-
calleeName = callee.name;
|
|
3443
|
-
} else if (t.isMemberExpression(callee) && t.isIdentifier(callee.property)) {
|
|
3444
|
-
calleeName = callee.property.name;
|
|
247
|
+
if (!state.frameworkFile) {
|
|
248
|
+
transformServerAction(callPath, state);
|
|
249
|
+
annotatePrimitive(callPath, state);
|
|
3445
250
|
}
|
|
3446
|
-
|
|
3447
|
-
|
|
3448
|
-
|
|
3449
|
-
|
|
3450
|
-
|
|
3451
|
-
} else if (t.isArrayPattern(id)) {
|
|
3452
|
-
for (const el of id.elements) {
|
|
3453
|
-
if (t.isIdentifier(el)) state.signalNames.add(el.name);
|
|
3454
|
-
}
|
|
3455
|
-
} else if (t.isObjectPattern(id)) {
|
|
3456
|
-
for (const prop of id.properties) {
|
|
3457
|
-
if (t.isObjectProperty(prop) && t.isIdentifier(prop.value)) {
|
|
3458
|
-
state.signalNames.add(prop.value.name);
|
|
3459
|
-
}
|
|
3460
|
-
}
|
|
3461
|
-
}
|
|
3462
|
-
}
|
|
3463
|
-
}
|
|
251
|
+
calls.push(callPath);
|
|
252
|
+
},
|
|
253
|
+
OptionalCallExpression(callPath) {
|
|
254
|
+
calls.push(callPath);
|
|
255
|
+
},
|
|
3464
256
|
});
|
|
257
|
+
// A spread's children, read where they render, once the props
|
|
258
|
+
// they come from are read where they are used.
|
|
259
|
+
path.traverse({
|
|
260
|
+
JSXElement(elPath) {
|
|
261
|
+
spreadChildren(elPath, state);
|
|
262
|
+
},
|
|
263
|
+
});
|
|
264
|
+
resolveCallees(path, calls, state.importedIdentifiers);
|
|
3465
265
|
},
|
|
3466
266
|
|
|
3467
267
|
exit(path, state) {
|
|
3468
|
-
|
|
3469
|
-
|
|
3470
|
-
|
|
3471
|
-
|
|
3472
|
-
// components are tree-shaken away. (SPRINT v0.11 C6)
|
|
3473
|
-
const tmplCall = t.callExpression(t.identifier('_$template'), [t.stringLiteral(tmpl.html)]);
|
|
3474
|
-
t.addComment(tmplCall, 'leading', ' @__PURE__ ');
|
|
3475
|
-
path.unshiftContainer('body',
|
|
3476
|
-
t.variableDeclaration('const', [
|
|
3477
|
-
t.variableDeclarator(t.identifier(tmpl.id), tmplCall)
|
|
3478
|
-
])
|
|
3479
|
-
);
|
|
3480
|
-
}
|
|
3481
|
-
|
|
3482
|
-
// Build fine-grained imports
|
|
3483
|
-
const fgSpecifiers = [];
|
|
3484
|
-
if (state.needsTemplate) {
|
|
3485
|
-
// Import the compiler-internal `_$template` export, NOT the public
|
|
3486
|
-
// `template` export. The public one warns in dev ("template() is a
|
|
3487
|
-
// compiler internal... XSS") — compiled output must never trip that
|
|
3488
|
-
// guard; the warning exists for *hand-written* template() calls
|
|
3489
|
-
// with dynamic strings. (SPRINT v0.11 C5)
|
|
3490
|
-
fgSpecifiers.push(
|
|
3491
|
-
t.importSpecifier(t.identifier('_$template'), t.identifier('_$template'))
|
|
3492
|
-
);
|
|
3493
|
-
}
|
|
3494
|
-
if (state.needsInsert) {
|
|
3495
|
-
fgSpecifiers.push(
|
|
3496
|
-
t.importSpecifier(t.identifier('_$insert'), t.identifier('insert'))
|
|
3497
|
-
);
|
|
3498
|
-
}
|
|
3499
|
-
if (state.needsEffect) {
|
|
3500
|
-
fgSpecifiers.push(
|
|
3501
|
-
t.importSpecifier(t.identifier('_$effect'), t.identifier('effect'))
|
|
3502
|
-
);
|
|
3503
|
-
}
|
|
3504
|
-
if (state.needsMapArray) {
|
|
3505
|
-
fgSpecifiers.push(
|
|
3506
|
-
t.importSpecifier(t.identifier('_$mapArray'), t.identifier('mapArray'))
|
|
3507
|
-
);
|
|
3508
|
-
}
|
|
3509
|
-
if (state.needsSpread) {
|
|
3510
|
-
fgSpecifiers.push(
|
|
3511
|
-
t.importSpecifier(t.identifier('_$spread'), t.identifier('spread'))
|
|
3512
|
-
);
|
|
3513
|
-
}
|
|
3514
|
-
if (state.needsSetProp) {
|
|
3515
|
-
fgSpecifiers.push(
|
|
3516
|
-
t.importSpecifier(t.identifier('_$setProp'), t.identifier('setProp'))
|
|
3517
|
-
);
|
|
3518
|
-
}
|
|
3519
|
-
if (state.needsMemo) {
|
|
3520
|
-
fgSpecifiers.push(
|
|
3521
|
-
t.importSpecifier(t.identifier('_$memo'), t.identifier('memo'))
|
|
3522
|
-
);
|
|
3523
|
-
}
|
|
3524
|
-
if (state.needsSetClass) {
|
|
3525
|
-
fgSpecifiers.push(
|
|
3526
|
-
t.importSpecifier(t.identifier('_$setClass'), t.identifier('setClass'))
|
|
3527
|
-
);
|
|
3528
|
-
}
|
|
3529
|
-
if (state.needsSetStyle) {
|
|
3530
|
-
fgSpecifiers.push(
|
|
3531
|
-
t.importSpecifier(t.identifier('_$setStyle'), t.identifier('setStyle'))
|
|
3532
|
-
);
|
|
3533
|
-
}
|
|
3534
|
-
if (state.needsSetAttr) {
|
|
3535
|
-
fgSpecifiers.push(
|
|
3536
|
-
t.importSpecifier(t.identifier('_$setAttr'), t.identifier('setAttr'))
|
|
3537
|
-
);
|
|
3538
|
-
}
|
|
3539
|
-
if (state.needsSetValue) {
|
|
3540
|
-
fgSpecifiers.push(
|
|
3541
|
-
t.importSpecifier(t.identifier('_$setValue'), t.identifier('setValue'))
|
|
3542
|
-
);
|
|
3543
|
-
}
|
|
3544
|
-
if (state.needsSetChecked) {
|
|
3545
|
-
fgSpecifiers.push(
|
|
3546
|
-
t.importSpecifier(t.identifier('_$setChecked'), t.identifier('setChecked'))
|
|
3547
|
-
);
|
|
3548
|
-
}
|
|
3549
|
-
if (state.needsCreateComponent) {
|
|
3550
|
-
fgSpecifiers.push(
|
|
3551
|
-
t.importSpecifier(t.identifier('_$createComponent'), t.identifier('_$createComponent'))
|
|
3552
|
-
);
|
|
3553
|
-
}
|
|
3554
|
-
if (state.needsComponentVNode) {
|
|
3555
|
-
fgSpecifiers.push(
|
|
3556
|
-
t.importSpecifier(t.identifier('_$componentVNode'), t.identifier('_$componentVNode'))
|
|
3557
|
-
);
|
|
268
|
+
if (state.ssr) finishSsrProgram(path, state);
|
|
269
|
+
else {
|
|
270
|
+
readPropFields(path, state);
|
|
271
|
+
finishDomProgram(path, state);
|
|
3558
272
|
}
|
|
3559
|
-
|
|
3560
|
-
fgSpecifiers.push(
|
|
3561
|
-
t.importSpecifier(t.identifier('_$delegateEvents'), t.identifier('delegateEvents'))
|
|
3562
|
-
);
|
|
3563
|
-
}
|
|
3564
|
-
|
|
3565
|
-
// Core imports (h/Fragment/Island for components)
|
|
3566
|
-
const coreSpecifiers = [];
|
|
3567
|
-
if (state.needsH) {
|
|
3568
|
-
coreSpecifiers.push(
|
|
3569
|
-
t.importSpecifier(t.identifier('h'), t.identifier('h'))
|
|
3570
|
-
);
|
|
3571
|
-
}
|
|
3572
|
-
if (state.needsFragment) {
|
|
3573
|
-
coreSpecifiers.push(
|
|
3574
|
-
t.importSpecifier(t.identifier('Fragment'), t.identifier('Fragment'))
|
|
3575
|
-
);
|
|
3576
|
-
}
|
|
3577
|
-
if (state.needsIsland) {
|
|
3578
|
-
coreSpecifiers.push(
|
|
3579
|
-
t.importSpecifier(t.identifier('Island'), t.identifier('Island'))
|
|
3580
|
-
);
|
|
3581
|
-
}
|
|
3582
|
-
|
|
3583
|
-
if (fgSpecifiers.length > 0) {
|
|
3584
|
-
/** @type {any} */
|
|
3585
|
-
let existingRenderImport = null;
|
|
3586
|
-
for (const node of path.node.body) {
|
|
3587
|
-
if (t.isImportDeclaration(node) && (
|
|
3588
|
-
node.source.value === 'what-framework/render' ||
|
|
3589
|
-
node.source.value === 'what-core/render'
|
|
3590
|
-
)) {
|
|
3591
|
-
existingRenderImport = node;
|
|
3592
|
-
break;
|
|
3593
|
-
}
|
|
3594
|
-
}
|
|
3595
|
-
|
|
3596
|
-
if (existingRenderImport) {
|
|
3597
|
-
const existingNames = new Set(
|
|
3598
|
-
existingRenderImport.specifiers
|
|
3599
|
-
.filter(s => t.isImportSpecifier(s))
|
|
3600
|
-
.map(s => s.imported.name)
|
|
3601
|
-
);
|
|
3602
|
-
for (const spec of fgSpecifiers) {
|
|
3603
|
-
if (!existingNames.has(spec.imported.name)) {
|
|
3604
|
-
existingRenderImport.specifiers.push(spec);
|
|
3605
|
-
}
|
|
3606
|
-
}
|
|
3607
|
-
} else {
|
|
3608
|
-
path.unshiftContainer('body',
|
|
3609
|
-
t.importDeclaration(fgSpecifiers, t.stringLiteral('what-framework/render'))
|
|
3610
|
-
);
|
|
3611
|
-
}
|
|
3612
|
-
}
|
|
3613
|
-
|
|
3614
|
-
if (coreSpecifiers.length > 0) {
|
|
3615
|
-
addCoreImports(path, t, coreSpecifiers);
|
|
3616
|
-
}
|
|
3617
|
-
|
|
3618
|
-
// Emit LAZY event delegation setup if any delegated events were used.
|
|
3619
|
-
// Previously this was a bare module-top-level `_$delegateEvents([...])`
|
|
3620
|
-
// call — a side effect that (a) prevented bundlers from tree-shaking
|
|
3621
|
-
// modules whose components are never used, and (b) attached document
|
|
3622
|
-
// listeners at import time even when no component ever mounted.
|
|
3623
|
-
// Instead we emit a once-guarded helper that each element setup calls
|
|
3624
|
-
// at construction time; unused modules carry only dead declarations
|
|
3625
|
-
// that DCE removes. (SPRINT v0.11 C6)
|
|
3626
|
-
if (state.needsDelegation && state.delegatedEvents && state.delegatedEvents.size > 0) {
|
|
3627
|
-
const eventArray = t.arrayExpression(
|
|
3628
|
-
[...state.delegatedEvents].map(e => t.stringLiteral(e))
|
|
3629
|
-
);
|
|
3630
|
-
// function _$delegate$() { if (_$delegated$) return; _$delegated$ = true; _$delegateEvents([...]); }
|
|
3631
|
-
const helperFn = t.functionDeclaration(
|
|
3632
|
-
t.identifier('_$delegate$'),
|
|
3633
|
-
[],
|
|
3634
|
-
t.blockStatement([
|
|
3635
|
-
t.ifStatement(
|
|
3636
|
-
t.identifier('_$delegated$'),
|
|
3637
|
-
t.returnStatement()
|
|
3638
|
-
),
|
|
3639
|
-
t.expressionStatement(
|
|
3640
|
-
t.assignmentExpression('=', t.identifier('_$delegated$'), t.booleanLiteral(true))
|
|
3641
|
-
),
|
|
3642
|
-
t.expressionStatement(
|
|
3643
|
-
t.callExpression(t.identifier('_$delegateEvents'), [eventArray])
|
|
3644
|
-
),
|
|
3645
|
-
])
|
|
3646
|
-
);
|
|
3647
|
-
// Unshift so `let _$delegated$ = false` executes before any
|
|
3648
|
-
// top-level component construction (e.g. a same-module mount()).
|
|
3649
|
-
path.unshiftContainer('body', [
|
|
3650
|
-
t.variableDeclaration('let', [
|
|
3651
|
-
t.variableDeclarator(t.identifier('_$delegated$'), t.booleanLiteral(false))
|
|
3652
|
-
]),
|
|
3653
|
-
helperFn,
|
|
3654
|
-
]);
|
|
3655
|
-
}
|
|
3656
|
-
}
|
|
273
|
+
},
|
|
3657
274
|
},
|
|
3658
275
|
|
|
3659
276
|
JSXElement(path, state) {
|
|
3660
|
-
|
|
277
|
+
if (state.ssr) transformSsrRoot(path, state);
|
|
278
|
+
else transformJsxRoot(path, state);
|
|
3661
279
|
},
|
|
3662
280
|
|
|
3663
281
|
JSXFragment(path, state) {
|
|
@@ -3665,40 +283,9 @@ export default function whatBabelPlugin({ types: t }) {
|
|
|
3665
283
|
// `const _el$N = ...` setup into _pendingSetup, which MUST be drained
|
|
3666
284
|
// here (hoisted or IIFE-wrapped) or the emitted `_el$N` references
|
|
3667
285
|
// are never declared (ReferenceError at runtime).
|
|
3668
|
-
|
|
3669
|
-
|
|
3670
|
-
|
|
286
|
+
if (state.ssr) transformSsrRoot(path, state);
|
|
287
|
+
else transformJsxRoot(path, state);
|
|
288
|
+
},
|
|
289
|
+
},
|
|
3671
290
|
};
|
|
3672
291
|
}
|
|
3673
|
-
|
|
3674
|
-
function addCoreImports(path, t, coreSpecifiers) {
|
|
3675
|
-
/** @type {any} */
|
|
3676
|
-
let existingImport = null;
|
|
3677
|
-
for (const node of path.node.body) {
|
|
3678
|
-
if (t.isImportDeclaration(node) && (
|
|
3679
|
-
node.source.value === 'what-core' || node.source.value === 'what-framework'
|
|
3680
|
-
)) {
|
|
3681
|
-
existingImport = node;
|
|
3682
|
-
break;
|
|
3683
|
-
}
|
|
3684
|
-
}
|
|
3685
|
-
|
|
3686
|
-
if (existingImport) {
|
|
3687
|
-
const existingNames = new Set(
|
|
3688
|
-
existingImport.specifiers
|
|
3689
|
-
.filter(s => t.isImportSpecifier(s))
|
|
3690
|
-
.map(s => s.imported.name)
|
|
3691
|
-
);
|
|
3692
|
-
for (const spec of coreSpecifiers) {
|
|
3693
|
-
if (!existingNames.has(spec.imported.name)) {
|
|
3694
|
-
existingImport.specifiers.push(spec);
|
|
3695
|
-
}
|
|
3696
|
-
}
|
|
3697
|
-
} else {
|
|
3698
|
-
const importDecl = t.importDeclaration(
|
|
3699
|
-
coreSpecifiers,
|
|
3700
|
-
t.stringLiteral('what-framework')
|
|
3701
|
-
);
|
|
3702
|
-
path.unshiftContainer('body', importDecl);
|
|
3703
|
-
}
|
|
3704
|
-
}
|