@kayjs/kay 2.0.0-alpha.8 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +442 -0
  4. package/src/build/compile.ts +20 -11
  5. package/src/build/files.ts +136 -0
  6. package/src/build/graph.ts +158 -0
  7. package/src/build/index.ts +231 -1296
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +224 -0
  10. package/src/build/plugin-host.ts +184 -0
  11. package/src/build/prerender.ts +93 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +58 -0
  14. package/src/build/routes.ts +135 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +228 -114
  17. package/src/cli/index.ts +298 -79
  18. package/src/cli/new.ts +67 -35
  19. package/src/compiler/analyze.ts +666 -91
  20. package/src/compiler/dom.ts +822 -629
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +164 -21
  24. package/src/compiler/shared.ts +442 -0
  25. package/src/compiler/ssr.ts +390 -324
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +291 -76
  28. package/src/dom/action.ts +23 -13
  29. package/src/dom/extras.ts +157 -84
  30. package/src/dom/index.ts +154 -33
  31. package/src/dom/island.ts +117 -39
  32. package/src/dom/loop.ts +34 -21
  33. package/src/index.ts +2 -1
  34. package/src/jsx-runtime.ts +11 -0
  35. package/src/plugins/context.ts +57 -0
  36. package/src/plugins/index.ts +120 -17
  37. package/src/reactivity/index.ts +250 -157
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +37 -12
  40. package/src/server/action.ts +217 -74
  41. package/src/server/compress.ts +155 -56
  42. package/src/server/cookies.ts +59 -22
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +201 -33
  45. package/src/server/index.ts +964 -737
  46. package/src/server/loader.ts +120 -0
  47. package/src/server/router.ts +27 -8
  48. package/src/server/security.ts +87 -39
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +96 -10
  52. package/src/ssr/index.ts +225 -56
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +5 -0
  55. package/src/unrenderable.ts +35 -0
@@ -1,21 +1,57 @@
1
1
  // Kay v2 Client DOM compiler: compiles TSX to hoisted template() clones, child-path walks,
2
- // delegated events, compiler-safe destructured props, and fine-grained keyed .map() loops.
3
-
4
- import type { AstNode, ModuleAnalysis } from './analyze'
5
- import { analyzeModule, parseTsx, walk } from './analyze'
2
+ // delegated events, compiler-safe destructured props, reactive spreads, and shared balanced hydration markers.
3
+
4
+ import type {
5
+ ArrowFunctionExpression,
6
+ BlockStatement,
7
+ Function as OxcFunction,
8
+ JSXElement,
9
+ JSXFragment,
10
+ Node,
11
+ ObjectPattern,
12
+ ParamPattern,
13
+ Program,
14
+ } from 'oxc-parser'
15
+ import type { ModuleAnalysis } from './analyze'
16
+ import { analyzeModule, loadDeclarations, parseTsx, walk } from './analyze'
6
17
  import { SourceEditor } from './patch'
7
- import { cleanJsxText, escapeStaticText } from './ssr'
8
-
9
- const VOID_ELEMENTS = new Set([
10
- 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
11
- 'link', 'meta', 'param', 'source', 'track', 'wbr',
12
- ])
18
+ import {
19
+ classifyJsxChild,
20
+ cleanJsxText,
21
+ collectPatternNames,
22
+ containsJsx,
23
+ decodeHtmlEntities,
24
+ DOM_PROPS,
25
+ escapeRawText,
26
+ escapeStaticAttr,
27
+ escapeStaticText,
28
+ EVENT_ATTR,
29
+ filterMeaningfulChildren,
30
+ isBlockedAttr,
31
+ isComponentTag,
32
+ isJsxNode,
33
+ isNodeCapableExpr,
34
+ isStringBoolAttr,
35
+ isUnsafeUrlAttr,
36
+ jsxTagName,
37
+ RAW_TEXT_ELEMENTS,
38
+ staticLiteral,
39
+ unwrapParens,
40
+ unwrapTsExpr,
41
+ VOID_ELEMENTS,
42
+ } from './shared'
13
43
 
14
44
  const SVG_CHILD_TAGS = new Set([
15
45
  'path', 'circle', 'rect', 'line', 'polyline', 'polygon', 'ellipse',
16
- 'g', 'defs', 'use', 'text', 'tspan', 'clipPath', 'mask',
17
- 'linearGradient', 'radialGradient', 'stop', 'pattern', 'symbol',
18
- 'marker', 'filter', 'feGaussianBlur', 'foreignObject', 'animate',
46
+ 'g', 'defs', 'use', 'text', 'tspan', 'textPath', 'clipPath', 'mask',
47
+ 'linearGradient', 'radialGradient', 'stop', 'pattern', 'symbol', 'image',
48
+ 'marker', 'filter', 'feBlend', 'feColorMatrix', 'feComponentTransfer',
49
+ 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap',
50
+ 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG',
51
+ 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode',
52
+ 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting',
53
+ 'feSpotLight', 'feTile', 'feTurbulence', 'foreignObject', 'animate',
54
+ 'animateMotion', 'animateTransform', 'set', 'mpath', 'desc', 'metadata', 'switch',
19
55
  ])
20
56
 
21
57
  const DELEGATED_EVENTS = new Set([
@@ -24,9 +60,6 @@ const DELEGATED_EVENTS = new Set([
24
60
  'pointerdown', 'pointerup', 'touchstart', 'touchend',
25
61
  ])
26
62
 
27
- const DOM_PROPS = new Set(['value', 'checked', 'selected', 'muted', 'indeterminate'])
28
- const EVENT_ATTR = /^on([A-Z]\w*)$/
29
-
30
63
  export interface CompileDomOptions {
31
64
  analysis?: ModuleAnalysis | undefined
32
65
  }
@@ -36,95 +69,187 @@ export interface CompileDomResult {
36
69
  analysis: ModuleAnalysis
37
70
  }
38
71
 
39
- function jsxTagName(node: AstNode): string {
40
- if (node.type === 'JSXIdentifier')
41
- return node.name as string
42
- if (node.type === 'JSXMemberExpression')
43
- return `${jsxTagName(node.object)}.${node.property.name}`
44
- if (node.type === 'JSXNamespacedName')
45
- return `${node.namespace.name}:${node.name.name}`
46
- return ''
47
- }
48
-
49
- function isComponentTag(tag: string): boolean {
50
- const first = tag.charCodeAt(0)
51
- return (first >= 65 && first <= 90) || tag.includes('.')
52
- }
53
-
54
- function unwrapParens(node: AstNode): AstNode {
55
- let cur = node
56
- while (cur.type === 'ParenthesizedExpression')
57
- cur = cur.expression as AstNode
58
- return cur
59
- }
60
-
61
- function escapeStaticAttr(str: string): string {
62
- return str
63
- .replaceAll('&', '&amp;')
64
- .replaceAll('"', '&quot;')
65
- .replaceAll('<', '&lt;')
66
- .replaceAll('>', '&gt;')
72
+ function withoutBindings(rewrites: ReadonlyMap<string, string>, patterns: readonly Node[]): Map<string, string> {
73
+ const names = new Set<string>()
74
+ for (const pattern of patterns)
75
+ collectPatternNames(pattern, names)
76
+ const kept = new Map(rewrites)
77
+ for (const name of names)
78
+ kept.delete(name)
79
+ return kept
67
80
  }
68
81
 
69
- function staticLiteral(node: AstNode): { ok: true, value: string | number | boolean | null } | { ok: false } {
70
- const n = unwrapParens(node)
71
- if (n.type === 'Literal') {
72
- const v = n.value
73
- if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null)
74
- return { ok: true, value: v }
82
+ // Names whose every binding in the file is a `const` holding an array literal: only those can be looped once without tracking.
83
+ function literalArrayConsts(program: Program): Set<string> {
84
+ const literal = new Set<string>()
85
+ const other = new Set<string>()
86
+ const bindOther = (pattern: Node | null | undefined): void => {
87
+ if (pattern !== null && pattern !== undefined)
88
+ collectPatternNames(pattern, other)
75
89
  }
76
- if (n.type === 'UnaryExpression' && n.operator === '-' && n.argument?.type === 'Literal' && typeof n.argument.value === 'number')
77
- return { ok: true, value: -n.argument.value }
78
- return { ok: false }
90
+ walk(program, (node) => {
91
+ if (node.type === 'VariableDeclaration') {
92
+ for (const decl of node.declarations) {
93
+ const init = decl.init !== null ? unwrapTsExpr(decl.init) : null
94
+ if (node.kind === 'const' && decl.id.type === 'Identifier' && init?.type === 'ArrayExpression')
95
+ literal.add(decl.id.name)
96
+ else
97
+ bindOther(decl.id)
98
+ }
99
+ }
100
+ else if (node.type === 'ImportSpecifier' || node.type === 'ImportDefaultSpecifier' || node.type === 'ImportNamespaceSpecifier') {
101
+ bindOther(node.local)
102
+ }
103
+ else if (node.type === 'FunctionDeclaration' || node.type === 'ClassDeclaration') {
104
+ bindOther(node.id)
105
+ }
106
+ if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
107
+ for (const param of node.params)
108
+ bindOther(param)
109
+ }
110
+ else if (node.type === 'CatchClause') {
111
+ bindOther(node.param)
112
+ }
113
+ })
114
+ for (const name of other)
115
+ literal.delete(name)
116
+ return literal
79
117
  }
80
118
 
81
- function collectPatternNames(pattern: AstNode, out: Set<string>): void {
82
- if (!pattern)
83
- return
84
- if (pattern.type === 'Identifier') {
85
- out.add(pattern.name as string)
86
- }
87
- else if (pattern.type === 'AssignmentPattern') {
88
- collectPatternNames(pattern.left, out)
89
- }
90
- else if (pattern.type === 'RestElement') {
91
- collectPatternNames(pattern.argument, out)
92
- }
93
- else if (pattern.type === 'ArrayPattern') {
94
- for (const el of pattern.elements as (AstNode | null)[]) {
95
- if (el !== null)
96
- collectPatternNames(el, out)
97
- }
98
- }
99
- else if (pattern.type === 'ObjectPattern') {
100
- for (const prop of pattern.properties as AstNode[]) {
101
- if (prop.type === 'RestElement')
102
- collectPatternNames(prop.argument, out)
103
- else
104
- collectPatternNames(prop.value, out)
119
+ /** Collects free identifier references inside a node (ignoring shadowed locals and property keys). */
120
+ function referencesAny(rootNode: Node, names: ReadonlySet<string>): boolean {
121
+ if (names.size === 0)
122
+ return false
123
+ let found = false
124
+ function visit(node: Node | null | undefined, shadowed: Set<string>): void {
125
+ if (found || node === null || node === undefined)
126
+ return
127
+ switch (node.type) {
128
+ case 'Identifier':
129
+ if (!shadowed.has(node.name) && names.has(node.name))
130
+ found = true
131
+ return
132
+ case 'MemberExpression':
133
+ visit(node.object, shadowed)
134
+ if (node.computed)
135
+ visit(node.property, shadowed)
136
+ return
137
+ case 'Property':
138
+ if (node.computed)
139
+ visit(node.key, shadowed)
140
+ visit(node.value, shadowed)
141
+ return
142
+ case 'ArrowFunctionExpression':
143
+ case 'FunctionExpression':
144
+ case 'FunctionDeclaration': {
145
+ const next = new Set(shadowed)
146
+ if (node.type !== 'ArrowFunctionExpression' && node.id !== null)
147
+ next.add(node.id.name)
148
+ for (const p of node.params)
149
+ collectPatternNames(p, next)
150
+ visit(node.body, next)
151
+ return
152
+ }
153
+ case 'BlockStatement': {
154
+ const next = new Set(shadowed)
155
+ for (const stmt of node.body) {
156
+ if (stmt.type === 'VariableDeclaration') {
157
+ for (const d of stmt.declarations) {
158
+ visit(d.init, next)
159
+ collectPatternNames(d.id, next)
160
+ }
161
+ }
162
+ else {
163
+ visit(stmt, next)
164
+ }
165
+ }
166
+ return
167
+ }
168
+ default: {
169
+ if (node.type.startsWith('TS'))
170
+ return
171
+ for (const [k, v] of Object.entries(node)) {
172
+ if (k === 'start' || k === 'end' || k === 'type')
173
+ continue
174
+ if (Array.isArray(v)) {
175
+ for (const item of v) {
176
+ if (item !== null && typeof item === 'object' && 'type' in item)
177
+ visit(item as Node, shadowed)
178
+ }
179
+ }
180
+ else if (v !== null && typeof v === 'object' && 'type' in v) {
181
+ visit(v as Node, shadowed)
182
+ }
183
+ }
184
+ }
105
185
  }
106
186
  }
187
+ visit(rootNode, new Set())
188
+ return found
107
189
  }
108
190
 
109
- /** Rewrites free identifier reads inside an AST node while respecting shadowing and property keys. */
191
+ /** Rewrites free identifier reads inside an AST node while respecting lexical scopes, class/object keys, labels, and nested JSX/components. */
110
192
  function rewriteFreeIdentifiers(
111
193
  source: string,
112
- rootNode: AstNode,
194
+ rootNode: Node,
113
195
  replacements: ReadonlyMap<string, string>,
196
+ onJsx?: (node: JSXElement | JSXFragment, rewrites: ReadonlyMap<string, string>) => string,
197
+ onFunction?: (fn: ArrowFunctionExpression | OxcFunction, rewrites: ReadonlyMap<string, string>) => string | undefined,
114
198
  ): string {
115
- if (replacements.size === 0)
199
+ if (replacements.size === 0 && (onJsx === undefined || !containsJsx(rootNode)))
116
200
  return source.slice(rootNode.start, rootNode.end)
117
201
 
118
- const offset = rootNode.start as number
202
+ const offset = rootNode.start
119
203
  const editor = new SourceEditor(source.slice(rootNode.start, rootNode.end))
120
204
 
121
- function visit(node: AstNode | null | undefined, shadowed: Set<string>): void {
122
- if (!node || typeof node !== 'object')
205
+ function visitPatternDefaults(pattern: Node | null | undefined, shadowed: Set<string>): void {
206
+ if (pattern === null || pattern === undefined)
123
207
  return
208
+ switch (pattern.type) {
209
+ case 'AssignmentPattern':
210
+ visitPatternDefaults(pattern.left, shadowed)
211
+ visit(pattern.right, shadowed)
212
+ return
213
+ case 'RestElement':
214
+ visitPatternDefaults(pattern.argument, shadowed)
215
+ return
216
+ case 'TSParameterProperty':
217
+ visitPatternDefaults(pattern.parameter, shadowed)
218
+ return
219
+ case 'ArrayPattern':
220
+ for (const el of pattern.elements)
221
+ visitPatternDefaults(el, shadowed)
222
+ return
223
+ case 'ObjectPattern':
224
+ for (const prop of pattern.properties) {
225
+ if (prop.type === 'RestElement') {
226
+ visitPatternDefaults(prop.argument, shadowed)
227
+ }
228
+ else {
229
+ if (prop.computed)
230
+ visit(prop.key, shadowed)
231
+ visitPatternDefaults(prop.value, shadowed)
232
+ }
233
+ }
234
+ }
235
+ }
236
+
237
+ function activeMap(shadowed: Set<string>): ReadonlyMap<string, string> {
238
+ return shadowed.size === 0 ? replacements : new Map([...replacements].filter(([k]) => !shadowed.has(k)))
239
+ }
240
+
241
+ function visit(node: Node | null | undefined, shadowed: Set<string>): void {
242
+ if (node === null || node === undefined)
243
+ return
244
+
245
+ if (onJsx !== undefined && isJsxNode(node)) {
246
+ editor.replace(node.start - offset, node.end - offset, onJsx(node, activeMap(shadowed)))
247
+ return
248
+ }
124
249
 
125
250
  switch (node.type) {
126
251
  case 'Identifier': {
127
- const name = node.name as string
252
+ const name = node.name
128
253
  if (!shadowed.has(name)) {
129
254
  const rep = replacements.get(name)
130
255
  if (rep !== undefined)
@@ -138,11 +263,19 @@ function rewriteFreeIdentifiers(
138
263
  visit(node.property, shadowed)
139
264
  return
140
265
  }
266
+ case 'MetaProperty':
267
+ case 'BreakStatement':
268
+ case 'ContinueStatement':
269
+ return
270
+ case 'LabeledStatement': {
271
+ visit(node.body, shadowed)
272
+ return
273
+ }
141
274
  case 'Property': {
142
275
  if (node.computed)
143
276
  visit(node.key, shadowed)
144
- if (node.shorthand && node.value?.type === 'Identifier') {
145
- const name = node.value.name as string
277
+ if (node.shorthand && node.value.type === 'Identifier') {
278
+ const name = node.value.name
146
279
  if (!shadowed.has(name) && replacements.has(name)) {
147
280
  editor.replace(node.start - offset, node.end - offset, `${name}: ${replacements.get(name)}`)
148
281
  return
@@ -151,31 +284,100 @@ function rewriteFreeIdentifiers(
151
284
  visit(node.value, shadowed)
152
285
  return
153
286
  }
287
+ case 'MethodDefinition':
288
+ case 'PropertyDefinition': {
289
+ if (node.computed)
290
+ visit(node.key, shadowed)
291
+ visit(node.value, shadowed)
292
+ return
293
+ }
294
+ case 'ClassDeclaration':
295
+ case 'ClassExpression': {
296
+ const next = new Set(shadowed)
297
+ if (node.id !== null)
298
+ next.add(node.id.name)
299
+ visit(node.superClass, shadowed)
300
+ visit(node.body, next)
301
+ return
302
+ }
303
+ case 'CatchClause': {
304
+ const next = new Set(shadowed)
305
+ visitPatternDefaults(node.param, next)
306
+ collectPatternNames(node.param, next)
307
+ visit(node.body, next)
308
+ return
309
+ }
310
+ case 'ForStatement': {
311
+ const next = new Set(shadowed)
312
+ if (node.init !== null) {
313
+ if (node.init.type === 'VariableDeclaration') {
314
+ for (const d of node.init.declarations) {
315
+ visit(d.init, next)
316
+ visitPatternDefaults(d.id, next)
317
+ collectPatternNames(d.id, next)
318
+ }
319
+ }
320
+ else {
321
+ visit(node.init, next)
322
+ }
323
+ }
324
+ visit(node.test, next)
325
+ visit(node.update, next)
326
+ visit(node.body, next)
327
+ return
328
+ }
329
+ case 'ForInStatement':
330
+ case 'ForOfStatement': {
331
+ visit(node.right, shadowed)
332
+ const next = new Set(shadowed)
333
+ if (node.left.type === 'VariableDeclaration') {
334
+ for (const d of node.left.declarations) {
335
+ visitPatternDefaults(d.id, next)
336
+ collectPatternNames(d.id, next)
337
+ }
338
+ }
339
+ else {
340
+ visit(node.left, next)
341
+ }
342
+ visit(node.body, next)
343
+ return
344
+ }
154
345
  case 'ArrowFunctionExpression':
155
346
  case 'FunctionExpression':
156
347
  case 'FunctionDeclaration': {
348
+ if (node !== rootNode && onFunction !== undefined) {
349
+ const compiled = onFunction(node, activeMap(shadowed))
350
+ if (compiled !== undefined) {
351
+ editor.replace(node.start - offset, node.end - offset, compiled)
352
+ return
353
+ }
354
+ }
157
355
  const nextShadow = new Set(shadowed)
158
- if (node.id?.name)
159
- nextShadow.add(node.id.name as string)
160
- for (const p of node.params as AstNode[])
356
+ if (node.type !== 'ArrowFunctionExpression' && node.id !== null)
357
+ nextShadow.add(node.id.name)
358
+ for (const p of node.params) {
359
+ visitPatternDefaults(p, nextShadow)
161
360
  collectPatternNames(p, nextShadow)
361
+ }
162
362
  visit(node.body, nextShadow)
163
363
  return
164
364
  }
165
365
  case 'BlockStatement': {
166
366
  const nextShadow = new Set(shadowed)
167
- for (const stmt of node.body as AstNode[]) {
367
+ for (const stmt of node.body) {
368
+ if (stmt.type === 'FunctionDeclaration' && stmt.id !== null)
369
+ nextShadow.add(stmt.id.name)
370
+ else if (stmt.type === 'ClassDeclaration' && stmt.id !== null)
371
+ nextShadow.add(stmt.id.name)
372
+ }
373
+ for (const stmt of node.body) {
168
374
  if (stmt.type === 'VariableDeclaration') {
169
- for (const d of stmt.declarations as AstNode[]) {
375
+ for (const d of stmt.declarations) {
170
376
  visit(d.init, nextShadow)
377
+ visitPatternDefaults(d.id, nextShadow)
171
378
  collectPatternNames(d.id, nextShadow)
172
379
  }
173
380
  }
174
- else if (stmt.type === 'FunctionDeclaration') {
175
- if (stmt.id?.name)
176
- nextShadow.add(stmt.id.name as string)
177
- visit(stmt, nextShadow)
178
- }
179
381
  else {
180
382
  visit(stmt, nextShadow)
181
383
  }
@@ -184,15 +386,7 @@ function rewriteFreeIdentifiers(
184
386
  }
185
387
  case 'VariableDeclarator': {
186
388
  visit(node.init, shadowed)
187
- return
188
- }
189
- case 'JSXAttribute': {
190
- visit(node.value, shadowed)
191
- return
192
- }
193
- case 'JSXOpeningElement': {
194
- for (const attr of node.attributes as AstNode[])
195
- visit(attr, shadowed)
389
+ visitPatternDefaults(node.id, shadowed)
196
390
  return
197
391
  }
198
392
  case 'TSAsExpression':
@@ -204,19 +398,20 @@ function rewriteFreeIdentifiers(
204
398
  return
205
399
  }
206
400
  default: {
207
- // Skip pure TypeScript type annotation nodes
208
- if (typeof node.type === 'string' && node.type.startsWith('TS'))
401
+ if (node.type.startsWith('TS'))
209
402
  return
210
- for (const key of Object.keys(node)) {
403
+ for (const [key, val] of Object.entries(node)) {
211
404
  if (key === 'start' || key === 'end' || key === 'type')
212
405
  continue
213
- const val = node[key]
214
406
  if (Array.isArray(val)) {
215
- for (let i = 0; i < val.length; i++)
216
- visit(val[i] as AstNode, shadowed)
407
+ for (let i = 0; i < val.length; i++) {
408
+ const item = val[i]
409
+ if (item !== null && typeof item === 'object' && 'type' in item)
410
+ visit(item as Node, shadowed)
411
+ }
217
412
  }
218
- else if (val !== null && typeof val === 'object') {
219
- visit(val as AstNode, shadowed)
413
+ else if (val !== null && typeof val === 'object' && 'type' in val) {
414
+ visit(val as Node, shadowed)
220
415
  }
221
416
  }
222
417
  }
@@ -234,11 +429,16 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
234
429
  if (!analysis.hasJsx && !analysis.hasLoadExport)
235
430
  return { code, analysis }
236
431
 
432
+ const staticArrays = literalArrayConsts(program)
433
+ const loadNodes = new Set<Node>(loadDeclarations(program))
434
+
237
435
  const editor = new SourceEditor(code)
238
436
  const used = new Set<string>()
239
437
  const templates: { name: string, html: string, isSvg?: boolean }[] = []
240
438
  const delegatedEvents = new Set<string>()
241
439
  let varCounter = 0
440
+ // Tracks whether the current JSX tree is enclosed by `<svg>` (reset inside `<foreignObject>`).
441
+ let svgDepth = 0
242
442
 
243
443
  const use = (name: string): string => {
244
444
  used.add(name)
@@ -246,40 +446,82 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
246
446
  }
247
447
  const freshVar = (prefix = '_e'): string => `${prefix}${varCounter++}`
248
448
 
249
- // Strip `export async function load(...)` in client builds
250
- for (const stmt of program.body as AstNode[]) {
251
- if (stmt.type === 'ExportNamedDeclaration') {
252
- const decl = stmt.declaration as AstNode | null
253
- if (decl?.type === 'FunctionDeclaration' && decl.id?.name === 'load')
254
- editor.remove(stmt.start, stmt.end)
449
+ // How each name a destructuring pattern binds is read from `source` on every access, so reads stay reactive.
450
+ function patternReads(pattern: Node, source: string, outerRewrites: ReadonlyMap<string, string>): Map<string, string> {
451
+ const reads = new Map<string, string>()
452
+ const running = new Map(outerRewrites)
453
+ if (pattern.type === 'ObjectPattern') {
454
+ for (const prop of pattern.properties) {
455
+ if (prop.type !== 'Property' || prop.computed || prop.key.type !== 'Identifier')
456
+ continue
457
+ const read = `${source}.${prop.key.name}`
458
+ if (prop.value.type === 'Identifier') {
459
+ reads.set(prop.value.name, read)
460
+ running.set(prop.value.name, read)
461
+ }
462
+ else if (prop.value.type === 'AssignmentPattern' && prop.value.left.type === 'Identifier') {
463
+ const defExpr = compileExpression(prop.value.right, running)
464
+ const simpleDef = prop.value.right.type === 'Literal' || prop.value.right.type === 'Identifier'
465
+ const expr = `(${read} === undefined ? ${simpleDef ? defExpr : `(${defExpr})`} : ${read})`
466
+ reads.set(prop.value.left.name, expr)
467
+ running.set(prop.value.left.name, expr)
468
+ }
469
+ }
470
+ }
471
+ const names = new Set<string>()
472
+ collectPatternNames(pattern, names)
473
+ const patCode = code.slice(pattern.start, pattern.end)
474
+ for (const name of names) {
475
+ if (!reads.has(name))
476
+ reads.set(name, `((${patCode}) => ${name})(${source})`)
255
477
  }
478
+ return reads
256
479
  }
257
480
 
258
- function hasJsxDescendant(node: AstNode | null | undefined): boolean {
259
- if (!node)
260
- return false
261
- let found = false
262
- walk(node, (child) => {
263
- if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
264
- found = true
265
- return false
266
- }
481
+ // Client builds keep the `load` binding, so every export form stays valid, and drop its server-only code.
482
+ for (const node of loadNodes) {
483
+ if (node.type === 'FunctionDeclaration' && node.id !== null)
484
+ editor.replace(node.start, node.end, `const ${node.id.name} = undefined`)
485
+ else
486
+ editor.replace(node.start, node.end, 'undefined')
487
+ }
488
+
489
+ function extractKeyExpr(jsxEl: Node): Node | undefined {
490
+ if (jsxEl.type !== 'JSXElement')
267
491
  return undefined
268
- })
269
- return found
492
+ for (const attr of jsxEl.openingElement.attributes) {
493
+ if (attr.type === 'JSXAttribute' && attr.name.type === 'JSXIdentifier' && attr.name.name === 'key') {
494
+ if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression')
495
+ return attr.value.expression
496
+ if (attr.value?.type === 'Literal')
497
+ return attr.value
498
+ }
499
+ }
500
+ return undefined
270
501
  }
271
502
 
272
- function extractBlockKeyExpr(block: AstNode): AstNode | undefined {
273
- let found: AstNode | undefined
503
+ function extractBlockKeyExpr(block: BlockStatement): Node | undefined {
504
+ const blockLocals = new Set<string>()
505
+ for (const stmt of block.body) {
506
+ if (stmt.type === 'VariableDeclaration') {
507
+ for (const d of stmt.declarations)
508
+ collectPatternNames(d.id, blockLocals)
509
+ }
510
+ else if ((stmt.type === 'FunctionDeclaration' || stmt.type === 'ClassDeclaration') && stmt.id !== null) {
511
+ blockLocals.add(stmt.id.name)
512
+ }
513
+ }
514
+ let found: Node | undefined
274
515
  walk(block, (child) => {
275
516
  if (found !== undefined)
276
517
  return false
277
518
  if (child.type === 'ArrowFunctionExpression' || child.type === 'FunctionExpression' || child.type === 'FunctionDeclaration')
278
519
  return false
279
- if (child.type === 'ReturnStatement' && child.argument) {
280
- const arg = unwrapParens(child.argument as AstNode)
520
+ if (child.type === 'ReturnStatement' && child.argument !== null) {
521
+ const arg = unwrapParens(child.argument)
281
522
  const k = extractKeyExpr(arg)
282
- if (k !== undefined) {
523
+ // Only hoist key expressions that don't depend on block-local variables.
524
+ if (k !== undefined && !referencesAny(k, blockLocals)) {
283
525
  found = k
284
526
  return false
285
527
  }
@@ -289,128 +531,38 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
289
531
  return found
290
532
  }
291
533
 
292
- function compileExpression(node: AstNode, scopeRewrites: ReadonlyMap<string, string>): string {
293
- if (!hasJsxDescendant(node))
294
- return rewriteFreeIdentifiers(code, node, scopeRewrites)
295
-
296
- // Replace nested JSX roots AND rewrite free identifiers in all surrounding non-JSX spans (respecting shadowing)
297
- const offset = node.start as number
298
- const sub = new SourceEditor(code.slice(node.start, node.end))
299
-
300
- function visitExpr(cur: AstNode | null | undefined, shadowed: Set<string>): void {
301
- if (!cur || typeof cur !== 'object')
302
- return
303
-
304
- if (cur.type === 'JSXElement' || cur.type === 'JSXFragment') {
305
- const activeRewrites = shadowed.size === 0
306
- ? scopeRewrites
307
- : new Map([...scopeRewrites].filter(([k]) => !shadowed.has(k)))
308
- sub.replace(cur.start - offset, cur.end - offset, compileRootJsx(cur, activeRewrites))
309
- return
310
- }
311
-
312
- switch (cur.type) {
313
- case 'Identifier': {
314
- const name = cur.name as string
315
- if (!shadowed.has(name)) {
316
- const rep = scopeRewrites.get(name)
317
- if (rep !== undefined)
318
- sub.replace(cur.start - offset, cur.end - offset, rep)
319
- }
320
- return
321
- }
322
- case 'MemberExpression': {
323
- visitExpr(cur.object, shadowed)
324
- if (cur.computed)
325
- visitExpr(cur.property, shadowed)
326
- return
327
- }
328
- case 'Property': {
329
- if (cur.computed)
330
- visitExpr(cur.key, shadowed)
331
- if (cur.shorthand && cur.value?.type === 'Identifier') {
332
- const name = cur.value.name as string
333
- if (!shadowed.has(name) && scopeRewrites.has(name)) {
334
- sub.replace(cur.start - offset, cur.end - offset, `${name}: ${scopeRewrites.get(name)}`)
335
- return
336
- }
337
- }
338
- visitExpr(cur.value, shadowed)
339
- return
340
- }
341
- case 'ArrowFunctionExpression':
342
- case 'FunctionExpression':
343
- case 'FunctionDeclaration': {
344
- const nextShadow = new Set(shadowed)
345
- if (cur.id?.name)
346
- nextShadow.add(cur.id.name as string)
347
- for (const p of cur.params as AstNode[])
348
- collectPatternNames(p, nextShadow)
349
- visitExpr(cur.body, nextShadow)
350
- return
351
- }
352
- case 'BlockStatement': {
353
- const nextShadow = new Set(shadowed)
354
- for (const stmt of cur.body as AstNode[]) {
355
- if (stmt.type === 'VariableDeclaration') {
356
- for (const d of stmt.declarations as AstNode[]) {
357
- visitExpr(d.init, nextShadow)
358
- collectPatternNames(d.id, nextShadow)
359
- }
360
- }
361
- else if (stmt.type === 'FunctionDeclaration') {
362
- if (stmt.id?.name)
363
- nextShadow.add(stmt.id.name as string)
364
- visitExpr(stmt, nextShadow)
365
- }
366
- else {
367
- visitExpr(stmt, nextShadow)
368
- }
369
- }
370
- return
371
- }
372
- case 'VariableDeclarator': {
373
- visitExpr(cur.init, shadowed)
374
- return
375
- }
376
- case 'TSAsExpression':
377
- case 'TSNonNullExpression':
378
- case 'TSSatisfiesExpression':
379
- case 'TSTypeAssertion':
380
- case 'TSInstantiationExpression': {
381
- visitExpr(cur.expression, shadowed)
382
- return
383
- }
384
- default: {
385
- if (typeof cur.type === 'string' && cur.type.startsWith('TS'))
386
- return
387
- for (const key of Object.keys(cur)) {
388
- if (key === 'start' || key === 'end' || key === 'type')
389
- continue
390
- const val = cur[key]
391
- if (Array.isArray(val)) {
392
- for (let i = 0; i < val.length; i++)
393
- visitExpr(val[i] as AstNode, shadowed)
394
- }
395
- else if (val !== null && typeof val === 'object') {
396
- visitExpr(val as AstNode, shadowed)
397
- }
398
- }
399
- }
400
- }
401
- }
534
+ function compileNestedComponent(fn: ArrowFunctionExpression | OxcFunction, outerRewrites: ReadonlyMap<string, string>): string | undefined {
535
+ if (!containsJsx(fn.body))
536
+ return undefined
537
+ const firstParam = fn.params[0]
538
+ const destructured = extractDestructuredParam(firstParam)
539
+ if (destructured === undefined)
540
+ return undefined
541
+ return buildCompiledFunction(fn, outerRewrites)
542
+ }
402
543
 
403
- visitExpr(node, new Set())
404
- return sub.toString()
544
+ function compileExpression(node: Node, scopeRewrites: ReadonlyMap<string, string>): string {
545
+ return rewriteFreeIdentifiers(code, node, scopeRewrites, compileRootJsx, compileNestedComponent)
405
546
  }
406
547
 
407
- function compileComponentCall(node: AstNode, scopeRewrites: ReadonlyMap<string, string>): string {
548
+ function compileComponentCall(node: JSXElement, scopeRewrites: ReadonlyMap<string, string>): string {
408
549
  const tag = jsxTagName(node.openingElement.name)
409
- const propEntries: string[] = []
550
+ const attrs = node.openingElement.attributes
551
+ const hasSpread = attrs.some(a => a.type === 'JSXSpreadAttribute')
552
+ const segments: string[] = []
553
+ let currentObj: string[] = []
554
+
555
+ const flushObj = () => {
556
+ if (currentObj.length > 0) {
557
+ segments.push(`{ ${currentObj.join(', ')} }`)
558
+ currentObj = []
559
+ }
560
+ }
410
561
 
411
- for (const attr of node.openingElement.attributes as AstNode[]) {
562
+ for (const attr of attrs) {
412
563
  if (attr.type === 'JSXSpreadAttribute') {
413
- propEntries.push(`...(${compileExpression(attr.argument, scopeRewrites)})`)
564
+ flushObj()
565
+ segments.push(`(${compileExpression(attr.argument, scopeRewrites)})`)
414
566
  continue
415
567
  }
416
568
  const name = jsxTagName(attr.name)
@@ -419,111 +571,103 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
419
571
 
420
572
  const propKey = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name)
421
573
  if (attr.value === null) {
422
- propEntries.push(`${propKey}: true`)
574
+ currentObj.push(`${propKey}: true`)
423
575
  }
424
576
  else if (attr.value.type === 'Literal') {
425
- propEntries.push(`${propKey}: ${JSON.stringify(attr.value.value)}`)
577
+ currentObj.push(`${propKey}: ${JSON.stringify(attr.value.value)}`)
426
578
  }
427
- else if (attr.value.type === 'JSXExpressionContainer') {
428
- const expr = attr.value.expression as AstNode
579
+ else if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
580
+ const expr = attr.value.expression
429
581
  const exprCode = compileExpression(expr, scopeRewrites)
430
- // Reactive getter for dynamic expressions; plain property for literals, functions, and bare identifiers (signals)
582
+ // Reactive getter for dynamic expressions; plain property for literals and inline functions.
431
583
  const isStatic = expr.type === 'Literal'
432
584
  || expr.type === 'ArrowFunctionExpression'
433
585
  || expr.type === 'FunctionExpression'
434
586
  if (isStatic)
435
- propEntries.push(`${propKey}: ${exprCode}`)
587
+ currentObj.push(`${propKey}: ${exprCode}`)
436
588
  else
437
- propEntries.push(`get ${propKey}() { return ${exprCode} }`)
589
+ currentObj.push(`get ${propKey}() { return ${exprCode} }`)
438
590
  }
439
591
  }
440
592
 
441
- const meaningful = filterChildren(node.children as AstNode[])
593
+ const meaningful = filterMeaningfulChildren(node.children)
442
594
  if (meaningful.length === 1) {
443
595
  const child = meaningful[0]!
444
596
  if (child.type === 'JSXText')
445
- propEntries.push(`children: ${JSON.stringify(cleanJsxText(child.value as string))}`)
446
- else if (child.type === 'JSXElement' || child.type === 'JSXFragment')
447
- propEntries.push(`get children() { return ${compileRootJsx(child, scopeRewrites)} }`)
448
- else if (child.type === 'JSXExpressionContainer')
449
- propEntries.push(`get children() { return ${compileExpression(child.expression, scopeRewrites)} }`)
597
+ currentObj.push(`children: ${JSON.stringify(decodeHtmlEntities(cleanJsxText(child.value)))}`)
598
+ else if (isJsxNode(child))
599
+ currentObj.push(`get children() { return ${compileRootJsx(child, scopeRewrites)} }`)
600
+ else if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression')
601
+ currentObj.push(`get children() { return ${compileExpression(child.expression, scopeRewrites)} }`)
450
602
  }
451
603
  else if (meaningful.length > 1) {
452
604
  const items = meaningful.map((c) => {
453
605
  if (c.type === 'JSXText')
454
- return JSON.stringify(cleanJsxText(c.value as string))
455
- if (c.type === 'JSXElement' || c.type === 'JSXFragment')
606
+ return JSON.stringify(decodeHtmlEntities(cleanJsxText(c.value)))
607
+ if (isJsxNode(c))
456
608
  return compileRootJsx(c, scopeRewrites)
457
- return compileExpression(c.expression, scopeRewrites)
609
+ if (c.type === 'JSXExpressionContainer' && c.expression.type !== 'JSXEmptyExpression')
610
+ return compileExpression(c.expression, scopeRewrites)
611
+ return 'null'
458
612
  })
459
- propEntries.push(`get children() { return [${items.join(', ')}] }`)
613
+ currentObj.push(`get children() { return [${items.join(', ')}] }`)
460
614
  }
461
615
 
462
- const propsObj = propEntries.length > 0 ? `{ ${propEntries.join(', ')} }` : '{}'
463
- return `${tag}(${propsObj})`
464
- }
616
+ flushObj()
465
617
 
466
- function filterChildren(children: AstNode[]): AstNode[] {
467
- return children.filter((c) => {
468
- if (c.type === 'JSXText')
469
- return cleanJsxText(c.value as string) !== ''
470
- if (c.type === 'JSXExpressionContainer' && c.expression.type === 'JSXEmptyExpression')
471
- return false
472
- return true
473
- })
474
- }
475
-
476
- function extractKeyExpr(jsxEl: AstNode): AstNode | undefined {
477
- if (jsxEl.type !== 'JSXElement')
478
- return undefined
479
- for (const attr of jsxEl.openingElement.attributes as AstNode[]) {
480
- if (attr.type === 'JSXAttribute' && attr.name?.name === 'key') {
481
- if (attr.value?.type === 'JSXExpressionContainer')
482
- return attr.value.expression as AstNode
483
- if (attr.value?.type === 'Literal')
484
- return attr.value as AstNode
485
- }
618
+ if (!hasSpread) {
619
+ const propsObj = segments[0] ?? '{}'
620
+ return `${tag}(${propsObj})`
486
621
  }
487
- return undefined
622
+ if (segments.length === 1)
623
+ return `${tag}(${segments[0]!})`
624
+ return `${tag}(${use('mergeProps')}(${segments.join(', ')}))`
488
625
  }
489
626
 
490
- function compileElementTree(rootEl: AstNode, scopeRewrites: ReadonlyMap<string, string>): string {
627
+ function compileElementTree(rootEl: JSXElement, scopeRewrites: ReadonlyMap<string, string>): string {
491
628
  const ops: string[] = []
492
629
  const rootVar = freshVar('_e')
493
630
  const childRefs = new Map<string, string>() // "parentVar:index" -> varName
494
- const childMaxIdx = new Map<string, number>()
495
631
 
496
- function ensureNode(parentVar: string, index: number): string {
497
- const key = `${parentVar}:${index}`
498
- const existing = childRefs.get(key)
499
- if (existing !== undefined)
500
- return existing
501
- const v = freshVar('_e')
502
- childRefs.set(key, v)
503
- const prevMax = childMaxIdx.get(parentVar) ?? -1
504
- if (index > prevMax)
505
- childMaxIdx.set(parentVar, index)
506
- return v
632
+ const walkPlan: { parentVar: string, index: number, varName: string }[] = []
633
+ const textSlotsByParent = new Map<string, Set<number>>()
634
+ const rangeSlotsByParent = new Map<string, Set<number>>()
635
+
636
+ const addTextSlot = (parentVar: string, idx: number) => {
637
+ let s = textSlotsByParent.get(parentVar)
638
+ if (s === undefined) {
639
+ s = new Set()
640
+ textSlotsByParent.set(parentVar, s)
641
+ }
642
+ s.add(idx)
507
643
  }
508
644
 
509
- const walkPlan: { parentVar: string, index: number, varName: string }[] = []
510
- const dynamicTextSlots = new Set<string>() // "parentVar:textIndex" for optional SSR text between <!---->...<!---->
645
+ const addRangeSlot = (parentVar: string, idx: number) => {
646
+ let s = rangeSlotsByParent.get(parentVar)
647
+ if (s === undefined) {
648
+ s = new Set()
649
+ rangeSlotsByParent.set(parentVar, s)
650
+ }
651
+ s.add(idx)
652
+ }
511
653
 
512
654
  function requestChild(parentVar: string, index: number): string {
513
655
  const key = `${parentVar}:${index}`
514
656
  const existing = childRefs.get(key)
515
657
  if (existing !== undefined)
516
658
  return existing
517
- const v = ensureNode(parentVar, index)
659
+ const v = freshVar('_e')
660
+ childRefs.set(key, v)
518
661
  walkPlan.push({ parentVar, index, varName: v })
519
662
  return v
520
663
  }
521
664
 
522
- function buildHtml(el: AstNode, elVar: string): string {
665
+ function buildHtml(el: JSXElement, elVar: string): string {
523
666
  const tag = jsxTagName(el.openingElement.name)
667
+ const rawTextTag = RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined
524
668
  let html = `<${tag}`
525
669
 
526
- for (const attr of el.openingElement.attributes as AstNode[]) {
670
+ for (const attr of el.openingElement.attributes) {
527
671
  if (attr.type === 'JSXSpreadAttribute') {
528
672
  ops.push(`${use('spread')}(${elVar}, () => (${compileExpression(attr.argument, scopeRewrites)}));`)
529
673
  continue
@@ -532,49 +676,62 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
532
676
  if (rawName === 'key' || rawName === '$hydrate')
533
677
  continue
534
678
 
535
- if (rawName === 'ref' && attr.value?.type === 'JSXExpressionContainer') {
536
- const refCode = compileExpression(attr.value.expression, scopeRewrites)
537
- ops.push(`(${refCode})(${elVar});`)
679
+ if (rawName === 'ref') {
680
+ if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
681
+ const refCode = compileExpression(attr.value.expression, scopeRewrites)
682
+ ops.push(`(${refCode})(${elVar});`)
683
+ }
538
684
  continue
539
685
  }
540
686
 
541
687
  if (rawName === 'innerHTML') {
542
688
  if (attr.value?.type === 'Literal')
543
689
  ops.push(`${use('setInnerHtml')}(${elVar}, ${JSON.stringify(String(attr.value.value))});`)
544
- else if (attr.value?.type === 'JSXExpressionContainer')
690
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression')
545
691
  ops.push(`${use('effect')}(() => ${use('setInnerHtml')}(${elVar}, ${compileExpression(attr.value.expression, scopeRewrites)}));`)
546
692
  continue
547
693
  }
548
694
 
549
695
  const eventMatch = EVENT_ATTR.exec(rawName)
550
- if (eventMatch !== null && attr.value?.type === 'JSXExpressionContainer') {
551
- const eventName = eventMatch[1]!.toLowerCase()
552
- const handlerCode = compileExpression(attr.value.expression, scopeRewrites)
553
- if (DELEGATED_EVENTS.has(eventName)) {
554
- delegatedEvents.add(eventName)
555
- ops.push(`${elVar}.$$${eventName} = ${handlerCode};`)
556
- }
557
- else {
558
- ops.push(`${use('on')}(${elVar}, ${JSON.stringify(eventName)}, ${handlerCode});`)
696
+ if (eventMatch !== null) {
697
+ if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
698
+ const eventName = eventMatch[1]!.toLowerCase()
699
+ const handlerCode = compileExpression(attr.value.expression, scopeRewrites)
700
+ if (DELEGATED_EVENTS.has(eventName)) {
701
+ delegatedEvents.add(eventName)
702
+ ops.push(`${elVar}.$$${eventName} = ${handlerCode};`)
703
+ }
704
+ else {
705
+ ops.push(`${use('on')}(${elVar}, ${JSON.stringify(eventName)}, ${handlerCode});`)
706
+ }
559
707
  }
560
708
  continue
561
709
  }
562
710
 
563
711
  const name = rawName === 'className' ? 'class' : rawName === 'htmlFor' ? 'for' : rawName
712
+ if (isBlockedAttr(name))
713
+ continue
714
+
564
715
  if (attr.value === null) {
565
- html += ` ${name}`
716
+ html += isStringBoolAttr(name) ? ` ${name}="true"` : ` ${name}`
566
717
  }
567
718
  else if (attr.value.type === 'Literal') {
568
- html += ` ${name}="${escapeStaticAttr(String(attr.value.value))}"`
719
+ if (!isUnsafeUrlAttr(name, attr.value.value))
720
+ html += ` ${name}="${escapeStaticAttr(String(attr.value.value))}"`
569
721
  }
570
- else if (attr.value.type === 'JSXExpressionContainer') {
571
- const expr = attr.value.expression as AstNode
572
- const lit = !DOM_PROPS.has(name) && name !== 'style' ? staticLiteral(expr) : { ok: false as const }
722
+ else if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
723
+ const expr = attr.value.expression
724
+ const lit = !DOM_PROPS.has(name) ? staticLiteral(expr) : { ok: false as const }
573
725
  if (lit.ok) {
574
- if (lit.value === true)
575
- html += ` ${name}`
576
- else if (lit.value !== false && lit.value !== null)
726
+ if (typeof lit.value === 'boolean') {
727
+ if (isStringBoolAttr(name))
728
+ html += ` ${name}="${lit.value ? 'true' : 'false'}"`
729
+ else if (lit.value === true)
730
+ html += ` ${name}`
731
+ }
732
+ else if (lit.value !== null && !isUnsafeUrlAttr(name, lit.value)) {
577
733
  html += ` ${name}="${escapeStaticAttr(String(lit.value))}"`
734
+ }
578
735
  continue
579
736
  }
580
737
  const exprCode = compileExpression(expr, scopeRewrites)
@@ -593,262 +750,249 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
593
750
  if (VOID_ELEMENTS.has(tag))
594
751
  return html
595
752
 
596
- const meaningful = filterChildren(el.children as AstNode[])
753
+ const meaningful = filterMeaningfulChildren(el.children)
754
+ const slots = meaningful.map(c => classifyJsxChild(c)).filter(s => s !== undefined)
755
+ const hasSiblings = slots.length > 1
597
756
  let domIndex = 0
598
757
  let prevWasStaticText = false
758
+ let hadVariableRange = false
759
+
760
+ const prevSvgDepth = svgDepth
761
+ if (tag === 'svg')
762
+ svgDepth = 1
763
+ else if (tag === 'foreignObject')
764
+ svgDepth = 0
765
+
766
+ try {
767
+ for (let i = 0; i < slots.length; i++) {
768
+ const slot = slots[i]!
769
+ const isLast = i === slots.length - 1
770
+
771
+ if (slot.kind === 'static-text') {
772
+ if (rawTextTag !== undefined)
773
+ html += escapeRawText(slot.text, rawTextTag)
774
+ else
775
+ html += escapeStaticText(slot.fromLiteral ? slot.text : decodeHtmlEntities(slot.text))
776
+ if (!prevWasStaticText) {
777
+ domIndex++
778
+ prevWasStaticText = true
779
+ }
780
+ continue
781
+ }
599
782
 
600
- for (let i = 0; i < meaningful.length; i++) {
601
- const child = meaningful[i]!
602
- const isLast = i === meaningful.length - 1
783
+ prevWasStaticText = false
603
784
 
604
- if (child.type === 'JSXText') {
605
- html += cleanJsxText(child.value as string)
606
- if (!prevWasStaticText) {
607
- domIndex++
608
- prevWasStaticText = true
785
+ if (slot.kind === 'element') {
786
+ const subOpsBefore = ops.length
787
+ const subWalkBefore = walkPlan.length
788
+ const placeholderVar = `__SUB_${varCounter++}`
789
+ const subHtml = buildHtml(slot.node, placeholderVar)
790
+ const needed = ops.length > subOpsBefore || walkPlan.length > subWalkBefore
791
+ if (needed) {
792
+ const realVar = requestChild(elVar, domIndex)
793
+ for (let k = subOpsBefore; k < ops.length; k++)
794
+ ops[k] = ops[k]!.replaceAll(placeholderVar, realVar)
795
+ for (let k = subWalkBefore; k < walkPlan.length; k++) {
796
+ if (walkPlan[k]!.parentVar === placeholderVar)
797
+ walkPlan[k]!.parentVar = realVar
798
+ }
799
+ const tSlots = textSlotsByParent.get(placeholderVar)
800
+ if (tSlots !== undefined) {
801
+ textSlotsByParent.delete(placeholderVar)
802
+ textSlotsByParent.set(realVar, tSlots)
803
+ }
804
+ const rSlots = rangeSlotsByParent.get(placeholderVar)
805
+ if (rSlots !== undefined) {
806
+ rangeSlotsByParent.delete(placeholderVar)
807
+ rangeSlotsByParent.set(realVar, rSlots)
808
+ }
609
809
  }
810
+ html += subHtml
811
+ domIndex++
610
812
  continue
611
813
  }
612
814
 
613
- if (child.type === 'JSXExpressionContainer' && child.expression?.type === 'Literal' && typeof child.expression.value === 'string') {
614
- html += escapeStaticText(child.expression.value)
615
- if (!prevWasStaticText) {
815
+ if (slot.kind === 'component' || slot.kind === 'fragment') {
816
+ const renderedCode = slot.kind === 'component'
817
+ ? compileComponentCall(slot.node, scopeRewrites)
818
+ : compileRootJsx(slot.node, scopeRewrites)
819
+ if (!hasSiblings) {
820
+ ops.push(`${use('insert')}(${elVar}, () => ${renderedCode}, null, null);`)
821
+ }
822
+ else if (isLast) {
823
+ const startVar = requestChild(elVar, domIndex)
824
+ html += '<!--k[-->'
616
825
  domIndex++
617
- prevWasStaticText = true
826
+ ops.push(`${use('insert')}(${elVar}, () => ${renderedCode}, null, ${startVar});`)
827
+ }
828
+ else {
829
+ const startVar = requestChild(elVar, domIndex)
830
+ const endVar = requestChild(elVar, domIndex + 1)
831
+ html += '<!--k[--><!--k]-->'
832
+ addRangeSlot(elVar, domIndex + 1)
833
+ domIndex += 2
834
+ ops.push(`${use('insert')}(${elVar}, () => ${renderedCode}, ${endVar}, ${startVar});`)
618
835
  }
836
+ hadVariableRange = true
619
837
  continue
620
838
  }
621
839
 
622
- prevWasStaticText = false
840
+ if (slot.kind === 'loop') {
841
+ const { match } = slot
842
+ const needsBracket = !isLast || hadVariableRange
843
+ let anchorVar: string
844
+ let skipArg = ''
845
+ if (needsBracket) {
846
+ anchorVar = requestChild(elVar, domIndex)
847
+ html += '<!--k[--><!--k]-->'
848
+ addRangeSlot(elVar, domIndex + 1)
849
+ domIndex += 2
850
+ }
851
+ else {
852
+ anchorVar = 'null'
853
+ if (domIndex > 0)
854
+ skipArg = `, ${domIndex}`
855
+ }
623
856
 
624
- if (child.type === 'JSXElement') {
625
- const childTag = jsxTagName(child.openingElement.name)
626
- if (isComponentTag(childTag)) {
627
- const anchorVar = isLast ? 'null' : requestChild(elVar, domIndex)
628
- if (!isLast) {
629
- html += '<!---->'
630
- domIndex++
631
- }
632
- const callCode = compileComponentCall(child, scopeRewrites)
633
- ops.push(`${use('insert')}(${elVar}, () => ${callCode}, ${anchorVar});`)
857
+ const eachCode = compileExpression(match.target, scopeRewrites)
858
+ const params = match.params
859
+ const firstParam = params[0]
860
+ const secondParam = params[1]
861
+ const idxParam = secondParam?.type === 'Identifier'
862
+ ? secondParam.name
863
+ : secondParam?.type === 'AssignmentPattern' && secondParam.left.type === 'Identifier'
864
+ ? secondParam.left.name
865
+ : undefined
866
+
867
+ // Fast path: a const array literal (e.g. `NAV.map(...)`) renders once through `eachStatic`.
868
+ const isStaticArr = match.target.type === 'Identifier' && staticArrays.has(match.target.name) && !scopeRewrites.has(match.target.name)
869
+ if (isStaticArr) {
870
+ const rawParams = params.map(p => code.slice(p.start, p.end)).join(', ')
871
+ const shadowed = withoutBindings(scopeRewrites, params)
872
+ const rowBody = match.isJsxBody ? compileRootJsx(match.body as JSXElement | JSXFragment, shadowed) : compileExpression(match.body, shadowed)
873
+ ops.push(`${use('eachStatic')}(${elVar}, ${anchorVar}, ${eachCode}, (${rawParams}) => ${rowBody}${skipArg});`)
874
+ hadVariableRange = true
875
+ continue
876
+ }
877
+
878
+ const keyAst = match.isJsxBody ? extractKeyExpr(match.body) : extractBlockKeyExpr(match.body as BlockStatement)
879
+ const rowSig = freshVar('_r')
880
+ const idxSig = idxParam !== undefined ? freshVar('_i') : undefined
881
+ const rowRewrites = new Map(scopeRewrites)
882
+ const keyRewrites = withoutBindings(scopeRewrites, params)
883
+ let keyFn: string
884
+
885
+ if (firstParam !== undefined && firstParam.type !== 'Identifier') {
886
+ const patCode = code.slice(firstParam.start, firstParam.end)
887
+ keyFn = keyAst !== undefined
888
+ ? `(${patCode}${idxParam ? `, ${idxParam}` : ''}) => ${compileExpression(keyAst, keyRewrites)}`
889
+ : `(_item) => _item`
890
+ for (const [name, read] of patternReads(firstParam, `${rowSig}.value`, scopeRewrites))
891
+ rowRewrites.set(name, read)
634
892
  }
635
893
  else {
636
- // Check if child element (or any descendant) needs bindings before allocating a var
637
- const subOpsBefore = ops.length
638
- const subWalkBefore = walkPlan.length
639
- const placeholderVar = `__SUB_${varCounter++}`
640
- const subHtml = buildHtml(child, placeholderVar)
641
- const needed = ops.length > subOpsBefore || walkPlan.length > subWalkBefore
642
- if (needed) {
643
- const realVar = requestChild(elVar, domIndex)
644
- for (let k = subOpsBefore; k < ops.length; k++)
645
- ops[k] = ops[k]!.replaceAll(placeholderVar, realVar)
646
- for (let k = subWalkBefore; k < walkPlan.length; k++) {
647
- if (walkPlan[k]!.parentVar === placeholderVar)
648
- walkPlan[k]!.parentVar = realVar
649
- }
650
- const prefix = `${placeholderVar}:`
651
- for (const slot of [...dynamicTextSlots]) {
652
- if (slot.startsWith(prefix)) {
653
- dynamicTextSlots.delete(slot)
654
- dynamicTextSlots.add(`${realVar}:${slot.slice(prefix.length)}`)
655
- }
656
- }
657
- }
658
- html += subHtml
659
- domIndex++
894
+ const itemParam = firstParam?.type === 'Identifier' ? firstParam.name : '_item'
895
+ keyFn = keyAst !== undefined
896
+ ? `(${itemParam}${idxParam ? `, ${idxParam}` : ''}) => ${compileExpression(keyAst, keyRewrites)}`
897
+ : `(${itemParam}) => ${itemParam}`
898
+ rowRewrites.set(itemParam, `${rowSig}.value`)
660
899
  }
900
+ if (idxParam !== undefined && idxSig !== undefined)
901
+ rowRewrites.set(idxParam, `${idxSig}.value`)
902
+
903
+ const rowBody = match.isJsxBody ? compileRootJsx(match.body as JSXElement | JSXFragment, rowRewrites) : compileExpression(match.body, rowRewrites)
904
+ const rowParams = idxSig !== undefined ? `${rowSig}, ${idxSig}` : rowSig
905
+ ops.push(`${use('loop')}(${elVar}, ${anchorVar}, () => ${eachCode}, ${keyFn}, (${rowParams}) => ${rowBody}${skipArg});`)
906
+ hadVariableRange = true
661
907
  continue
662
908
  }
663
909
 
664
- if (child.type === 'JSXFragment') {
665
- const anchorVar = isLast ? 'null' : requestChild(elVar, domIndex)
666
- if (!isLast) {
667
- html += '<!---->'
668
- domIndex++
910
+ if (slot.kind === 'and-show') {
911
+ let anchorVar = 'null'
912
+ if (hasSiblings) {
913
+ anchorVar = requestChild(elVar, domIndex)
914
+ html += '<!--k[--><!--k]-->'
915
+ addRangeSlot(elVar, domIndex + 1)
916
+ domIndex += 2
669
917
  }
670
- const fragCode = compileRootJsx(child, scopeRewrites)
671
- ops.push(`${use('insert')}(${elVar}, () => ${fragCode}, ${anchorVar});`)
918
+ const whenCode = compileExpression(slot.expr.left, scopeRewrites)
919
+ const trueCode = compileRootJsx(slot.right, scopeRewrites)
920
+ ops.push(`${use('show')}(${elVar}, ${anchorVar}, () => ${whenCode}, () => ${trueCode});`)
921
+ hadVariableRange = true
672
922
  continue
673
923
  }
674
924
 
675
- if (child.type === 'JSXExpressionContainer') {
676
- const expr = child.expression as AstNode
677
-
678
- // Case 1: Keyed `.map((item, idx?) => <jsx> | { ... return <jsx> })` → `__loop(...)`
679
- if (
680
- expr.type === 'CallExpression'
681
- && expr.callee?.type === 'MemberExpression'
682
- && !expr.callee.computed
683
- && expr.callee.property?.name === 'map'
684
- && expr.arguments?.length === 1
685
- ) {
686
- const cb = expr.arguments[0] as AstNode
687
- const cbBody = cb.body?.type === 'ParenthesizedExpression' ? cb.body.expression : cb.body
688
- const isJsxBody = cbBody?.type === 'JSXElement' || cbBody?.type === 'JSXFragment'
689
- const isBlockJsxBody = cbBody?.type === 'BlockStatement' && hasJsxDescendant(cbBody)
690
- if (
691
- (cb.type === 'ArrowFunctionExpression' || cb.type === 'FunctionExpression')
692
- && (isJsxBody || isBlockJsxBody)
693
- ) {
694
- const loopSkip = domIndex
695
- const anchorVar = isLast ? 'null' : requestChild(elVar, domIndex)
696
- if (!isLast) {
697
- html += '<!---->'
698
- domIndex++
699
- }
700
-
701
- const eachCode = compileExpression(expr.callee.object, scopeRewrites)
702
- const params = cb.params as AstNode[]
703
- const firstParam = params[0]
704
- const idxParam = params[1]?.type === 'Identifier' ? params[1].name as string : undefined
705
- const skipArg = loopSkip > 0 ? `, ${loopSkip}` : ''
706
-
707
- // Fast path: provably static constant array (e.g. `NAV.map(...)`) -> lightweight `eachStatic` (0 bytes of LIS reconciler!)
708
- const isStaticArr = expr.callee.object.type === 'Identifier' && !scopeRewrites.has(expr.callee.object.name as string)
709
- if (isStaticArr) {
710
- const rawParams = params.map(p => code.slice(p.start, p.end)).join(', ')
711
- const shadowed = new Map(scopeRewrites)
712
- for (const p of params) {
713
- const names = new Set<string>()
714
- collectPatternNames(p, names)
715
- for (const n of names)
716
- shadowed.delete(n)
717
- }
718
- const rowBody = isJsxBody ? compileRootJsx(cbBody, shadowed) : compileExpression(cbBody, shadowed)
719
- ops.push(`${use('eachStatic')}(${elVar}, ${anchorVar}, ${eachCode}, (${rawParams}) => ${rowBody}${skipArg});`)
720
- continue
721
- }
722
-
723
- const keyAst = isJsxBody ? extractKeyExpr(cbBody) : extractBlockKeyExpr(cbBody)
724
-
725
- const rowSig = freshVar('_r')
726
- const idxSig = idxParam !== undefined ? freshVar('_i') : undefined
727
- const rowRewrites = new Map(scopeRewrites)
728
- let keyFn: string
729
-
730
- const keyRewrites = new Map(scopeRewrites)
731
- for (const p of params) {
732
- const names = new Set<string>()
733
- collectPatternNames(p, names)
734
- for (const n of names)
735
- keyRewrites.delete(n)
736
- }
737
-
738
- if (firstParam?.type === 'ObjectPattern') {
739
- const patCode = code.slice(firstParam.start, firstParam.end)
740
- keyFn = keyAst !== undefined
741
- ? `(${patCode}${idxParam ? `, ${idxParam}` : ''}) => ${compileExpression(keyAst, keyRewrites)}`
742
- : `(_item) => _item`
743
- for (const prop of firstParam.properties as AstNode[]) {
744
- if (prop.type === 'Property' && prop.key?.type === 'Identifier') {
745
- const propKey = prop.key.name as string
746
- if (prop.value.type === 'Identifier') {
747
- rowRewrites.set(prop.value.name as string, `${rowSig}.value.${propKey}`)
748
- }
749
- else if (prop.value.type === 'AssignmentPattern' && prop.value.left?.type === 'Identifier') {
750
- const defCode = code.slice(prop.value.right.start, prop.value.right.end)
751
- rowRewrites.set(prop.value.left.name as string, `(${rowSig}.value.${propKey} === undefined ? ${defCode} : ${rowSig}.value.${propKey})`)
752
- }
753
- }
754
- }
755
- }
756
- else {
757
- const itemParam = firstParam?.type === 'Identifier' ? firstParam.name as string : '_item'
758
- keyFn = keyAst !== undefined
759
- ? `(${itemParam}${idxParam ? `, ${idxParam}` : ''}) => ${compileExpression(keyAst, keyRewrites)}`
760
- : `(${itemParam}) => ${itemParam}`
761
- rowRewrites.set(itemParam, `${rowSig}.value`)
762
- }
763
- if (idxParam !== undefined && idxSig !== undefined)
764
- rowRewrites.set(idxParam, `${idxSig}.value`)
765
-
766
- const rowBody = isJsxBody ? compileRootJsx(cbBody, rowRewrites) : compileExpression(cbBody, rowRewrites)
767
- const rowParams = idxSig !== undefined ? `${rowSig}, ${idxSig}` : rowSig
768
- ops.push(`${use('loop')}(${elVar}, ${anchorVar}, () => ${eachCode}, ${keyFn}, (${rowParams}) => ${rowBody}${skipArg});`)
769
- continue
770
- }
925
+ if (slot.kind === 'ternary-show') {
926
+ let anchorVar = 'null'
927
+ if (hasSiblings) {
928
+ anchorVar = requestChild(elVar, domIndex)
929
+ html += '<!--k[--><!--k]-->'
930
+ addRangeSlot(elVar, domIndex + 1)
931
+ domIndex += 2
771
932
  }
933
+ const whenCode = compileExpression(slot.expr.test, scopeRewrites)
934
+ const trueCode = isJsxNode(slot.cons)
935
+ ? compileRootJsx(slot.cons, scopeRewrites)
936
+ : compileExpression(slot.cons, scopeRewrites)
937
+ const falseCode = isJsxNode(slot.alt)
938
+ ? compileRootJsx(slot.alt, scopeRewrites)
939
+ : compileExpression(slot.alt, scopeRewrites)
940
+ ops.push(`${use('show')}(${elVar}, ${anchorVar}, () => ${whenCode}, () => ${trueCode}, () => ${falseCode});`)
941
+ hadVariableRange = true
942
+ continue
943
+ }
772
944
 
773
- // Case 2: `cond && <jsx>` → `__show(...)`
774
- if (expr.type === 'LogicalExpression' && expr.operator === '&&') {
775
- const right = unwrapParens(expr.right)
776
- if (right.type === 'JSXElement' || right.type === 'JSXFragment') {
777
- const anchorVar = isLast ? 'null' : requestChild(elVar, domIndex)
778
- if (!isLast) {
779
- html += '<!---->'
780
- domIndex++
781
- }
782
- const whenCode = compileExpression(expr.left, scopeRewrites)
783
- const trueCode = compileRootJsx(right, scopeRewrites)
784
- ops.push(`${use('show')}(${elVar}, ${anchorVar}, () => ${whenCode}, () => ${trueCode});`)
785
- continue
786
- }
945
+ // Generic expression slot
946
+ const exprCode = compileExpression(slot.expr, scopeRewrites)
947
+ if (isNodeCapableExpr(slot.expr)) {
948
+ if (!hasSiblings) {
949
+ ops.push(`${use('insert')}(${elVar}, () => ${exprCode}, null, null);`)
787
950
  }
788
-
789
- // Case 3: `cond ? <a/> : <b/>` → `__show(...)`
790
- if (expr.type === 'ConditionalExpression') {
791
- const consNode = unwrapParens(expr.consequent)
792
- const altNode = unwrapParens(expr.alternate)
793
- if (consNode.type === 'JSXElement' || consNode.type === 'JSXFragment' || altNode.type === 'JSXElement' || altNode.type === 'JSXFragment') {
794
- const anchorVar = isLast ? 'null' : requestChild(elVar, domIndex)
795
- if (!isLast) {
796
- html += '<!---->'
797
- domIndex++
798
- }
799
- const whenCode = compileExpression(expr.test, scopeRewrites)
800
- const trueCode = consNode.type === 'JSXElement' || consNode.type === 'JSXFragment'
801
- ? compileRootJsx(consNode, scopeRewrites)
802
- : compileExpression(consNode, scopeRewrites)
803
- const falseCode = altNode.type === 'JSXElement' || altNode.type === 'JSXFragment'
804
- ? compileRootJsx(altNode, scopeRewrites)
805
- : compileExpression(altNode, scopeRewrites)
806
- ops.push(`${use('show')}(${elVar}, ${anchorVar}, () => ${whenCode}, () => ${trueCode}, () => ${falseCode});`)
807
- continue
808
- }
951
+ else if (isLast) {
952
+ const startVar = requestChild(elVar, domIndex)
953
+ html += '<!--k[-->'
954
+ domIndex++
955
+ ops.push(`${use('insert')}(${elVar}, () => ${exprCode}, null, ${startVar});`)
809
956
  }
810
-
811
- // Case 4: Dynamic children slot / Node insertion (`{children}`, `{props.children}`, or any expression containing JSX)
812
- const isChildrenExpr = (expr.type === 'Identifier' && expr.name === 'children')
813
- || (expr.type === 'MemberExpression' && !expr.computed && expr.property?.name === 'children')
814
- const exprCode = compileExpression(expr, scopeRewrites)
815
- if (isChildrenExpr || hasJsxDescendant(expr)) {
816
- const anchorVar = isLast ? 'null' : requestChild(elVar, domIndex)
817
- if (!isLast) {
818
- html += '<!---->'
819
- domIndex++
820
- }
821
- ops.push(`${use('insert')}(${elVar}, () => ${exprCode}, ${anchorVar});`)
822
- continue
957
+ else {
958
+ const startVar = requestChild(elVar, domIndex)
959
+ const endVar = requestChild(elVar, domIndex + 1)
960
+ html += '<!--k[--><!--k]-->'
961
+ addRangeSlot(elVar, domIndex + 1)
962
+ domIndex += 2
963
+ ops.push(`${use('insert')}(${elVar}, () => ${exprCode}, ${endVar}, ${startVar});`)
823
964
  }
824
-
825
- // Case 5: Dynamic text / expression binding
826
- if (meaningful.length === 1) {
827
- // Sole dynamic child: 0 comment markers!
828
- html += ' '
829
- domIndex++
830
- const txtVar = freshVar('_txt')
831
- ops.push(`const ${txtVar} = ${use('firstText')}(${elVar});`)
832
- ops.push(`${use('effect')}(() => ${use('setText')}(${txtVar}, ${exprCode}));`)
965
+ hadVariableRange = true
966
+ }
967
+ else if (!hasSiblings) {
968
+ // Sole dynamic child: 0 comment markers!
969
+ html += ' '
970
+ domIndex++
971
+ const txtVar = freshVar('_txt')
972
+ ops.push(`const ${txtVar} = ${use('firstText')}(${elVar});`)
973
+ ops.push(`${use('effect')}(() => ${use('setText')}(${txtVar}, ${exprCode}));`)
974
+ }
975
+ else {
976
+ // Sibling dynamic text: open comment + optional text (+ closing comment if followed by more siblings)
977
+ const markerVar = requestChild(elVar, domIndex)
978
+ if (isLast) {
979
+ html += '<!----> '
980
+ domIndex += 2
833
981
  }
834
982
  else {
835
- // Sibling dynamic child: open comment + optional text (+ closing comment if followed by more siblings)
836
- const markerVar = requestChild(elVar, domIndex)
837
- if (isLast) {
838
- html += '<!----> '
839
- domIndex += 2
840
- }
841
- else {
842
- html += '<!----> <!---->'
843
- dynamicTextSlots.add(`${elVar}:${domIndex + 1}`)
844
- domIndex += 3
845
- }
846
- const txtVar = freshVar('_txt')
847
- ops.push(`const ${txtVar} = ${use('textAfter')}(${markerVar});`)
848
- ops.push(`${use('effect')}(() => ${use('setText')}(${txtVar}, ${exprCode}));`)
983
+ html += '<!----> <!---->'
984
+ addTextSlot(elVar, domIndex + 1)
985
+ domIndex += 3
849
986
  }
987
+ const txtVar = freshVar('_txt')
988
+ ops.push(`const ${txtVar} = ${use('textAfter')}(${markerVar});`)
989
+ ops.push(`${use('effect')}(() => ${use('setText')}(${txtVar}, ${exprCode}));`)
990
+ }
850
991
  }
851
992
  }
993
+ finally {
994
+ svgDepth = prevSvgDepth
995
+ }
852
996
 
853
997
  html += `</${tag}>`
854
998
  return html
@@ -857,9 +1001,10 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
857
1001
  const html = buildHtml(rootEl, rootVar)
858
1002
  const rootTag = jsxTagName(rootEl.openingElement.name)
859
1003
  const tmplName = `_t${templates.length}`
860
- templates.push({ name: tmplName, html, isSvg: SVG_CHILD_TAGS.has(rootTag) })
1004
+ const isSvg = svgDepth > 0 ? rootTag !== 'svg' : SVG_CHILD_TAGS.has(rootTag)
1005
+ templates.push({ name: tmplName, html, isSvg })
861
1006
 
862
- // Emit efficient parent->child sibling walks grouped by parentVar (breadth-first / parent-first order)
1007
+ // Emit parent->child sibling walks grouped by parentVar (breadth-first / parent-first order)
863
1008
  const walkStmts: string[] = []
864
1009
  const byParent = new Map<string, { index: number, varName: string }[]>()
865
1010
  for (const item of walkPlan) {
@@ -871,7 +1016,6 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
871
1016
  arr.push({ index: item.index, varName: item.varName })
872
1017
  }
873
1018
 
874
- // Emit walks in topological order (root first)
875
1019
  const emittedParents = new Set<string>([rootVar])
876
1020
  const queue = [rootVar]
877
1021
  while (queue.length > 0) {
@@ -881,6 +1025,8 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
881
1025
  continue
882
1026
  list.sort((a, b) => a.index - b.index)
883
1027
 
1028
+ const tSlots = textSlotsByParent.get(pVar)
1029
+ const rSlots = rangeSlotsByParent.get(pVar)
884
1030
  let prevVar: string | undefined
885
1031
  let prevIdx = -1
886
1032
  for (const { index, varName } of list) {
@@ -895,10 +1041,14 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
895
1041
  pos = prevIdx
896
1042
  }
897
1043
  while (pos < index) {
898
- if (dynamicTextSlots.has(`${pVar}:${pos + 1}`) && pos + 2 <= index) {
1044
+ if (tSlots?.has(pos + 1) && pos + 2 <= index) {
899
1045
  expr = `${use('skipText')}(${expr})`
900
1046
  pos += 2
901
1047
  }
1048
+ else if (rSlots?.has(pos + 1)) {
1049
+ expr = `${use('skipRange')}(${expr})`
1050
+ pos += 1
1051
+ }
902
1052
  else {
903
1053
  expr = `${expr}.nextSibling`
904
1054
  pos += 1
@@ -920,20 +1070,35 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
920
1070
  return `(() => { const ${rootVar} = ${tmplName}(); ${walkStmts.join(' ')} ${ops.join(' ')} return ${rootVar}; })()`
921
1071
  }
922
1072
 
923
- function compileRootJsx(node: AstNode, scopeRewrites: ReadonlyMap<string, string>): string {
1073
+ function compileRootJsx(node: JSXElement | JSXFragment, scopeRewrites: ReadonlyMap<string, string>): string {
924
1074
  if (node.type === 'JSXFragment') {
925
- const meaningful = filterChildren(node.children as AstNode[])
1075
+ const meaningful = filterMeaningfulChildren(node.children)
926
1076
  if (meaningful.length === 0)
927
1077
  return 'null'
928
- if (meaningful.length === 1 && meaningful[0]!.type === 'JSXElement')
929
- return compileRootJsx(meaningful[0]!, scopeRewrites)
1078
+ if (meaningful.length === 1) {
1079
+ const only = meaningful[0]!
1080
+ if (isJsxNode(only))
1081
+ return compileRootJsx(only, scopeRewrites)
1082
+ if (only.type === 'JSXText')
1083
+ return `document.createTextNode(${JSON.stringify(decodeHtmlEntities(cleanJsxText(only.value)))})`
1084
+ if (only.type === 'JSXExpressionContainer' && only.expression.type !== 'JSXEmptyExpression') {
1085
+ const exprCode = compileExpression(only.expression, scopeRewrites)
1086
+ return `(() => { const _f = document.createDocumentFragment(); ${use('insert')}(_f, () => (${exprCode}), null, null); return _f; })()`
1087
+ }
1088
+ }
930
1089
 
931
1090
  const items = meaningful.map((child) => {
932
- if (child.type === 'JSXElement' || child.type === 'JSXFragment')
1091
+ if (isJsxNode(child))
933
1092
  return compileRootJsx(child, scopeRewrites)
934
1093
  if (child.type === 'JSXText')
935
- return `document.createTextNode(${JSON.stringify(cleanJsxText(child.value as string))})`
936
- return `document.createTextNode(String(${compileExpression(child.expression, scopeRewrites)} ?? ""))`
1094
+ return `document.createTextNode(${JSON.stringify(decodeHtmlEntities(cleanJsxText(child.value)))})`
1095
+ if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression') {
1096
+ const exprCode = compileExpression(child.expression, scopeRewrites)
1097
+ if (isNodeCapableExpr(child.expression))
1098
+ return `(() => { const _f = document.createDocumentFragment(); ${use('insert')}(_f, () => (${exprCode}), null, null); return _f; })()`
1099
+ return `(() => { const _t = document.createTextNode(""); ${use('effect')}(() => ${use('setText')}(_t, (${exprCode}))); return _t; })()`
1100
+ }
1101
+ return 'document.createTextNode("")'
937
1102
  })
938
1103
  return `${use('frag')}(${items.join(', ')})`
939
1104
  }
@@ -945,98 +1110,126 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
945
1110
  return compileElementTree(node, scopeRewrites)
946
1111
  }
947
1112
 
948
- // Handle component functions with destructured props + JSX compilation
949
- function processFunction(fn: AstNode): void {
950
- let fnHasJsx = false
951
- walk(fn.body, (child) => {
952
- if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
953
- fnHasJsx = true
954
- return false
955
- }
1113
+ function extractDestructuredParam(firstParam: ParamPattern | undefined): {
1114
+ pattern: ObjectPattern
1115
+ defaultExpr: Node | undefined
1116
+ replaceStart: number
1117
+ replaceEnd: number
1118
+ typeAnn: string
1119
+ } | undefined {
1120
+ if (firstParam === undefined)
956
1121
  return undefined
957
- })
958
- if (!fnHasJsx)
959
- return
960
-
961
- const propRewrites = new Map<string, string>()
962
- const firstParam = (fn.params as AstNode[])[0]
963
- if (firstParam !== undefined && firstParam.type === 'ObjectPattern') {
964
- const pVar = '__p'
1122
+ if (firstParam.type === 'ObjectPattern') {
965
1123
  const typeAnn = firstParam.typeAnnotation ? code.slice(firstParam.typeAnnotation.start, firstParam.typeAnnotation.end) : ''
966
- editor.replace(firstParam.start, firstParam.end, `${pVar}${typeAnn}`)
1124
+ return { pattern: firstParam, defaultExpr: undefined, replaceStart: firstParam.start, replaceEnd: firstParam.end, typeAnn }
1125
+ }
1126
+ if (firstParam.type === 'AssignmentPattern' && firstParam.left.type === 'ObjectPattern') {
1127
+ const pat = firstParam.left
1128
+ const typeAnn = pat.typeAnnotation ? code.slice(pat.typeAnnotation.start, pat.typeAnnotation.end) : ''
1129
+ return { pattern: pat, defaultExpr: firstParam.right, replaceStart: firstParam.start, replaceEnd: firstParam.end, typeAnn }
1130
+ }
1131
+ return undefined
1132
+ }
967
1133
 
968
- const extractedKeys: string[] = []
969
- let restName: string | undefined
1134
+ function computePropRewrites(
1135
+ destructured: { pattern: ObjectPattern, defaultExpr: Node | undefined },
1136
+ pVar: string,
1137
+ outerRewrites: ReadonlyMap<string, string>,
1138
+ ): Map<string, string> {
1139
+ const propRewrites = new Map(outerRewrites)
1140
+ for (const [name, read] of patternReads(destructured.pattern, pVar, outerRewrites))
1141
+ propRewrites.set(name, read)
1142
+
1143
+ const extractedKeys: string[] = []
1144
+ let restName: string | undefined
1145
+ let staticKeys = true
1146
+ for (const prop of destructured.pattern.properties) {
1147
+ if (prop.type === 'RestElement')
1148
+ restName = prop.argument.type === 'Identifier' ? prop.argument.name : undefined
1149
+ else if (!prop.computed && prop.key.type === 'Identifier')
1150
+ extractedKeys.push(prop.key.name)
1151
+ else if (!prop.computed && prop.key.type === 'Literal' && typeof prop.key.value === 'string')
1152
+ extractedKeys.push(prop.key.value)
1153
+ else
1154
+ staticKeys = false
1155
+ }
1156
+ if (restName !== undefined && staticKeys)
1157
+ propRewrites.set(restName, `${use('omit')}(${pVar}, ${JSON.stringify(extractedKeys)})`)
1158
+ return propRewrites
1159
+ }
970
1160
 
971
- for (const prop of firstParam.properties as AstNode[]) {
972
- if (prop.type === 'Property' && prop.key?.type === 'Identifier') {
973
- const propKey = prop.key.name as string
974
- extractedKeys.push(propKey)
975
- if (prop.value.type === 'Identifier') {
976
- propRewrites.set(prop.value.name as string, `${pVar}.${propKey}`)
977
- }
978
- else if (prop.value.type === 'AssignmentPattern' && prop.value.left?.type === 'Identifier') {
979
- const defCode = code.slice(prop.value.right.start, prop.value.right.end)
980
- propRewrites.set(prop.value.left.name as string, `(${pVar}.${propKey} === undefined ? ${defCode} : ${pVar}.${propKey})`)
981
- }
982
- }
983
- else if (prop.type === 'RestElement' && prop.argument?.type === 'Identifier') {
984
- restName = prop.argument.name as string
985
- }
986
- }
1161
+ function buildCompiledFunction(fn: ArrowFunctionExpression | OxcFunction, outerRewrites: ReadonlyMap<string, string>): string {
1162
+ const fnEditor = new SourceEditor(code.slice(fn.start, fn.end))
1163
+ const offset = fn.start
1164
+ const destructured = extractDestructuredParam(fn.params[0])
1165
+ const pVar = freshVar('__p')
1166
+ let propRewrites = new Map(outerRewrites)
1167
+
1168
+ if (destructured !== undefined) {
1169
+ const defSuffix = destructured.defaultExpr !== undefined
1170
+ ? ` = ${compileExpression(destructured.defaultExpr, outerRewrites)}`
1171
+ : ''
1172
+ fnEditor.replace(destructured.replaceStart - offset, destructured.replaceEnd - offset, `${pVar}${destructured.typeAnn}${defSuffix}`)
1173
+ propRewrites = computePropRewrites(destructured, pVar, outerRewrites)
1174
+ }
1175
+
1176
+ if (fn.body !== null)
1177
+ fnEditor.replace(fn.body.start - offset, fn.body.end - offset, compileExpression(fn.body, propRewrites))
1178
+ return fnEditor.toString()
1179
+ }
987
1180
 
988
- if (restName !== undefined)
989
- propRewrites.set(restName, `${use('omit')}(${pVar}, ${JSON.stringify(extractedKeys)})`)
1181
+ // Handle top-level component functions with destructured props + JSX compilation
1182
+ function processFunction(fn: ArrowFunctionExpression | OxcFunction): void {
1183
+ if (fn.body === null || !containsJsx(fn.body))
1184
+ return
1185
+
1186
+ const destructured = extractDestructuredParam(fn.params[0])
1187
+ let propRewrites = new Map<string, string>()
1188
+
1189
+ if (destructured !== undefined) {
1190
+ const pVar = '__p'
1191
+ const defSuffix = destructured.defaultExpr !== undefined
1192
+ ? ` = ${compileExpression(destructured.defaultExpr, new Map())}`
1193
+ : ''
1194
+ editor.replace(destructured.replaceStart, destructured.replaceEnd, `${pVar}${destructured.typeAnn}${defSuffix}`)
1195
+ propRewrites = computePropRewrites(destructured, pVar, new Map())
990
1196
  }
991
1197
 
992
- // Rewrite prop reads in non-JSX statements of the function body, and compile JSX roots with propRewrites
993
- if (propRewrites.size > 0 && fn.body?.type === 'BlockStatement') {
1198
+ if (propRewrites.size > 0 && fn.body.type === 'BlockStatement') {
994
1199
  const shadowed = new Set<string>()
995
- for (const stmt of fn.body.body as AstNode[]) {
996
- let stmtHasJsx = false
997
- walk(stmt, (child) => {
998
- if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
999
- stmtHasJsx = true
1000
- return false
1001
- }
1002
- return undefined
1003
- })
1200
+ for (const stmt of fn.body.body) {
1201
+ if (stmt.type === 'FunctionDeclaration' && stmt.id !== null)
1202
+ shadowed.add(stmt.id.name)
1203
+ else if (stmt.type === 'ClassDeclaration' && stmt.id !== null)
1204
+ shadowed.add(stmt.id.name)
1205
+ }
1206
+ for (const stmt of fn.body.body) {
1004
1207
  const active = new Map<string, string>()
1005
1208
  for (const [k, v] of propRewrites) {
1006
1209
  if (!shadowed.has(k))
1007
1210
  active.set(k, v)
1008
1211
  }
1009
- // A statement holding JSX also reads props around it (`if (on) return <b/>`): compile both in one pass.
1010
- if (stmtHasJsx)
1212
+ if (active.size > 0 || containsJsx(stmt))
1011
1213
  editor.replace(stmt.start, stmt.end, compileExpression(stmt, active))
1012
- else if (active.size > 0)
1013
- editor.replace(stmt.start, stmt.end, rewriteFreeIdentifiers(code, stmt, active))
1014
1214
  if (stmt.type === 'VariableDeclaration') {
1015
- for (const d of stmt.declarations as AstNode[])
1215
+ for (const d of stmt.declarations)
1016
1216
  collectPatternNames(d.id, shadowed)
1017
1217
  }
1018
1218
  }
1019
1219
  }
1020
- else if (propRewrites.size > 0) {
1021
- editor.replace(fn.body.start, fn.body.end, compileExpression(fn.body, propRewrites))
1022
- }
1023
1220
  else {
1024
- walk(fn.body, (child) => {
1025
- if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
1026
- editor.replace(child.start, child.end, compileRootJsx(child, propRewrites))
1027
- return false
1028
- }
1029
- return undefined
1030
- })
1221
+ editor.replace(fn.body.start, fn.body.end, compileExpression(fn.body, propRewrites))
1031
1222
  }
1032
1223
  }
1033
1224
 
1034
1225
  walk(program, (node) => {
1226
+ if (loadNodes.has(node))
1227
+ return false
1035
1228
  if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
1036
1229
  processFunction(node)
1037
1230
  return false
1038
1231
  }
1039
- if (node.type === 'JSXElement' || node.type === 'JSXFragment') {
1232
+ if (isJsxNode(node)) {
1040
1233
  editor.replace(node.start, node.end, compileRootJsx(node, new Map()))
1041
1234
  return false
1042
1235
  }
@@ -1052,7 +1245,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
1052
1245
 
1053
1246
  if (used.size > 0) {
1054
1247
  const hasLoop = used.delete('loop')
1055
- const EXTRA_HELPERS = ['insert', 'omit', 'setInnerHtml', 'show', 'spread']
1248
+ const EXTRA_HELPERS = ['insert', 'mergeProps', 'omit', 'setInnerHtml', 'show', 'spread']
1056
1249
  const usedExtras: string[] = []
1057
1250
  for (const name of EXTRA_HELPERS) {
1058
1251
  if (used.delete(name))