prunelle 0.1.1 → 0.7.2

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 (177) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +89 -41
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +238 -0
  15. package/src/build/files.ts +15 -0
  16. package/src/build/first-load.ts +85 -14
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +225 -122
  19. package/src/build/island-promote.ts +311 -0
  20. package/src/build/islands.ts +14 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +3 -6
  23. package/src/build/plugin-host.ts +115 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +177 -39
  26. package/src/build/reach.ts +200 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +48 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +112 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +636 -0
  36. package/src/cli/check-imports.ts +31 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +101 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -22
  49. package/src/compiler/analyze.ts +87 -54
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability-private.ts +566 -0
  52. package/src/compiler/cacheability.ts +335 -0
  53. package/src/compiler/compliance-eco.ts +71 -0
  54. package/src/compiler/compliance-rgaa.ts +614 -0
  55. package/src/compiler/compliance-urls.ts +148 -0
  56. package/src/compiler/compliance.ts +407 -352
  57. package/src/compiler/data-keys.ts +199 -192
  58. package/src/compiler/dev-source.ts +87 -0
  59. package/src/compiler/dom-attrs.ts +138 -65
  60. package/src/compiler/dom.ts +517 -442
  61. package/src/compiler/expr-context.ts +260 -81
  62. package/src/compiler/foreign-imports.ts +88 -0
  63. package/src/compiler/mistakes.ts +23 -2
  64. package/src/compiler/props-body.ts +60 -0
  65. package/src/compiler/props.ts +87 -36
  66. package/src/compiler/scope.ts +400 -333
  67. package/src/compiler/server-only.ts +190 -151
  68. package/src/compiler/shared.ts +42 -14
  69. package/src/compiler/signal-reads.ts +6 -2
  70. package/src/compiler/spread-handlers.ts +295 -0
  71. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  72. package/src/compiler/ssr.ts +220 -89
  73. package/src/context.ts +34 -0
  74. package/src/dev/error-log.ts +177 -0
  75. package/src/dev/host-check.ts +32 -0
  76. package/src/dev/index.ts +94 -34
  77. package/src/dev/open-editor.ts +228 -0
  78. package/src/dev/protocol.ts +3 -0
  79. package/src/dev/reload.ts +5 -3
  80. package/src/dev/supervisor.ts +50 -25
  81. package/src/dev/watchers.ts +74 -13
  82. package/src/dom/action.ts +47 -21
  83. package/src/dom/attrs.ts +15 -3
  84. package/src/dom/extras.ts +57 -40
  85. package/src/dom/index.ts +54 -14
  86. package/src/dom/island.ts +102 -68
  87. package/src/dom/loop.ts +66 -32
  88. package/src/eco/declaration.ts +328 -0
  89. package/src/eco/index.ts +69 -0
  90. package/src/index.ts +2 -2
  91. package/src/jsx-runtime.ts +2 -2
  92. package/src/plugins/config.ts +18 -12
  93. package/src/plugins/context.ts +44 -1
  94. package/src/plugins/index.ts +2 -2
  95. package/src/plugins/load.ts +30 -10
  96. package/src/plugins/order.ts +38 -1
  97. package/src/plugins/public.ts +6 -3
  98. package/src/plugins/services.ts +84 -0
  99. package/src/plugins/types.ts +51 -2
  100. package/src/reactivity/graph.ts +10 -0
  101. package/src/reactivity/index.ts +24 -16
  102. package/src/reactivity/selector.ts +31 -4
  103. package/src/reactivity/store.ts +64 -20
  104. package/src/server/action-flash.ts +158 -0
  105. package/src/server/action-protect.ts +199 -0
  106. package/src/server/action-registry.ts +1 -1
  107. package/src/server/action.ts +188 -152
  108. package/src/server/app-secret.ts +63 -0
  109. package/src/server/assets.ts +34 -2
  110. package/src/server/compress.ts +96 -10
  111. package/src/server/consent.ts +59 -22
  112. package/src/server/cookies.ts +16 -2
  113. package/src/server/document.ts +25 -10
  114. package/src/server/env.ts +14 -0
  115. package/src/server/errors.ts +308 -65
  116. package/src/server/form-schema.ts +337 -0
  117. package/src/server/health.ts +275 -0
  118. package/src/server/http.ts +186 -39
  119. package/src/server/index.ts +272 -273
  120. package/src/server/loader.ts +15 -2
  121. package/src/server/page.ts +15 -0
  122. package/src/server/param-matchers.ts +112 -0
  123. package/src/server/plugin-host.ts +125 -88
  124. package/src/server/public.ts +6 -5
  125. package/src/server/rate-limit.ts +102 -36
  126. package/src/server/request-body.ts +1 -1
  127. package/src/server/route-cache.ts +541 -0
  128. package/src/server/route-table.ts +356 -11
  129. package/src/server/router.ts +125 -40
  130. package/src/server/routing.ts +112 -63
  131. package/src/server/sanitize-html.ts +309 -0
  132. package/src/server/security.ts +279 -52
  133. package/src/server/serve-handlers.ts +31 -7
  134. package/src/server/standard-schema.ts +17 -0
  135. package/src/server/start.ts +60 -16
  136. package/src/server/static-dir.ts +91 -12
  137. package/src/server/stream.ts +68 -27
  138. package/src/ssr/consent-banner.ts +58 -0
  139. package/src/ssr/context.ts +106 -8
  140. package/src/ssr/index.ts +151 -4
  141. package/src/ssr/navigation.ts +2 -2
  142. package/src/ssr/region.ts +40 -19
  143. package/src/style.ts +64 -1
  144. package/src/test/browser.ts +28 -13
  145. package/src/test/index.ts +97 -12
  146. package/src/ts-plugin/diagnostics.ts +505 -0
  147. package/src/ts-plugin/fixes.ts +364 -0
  148. package/src/ts-plugin/index.ts +194 -0
  149. package/templates/_shared/AGENTS.md +2 -2
  150. package/templates/_shared/gitignore +5 -0
  151. package/templates/_shared/mcp.json +11 -0
  152. package/templates/_shared/src/routes/legal.tsx +15 -1
  153. package/templates/_shared/tsconfig.json +5 -0
  154. package/templates/app/.env.example +4 -0
  155. package/templates/app/package.json +2 -1
  156. package/templates/app/prunelle.config.ts +2 -0
  157. package/templates/app/src/auth.ts +4 -6
  158. package/templates/app/src/mail.ts +4 -0
  159. package/templates/app/src/routes/_layout.tsx +9 -1
  160. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  161. package/templates/app/src/routes/login.tsx +49 -30
  162. package/templates/app/src/routes/privacy.tsx +25 -0
  163. package/templates/app/src/styles/app.css +8 -1
  164. package/templates/app/tests/app.test.ts +44 -3
  165. package/templates/blog/package.json +1 -1
  166. package/templates/blog/prunelle.config.ts +1 -1
  167. package/templates/blog/src/routes/_layout.tsx +6 -1
  168. package/templates/blog/src/routes/index.tsx +5 -1
  169. package/templates/blog/src/styles/app.css +6 -1
  170. package/templates/fullstack/package.json +1 -1
  171. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  172. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  173. package/templates/fullstack/src/styles/app.css +11 -1
  174. package/templates/minimal/package.json +1 -1
  175. package/templates/minimal/src/routes/_layout.tsx +4 -0
  176. package/templates/minimal/src/styles/app.css +11 -1
  177. package/ts-plugin.cjs +4277 -0
@@ -12,25 +12,26 @@ import type {
12
12
  } from 'oxc-parser'
13
13
  import type { ModuleAnalysis } from './analyze'
14
14
  import type { WalkItem } from './emit'
15
- import type { HydrationMarker, MapCallMatch } from './shared'
15
+ import type { ExprContext, HydrationMarker, MapCallMatch } from './shared'
16
16
 
17
- import { analyzeModule, loadDeclarations, parseTsx } from './analyze'
17
+ import { analyzeModule, getExprContext, loadDeclarations, parseTsx } from './analyze'
18
18
  import { walk } from './ast'
19
+ import { createDevSourceAttr } from './dev-source'
19
20
  import { collectStaticStyleNames, compileElementAttributes, compileRawTextChildren, formatSetTextOp, resolveComponentCallee } from './dom-attrs'
20
21
  import { emitWalkStatements, moduleHeader, SVG_CHILD_TAGS } from './emit'
21
22
  import { SourceEditor } from './patch'
22
- import { createPropCompiler, isStaticPropExpr, withoutBindings } from './props'
23
+ import { compileParamList, createPropCompiler, isStaticPropExpr, withoutBindings } from './props'
23
24
  import { extractBlockKeyExpr, extractKeyExpr, literalArrayConsts, rewriteFreeIdentifiers } from './scope'
24
25
  import {
25
26
  cleanJsxText,
26
27
  containsJsx,
27
- createExprContext,
28
28
  decodeHtmlEntities,
29
29
  escapeStaticText,
30
30
  filterMeaningfulChildren,
31
31
  isComponentTag,
32
32
  isJsxNode,
33
33
  jsxTagName,
34
+ matchJsxMapCall,
34
35
  planChildSlots,
35
36
  RAW_TEXT_ELEMENTS,
36
37
  resolvePrunelleTag,
@@ -39,6 +40,8 @@ import {
39
40
 
40
41
  export interface CompileDomOptions {
41
42
  analysis?: ModuleAnalysis | undefined
43
+ /** Project root for dev-only `data-pru-src="file:line:col"` attributes; omit in production. */
44
+ devSourceRoot?: string | undefined
42
45
  }
43
46
 
44
47
  export interface CompileDomResult {
@@ -46,502 +49,574 @@ export interface CompileDomResult {
46
49
  analysis: ModuleAnalysis
47
50
  }
48
51
 
49
- export function compileDom(filename: string, code: string, options: CompileDomOptions = {}): CompileDomResult {
50
- const program = options.analysis?.program ?? parseTsx(filename, code)
51
- const analysis = options.analysis ?? analyzeModule(filename, code, program)
52
+ const SUB_VAR_RE = /__SUB_\d+/g
52
53
 
53
- if (!analysis.hasJsx && !analysis.hasLoadExport)
54
- return { code, analysis }
55
-
56
- const staticArrays = literalArrayConsts(program)
57
- const loadNodes = new Set<Node>(loadDeclarations(program))
58
- const jsxNodes = analysis.jsxNodes
59
- const exprContext = createExprContext(program, jsxNodes)
60
- const staticStyleNames = collectStaticStyleNames(program, exprContext.primitiveVars)
54
+ interface DomCompilerCtx {
55
+ code: string
56
+ analysis: ModuleAnalysis
57
+ jsxNodes: WeakSet<Node>
58
+ exprContext: ExprContext
59
+ staticArrays: ReadonlySet<string>
60
+ staticStyleNames: ReadonlySet<string>
61
+ devSrc: (el: JSXElement, tag: string) => string
62
+ templates: { name: string, html: string, isSvg?: boolean }[]
63
+ delegatedEvents: Set<string>
64
+ svgDepth: number
65
+ use: (name: string) => string
66
+ freshVar: (prefix?: string) => string
67
+ nextVarId: () => number
68
+ compileExpression: (node: Node, scopeRewrites: ReadonlyMap<string, string>) => string
69
+ compileLoopRow: ReturnType<typeof createPropCompiler>['compileLoopRow']
70
+ withPrelude: ReturnType<typeof createPropCompiler>['withPrelude']
71
+ }
61
72
 
62
- const editor = new SourceEditor(code)
63
- const used = new Set<string>()
64
- const templates: { name: string, html: string, isSvg?: boolean }[] = []
65
- const delegatedEvents = new Set<string>()
66
- let varCounter = 0
67
- // Tracks whether the current JSX tree is enclosed by `<svg>` (reset inside `<foreignObject>`).
68
- let svgDepth = 0
73
+ interface ElementTreeState {
74
+ ops: string[]
75
+ walkPlan: WalkItem[]
76
+ childRefs: Map<string, string>
77
+ textSlotsByParent: Map<string, Set<number>>
78
+ rangeSlotsByParent: Map<string, Set<number>>
79
+ varAliases: Map<string, string>
80
+ }
69
81
 
70
- const use = (name: string): string => {
71
- used.add(name)
72
- return `__${name}`
82
+ function addSlot(map: Map<string, Set<number>>, parentVar: string, idx: number): void {
83
+ let s = map.get(parentVar)
84
+ if (s === undefined) {
85
+ s = new Set()
86
+ map.set(parentVar, s)
73
87
  }
74
- const freshVar = (prefix = '_e'): string => `${prefix}${varCounter++}`
88
+ s.add(idx)
89
+ }
75
90
 
76
- // Client builds keep the `load` binding, so every export form stays valid, and drop its server-only code.
77
- for (const node of loadNodes) {
78
- if (node.type === 'FunctionDeclaration' && node.id !== null)
79
- editor.replace(node.start, node.end, `const ${node.id.name} = undefined`)
80
- else
81
- editor.replace(node.start, node.end, 'undefined')
91
+ function remapSlotMap(map: Map<string, Set<number>>, aliases: ReadonlyMap<string, string>): void {
92
+ if (map.size === 0)
93
+ return
94
+ const moved: [string, string, Set<number>][] = []
95
+ for (const [k, v] of map) {
96
+ const target = aliases.get(k)
97
+ if (target !== undefined)
98
+ moved.push([k, target, v])
82
99
  }
83
-
84
- const { compileLoopRow, withPrelude, extractDestructuredParam, buildCompiledFunction, processFunction } = createPropCompiler({
85
- code,
86
- editor,
87
- jsxNodes,
88
- use,
89
- freshVar,
90
- compileExpression: (node, rewrites) => compileExpression(node, rewrites),
91
- })
92
-
93
- function compileNestedComponent(fn: ArrowFunctionExpression | OxcFunction, outerRewrites: ReadonlyMap<string, string>): string | undefined {
94
- if (!containsJsx(fn.body, jsxNodes))
95
- return undefined
96
- const firstParam = fn.params[0]
97
- const destructured = extractDestructuredParam(firstParam)
98
- if (destructured === undefined)
99
- return undefined
100
- return buildCompiledFunction(fn, outerRewrites)
100
+ for (const [from, to, v] of moved) {
101
+ map.delete(from)
102
+ map.set(to, v)
101
103
  }
104
+ }
102
105
 
103
- function compileExpression(node: Node, scopeRewrites: ReadonlyMap<string, string>): string {
104
- return rewriteFreeIdentifiers(code, node, scopeRewrites, jsxNodes, compileRootJsx, compileNestedComponent)
106
+ function resolveElementAliases(tree: ElementTreeState): void {
107
+ const { varAliases, walkPlan, ops, textSlotsByParent, rangeSlotsByParent } = tree
108
+ if (varAliases.size === 0)
109
+ return
110
+ for (let i = 0; i < walkPlan.length; i++) {
111
+ const item = walkPlan[i]!
112
+ const mapped = varAliases.get(item.parentVar)
113
+ if (mapped !== undefined)
114
+ item.parentVar = mapped
115
+ }
116
+ remapSlotMap(textSlotsByParent, varAliases)
117
+ remapSlotMap(rangeSlotsByParent, varAliases)
118
+ const replaceFn = (match: string): string => varAliases.get(match) ?? match
119
+ for (let i = 0; i < ops.length; i++) {
120
+ const op = ops[i]!
121
+ if (op.includes('__SUB_'))
122
+ ops[i] = op.replace(SUB_VAR_RE, replaceFn)
105
123
  }
124
+ }
106
125
 
107
- function compileComponentCall(node: JSXElement, scopeRewrites: ReadonlyMap<string, string>): string {
108
- const tag = jsxTagName(node.openingElement.name)
109
- // `Catch` itself stays server-side, so the `prunelle` an island imports does not pull the DOM runtime into every client build.
110
- const callee = resolvePrunelleTag(tag, analysis.imports) === 'Catch' ? use('catchBoundary') : resolveComponentCallee(tag, scopeRewrites)
111
- const attrs = node.openingElement.attributes
112
- const hasSpread = attrs.some(a => a.type === 'JSXSpreadAttribute')
113
- const segments: string[] = []
114
- let currentObj: string[] = []
115
-
116
- const flushObj = () => {
117
- if (currentObj.length > 0) {
118
- segments.push(`{ ${currentObj.join(', ')} }`)
119
- currentObj = []
120
- }
121
- }
126
+ function requestTreeChild(ctx: DomCompilerCtx, tree: ElementTreeState, parentVar: string, index: number): string {
127
+ const key = `${parentVar}:${index}`
128
+ const existing = tree.childRefs.get(key)
129
+ if (existing !== undefined)
130
+ return existing
131
+ const v = ctx.freshVar('_e')
132
+ tree.childRefs.set(key, v)
133
+ tree.walkPlan.push({ parentVar, index, varName: v })
134
+ return v
135
+ }
122
136
 
123
- for (const attr of attrs) {
124
- if (attr.type === 'JSXSpreadAttribute') {
125
- flushObj()
126
- segments.push(`(${compileExpression(attr.argument, scopeRewrites)})`)
127
- continue
128
- }
129
- const name = jsxTagName(attr.name)
130
- if (name === 'key' || name === '$hydrate')
131
- continue
137
+ function compileComponentCall(ctx: DomCompilerCtx, node: JSXElement, scopeRewrites: ReadonlyMap<string, string>): string {
138
+ const tag = jsxTagName(node.openingElement.name)
139
+ // `Catch` itself stays server-side, so the `prunelle` an island imports does not pull the DOM runtime into every client build.
140
+ const callee = resolvePrunelleTag(tag, ctx.analysis.imports) === 'Catch' ? ctx.use('catchBoundary') : resolveComponentCallee(tag, scopeRewrites)
141
+ const attrs = node.openingElement.attributes
142
+ const hasSpread = attrs.some(a => a.type === 'JSXSpreadAttribute')
143
+ const segments: string[] = []
144
+ let currentObj: string[] = []
145
+
146
+ const flushObj = () => {
147
+ if (currentObj.length > 0) {
148
+ segments.push(`{ ${currentObj.join(', ')} }`)
149
+ currentObj = []
150
+ }
151
+ }
132
152
 
133
- const propKey = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name)
134
- if (attr.value === null) {
135
- currentObj.push(`${propKey}: true`)
136
- }
137
- else if (attr.value.type === 'Literal') {
138
- currentObj.push(`${propKey}: ${JSON.stringify(attr.value.value)}`)
139
- }
140
- else if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
141
- const expr = attr.value.expression
142
- const exprCode = compileExpression(expr, scopeRewrites)
143
- // Reactive getter for dynamic expressions; plain property for identifiers, constant literals/collections, and inline functions.
144
- if (isStaticPropExpr(expr, scopeRewrites))
145
- currentObj.push(`${propKey}: ${exprCode}`)
146
- else
147
- currentObj.push(`get ${propKey}() { return ${exprCode} }`)
148
- }
153
+ for (const attr of attrs) {
154
+ if (attr.type === 'JSXSpreadAttribute') {
155
+ flushObj()
156
+ segments.push(`(${ctx.compileExpression(attr.argument, scopeRewrites)})`)
157
+ continue
149
158
  }
159
+ const name = jsxTagName(attr.name)
160
+ if (name === 'key' || name === '$hydrate')
161
+ continue
150
162
 
151
- const meaningful = filterMeaningfulChildren(node.children)
152
- if (meaningful.length === 1) {
153
- const child = meaningful[0]!
154
- if (child.type === 'JSXText')
155
- currentObj.push(`children: ${JSON.stringify(decodeHtmlEntities(cleanJsxText(child.value)))}`)
156
- else if (isJsxNode(child))
157
- currentObj.push(`get children() { return ${compileRootJsx(child, scopeRewrites)} }`)
158
- else if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression')
159
- currentObj.push(`get children() { return ${compileExpression(child.expression, scopeRewrites)} }`)
163
+ const propKey = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name)
164
+ if (attr.value === null) {
165
+ currentObj.push(`${propKey}: true`)
166
+ }
167
+ else if (attr.value.type === 'Literal') {
168
+ currentObj.push(`${propKey}: ${JSON.stringify(attr.value.value)}`)
160
169
  }
161
- else if (meaningful.length > 1) {
162
- currentObj.push(`get children() { return ${compileFragmentChildren(node.children, scopeRewrites)} }`)
170
+ else if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
171
+ const expr = attr.value.expression
172
+ const exprCode = ctx.compileExpression(expr, scopeRewrites)
173
+ // Reactive getter for dynamic expressions; plain property for identifiers, constant literals/collections, and inline functions.
174
+ if (isStaticPropExpr(expr, scopeRewrites))
175
+ currentObj.push(`${propKey}: ${exprCode}`)
176
+ else
177
+ currentObj.push(`get ${propKey}() { return ${exprCode} }`)
163
178
  }
179
+ }
164
180
 
165
- flushObj()
181
+ const meaningful = filterMeaningfulChildren(node.children)
182
+ if (meaningful.length === 1) {
183
+ const child = meaningful[0]!
184
+ if (child.type === 'JSXText')
185
+ currentObj.push(`children: ${JSON.stringify(decodeHtmlEntities(cleanJsxText(child.value)))}`)
186
+ else if (isJsxNode(child))
187
+ currentObj.push(`get children() { return ${compileRootJsx(ctx, child, scopeRewrites)} }`)
188
+ else if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression')
189
+ currentObj.push(`get children() { return ${matchJsxMapCall(child.expression, ctx.jsxNodes) !== undefined ? compileFragmentChildren(ctx, node.children, scopeRewrites) : ctx.compileExpression(child.expression, scopeRewrites)} }`)
190
+ }
191
+ else if (meaningful.length > 1) {
192
+ currentObj.push(`get children() { return ${compileFragmentChildren(ctx, node.children, scopeRewrites)} }`)
193
+ }
194
+
195
+ flushObj()
166
196
 
167
- if (!hasSpread) {
168
- const propsObj = segments[0] ?? '{}'
169
- return `${callee}(${propsObj})`
197
+ if (!hasSpread)
198
+ return `${callee}(${segments[0] ?? '{}'})`
199
+ if (segments.length === 1)
200
+ return `${callee}(${segments[0]!})`
201
+ return `${callee}(${ctx.use('mergeProps')}(${segments.join(', ')}))`
202
+ }
203
+
204
+ /** Compiles a `.map()` JSX loop into either `__eachStatic` or keyed `__loop`, reusable for both element children and fragments. */
205
+ function compileLoopCall(
206
+ ctx: DomCompilerCtx,
207
+ match: MapCallMatch,
208
+ scopeRewrites: ReadonlyMap<string, string>,
209
+ skipArg = '',
210
+ ): { isStatic: boolean, call: (p: string, a: string) => string } {
211
+ const eachCode = ctx.compileExpression(match.target, scopeRewrites)
212
+ const params = match.params
213
+ const firstParam = params[0]
214
+ const secondParam = params[1]
215
+ const idxParam = secondParam?.type === 'Identifier'
216
+ ? secondParam.name
217
+ : secondParam?.type === 'AssignmentPattern' && secondParam.left.type === 'Identifier'
218
+ ? secondParam.left.name
219
+ : undefined
220
+
221
+ // Fast path: a const array literal (e.g. `NAV.map(...)`) renders once through `eachStatic`.
222
+ const isStaticArr = match.target.type === 'Identifier' && ctx.staticArrays.has(match.target.name) && !scopeRewrites.has(match.target.name)
223
+ if (isStaticArr) {
224
+ const rawParams = compileParamList(ctx.code, params, scopeRewrites, ctx.compileExpression)
225
+ const shadowed = withoutBindings(scopeRewrites, params)
226
+ const rowBody = match.isJsxBody ? compileRootJsx(ctx, match.body as JSXElement | JSXFragment, shadowed) : ctx.compileExpression(match.body, shadowed)
227
+ return {
228
+ isStatic: true,
229
+ call: (p, a) => `${ctx.use('eachStatic')}(${p}, ${a}, ${eachCode}, (${rawParams}) => ${rowBody}${skipArg})`,
170
230
  }
171
- if (segments.length === 1)
172
- return `${callee}(${segments[0]!})`
173
- return `${callee}(${use('mergeProps')}(${segments.join(', ')}))`
174
231
  }
175
232
 
176
- /** Compiles a `.map()` JSX loop into either `__eachStatic` or keyed `__loop`, reusable for both element children and fragments. */
177
- function compileLoopCall(
178
- match: MapCallMatch,
179
- scopeRewrites: ReadonlyMap<string, string>,
180
- parentExpr: string,
181
- anchorExpr: string,
182
- skipArg = '',
183
- ): { isStatic: boolean, call: (p: string, a: string) => string } {
184
- const eachCode = compileExpression(match.target, scopeRewrites)
185
- const params = match.params
186
- const firstParam = params[0]
187
- const secondParam = params[1]
188
- const idxParam = secondParam?.type === 'Identifier'
189
- ? secondParam.name
190
- : secondParam?.type === 'AssignmentPattern' && secondParam.left.type === 'Identifier'
191
- ? secondParam.left.name
192
- : undefined
193
-
194
- // Fast path: a const array literal (e.g. `NAV.map(...)`) renders once through `eachStatic`.
195
- const isStaticArr = match.target.type === 'Identifier' && staticArrays.has(match.target.name) && !scopeRewrites.has(match.target.name)
196
- if (isStaticArr) {
197
- const rawParams = params.map(p => code.slice(p.start, p.end)).join(', ')
198
- const shadowed = withoutBindings(scopeRewrites, params)
199
- const rowBody = match.isJsxBody ? compileRootJsx(match.body as JSXElement | JSXFragment, shadowed) : compileExpression(match.body, shadowed)
200
- return {
201
- isStatic: true,
202
- call: (p, a) => `${use('eachStatic')}(${p}, ${a}, ${eachCode}, (${rawParams}) => ${rowBody}${skipArg})`,
203
- }
204
- }
233
+ const keyAst = match.isJsxBody ? extractKeyExpr(match.body) : extractBlockKeyExpr(match.body as BlockStatement)
234
+ const rowSig = ctx.freshVar('_r')
235
+ const idxSig = idxParam !== undefined ? ctx.freshVar('_i') : undefined
236
+ const keyRewrites = withoutBindings(scopeRewrites, params)
237
+ const { keyFn, rowRewrites, prelude } = ctx.compileLoopRow({ firstParam, idxParam, keyAst, rowSig, scopeRewrites, keyRewrites })
238
+ if (idxParam !== undefined && idxSig !== undefined)
239
+ rowRewrites.set(idxParam, `${idxSig}.value`)
240
+
241
+ const rawRowBody = match.isJsxBody ? compileRootJsx(ctx, match.body as JSXElement | JSXFragment, rowRewrites) : ctx.compileExpression(match.body, rowRewrites)
242
+ const rowBody = ctx.withPrelude(rawRowBody, match.body, prelude)
243
+ const rowParams = idxSig !== undefined ? `${rowSig}, ${idxSig}` : rowSig
244
+ return {
245
+ isStatic: false,
246
+ call: (p, a) => `${ctx.use('loop')}(${p}, ${a}, () => ${eachCode}, ${keyFn}, (${rowParams}) => ${rowBody}${skipArg})`,
247
+ }
248
+ }
205
249
 
206
- const keyAst = match.isJsxBody ? extractKeyExpr(match.body) : extractBlockKeyExpr(match.body as BlockStatement)
207
- const rowSig = freshVar('_r')
208
- const idxSig = idxParam !== undefined ? freshVar('_i') : undefined
209
- const keyRewrites = withoutBindings(scopeRewrites, params)
210
- const { keyFn, rowRewrites, prelude } = compileLoopRow({ firstParam, idxParam, keyAst, rowSig, scopeRewrites, keyRewrites })
211
- if (idxParam !== undefined && idxSig !== undefined)
212
- rowRewrites.set(idxParam, `${idxSig}.value`)
213
-
214
- const rawRowBody = match.isJsxBody ? compileRootJsx(match.body as JSXElement | JSXFragment, rowRewrites) : compileExpression(match.body, rowRewrites)
215
- const rowBody = withPrelude(rawRowBody, match.body, prelude)
216
- const rowParams = idxSig !== undefined ? `${rowSig}, ${idxSig}` : rowSig
217
- void parentExpr
218
- void anchorExpr
219
- return {
220
- isStatic: false,
221
- call: (p, a) => `${use('loop')}(${p}, ${a}, () => ${eachCode}, ${keyFn}, (${rowParams}) => ${rowBody}${skipArg})`,
250
+ function emitTextSlotOp(
251
+ ctx: DomCompilerCtx,
252
+ tree: ElementTreeState,
253
+ elVar: string,
254
+ domIndex: number,
255
+ marker: HydrationMarker,
256
+ open: string,
257
+ close: string,
258
+ exprCode: string,
259
+ expr: Node,
260
+ scopeRewrites: ReadonlyMap<string, string>,
261
+ ): { html: string, nextIndex: number } {
262
+ const txtVar = ctx.freshVar('_txt')
263
+ let html: string
264
+ let nextIndex: number
265
+ if (marker === 'none') {
266
+ html = ' '
267
+ nextIndex = domIndex + 1
268
+ tree.ops.push(`const ${txtVar} = ${ctx.use('firstText')}(${elVar});`)
269
+ }
270
+ else {
271
+ const markerVar = requestTreeChild(ctx, tree, elVar, domIndex)
272
+ if (marker === 'text') {
273
+ html = `${open} ${close}`
274
+ addSlot(tree.textSlotsByParent, elVar, domIndex + 1)
275
+ nextIndex = domIndex + 3
222
276
  }
277
+ else {
278
+ html = `${open} `
279
+ nextIndex = domIndex + 2
280
+ }
281
+ tree.ops.push(`const ${txtVar} = ${ctx.use('textAfter')}(${markerVar});`)
223
282
  }
283
+ tree.ops.push(formatSetTextOp(txtVar, exprCode, expr, scopeRewrites, ctx.use))
284
+ return { html, nextIndex }
285
+ }
286
+
287
+ function buildElementHtml(
288
+ ctx: DomCompilerCtx,
289
+ tree: ElementTreeState,
290
+ el: JSXElement,
291
+ elVar: string,
292
+ scopeRewrites: ReadonlyMap<string, string>,
293
+ ): string {
294
+ const tag = jsxTagName(el.openingElement.name)
295
+ const rawTextTag = RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined
296
+ const postChildOps: string[] = []
297
+ const attrHtml = compileElementAttributes({
298
+ el,
299
+ tag,
300
+ elVar,
301
+ scopeRewrites,
302
+ staticStyleNames: ctx.staticStyleNames,
303
+ ops: tree.ops,
304
+ postChildOps,
305
+ delegatedEvents: ctx.delegatedEvents,
306
+ use: ctx.use,
307
+ freshVar: ctx.freshVar,
308
+ compileExpression: ctx.compileExpression,
309
+ })
224
310
 
225
- function compileElementTree(rootEl: JSXElement, scopeRewrites: ReadonlyMap<string, string>): string {
226
- const ops: string[] = []
227
- const rootVar = freshVar('_e')
228
- const childRefs = new Map<string, string>() // "parentVar:index" -> varName
311
+ let html = `<${tag}${ctx.devSrc(el, tag)}${attrHtml}>`
312
+ if (VOID_ELEMENTS.has(tag))
313
+ return html
229
314
 
230
- const walkPlan: WalkItem[] = []
231
- const textSlotsByParent = new Map<string, Set<number>>()
232
- const rangeSlotsByParent = new Map<string, Set<number>>()
315
+ if (rawTextTag !== undefined) {
316
+ html += compileRawTextChildren(el, rawTextTag, elVar, scopeRewrites, tree.ops, ctx.use, ctx.compileExpression)
317
+ return `${html}</${tag}>`
318
+ }
233
319
 
234
- const addSlot = (map: Map<string, Set<number>>, parentVar: string, idx: number) => {
235
- let s = map.get(parentVar)
236
- if (s === undefined) {
237
- s = new Set()
238
- map.set(parentVar, s)
239
- }
240
- s.add(idx)
320
+ const planned = planChildSlots(el.children, { jsxNodes: ctx.jsxNodes, exprContext: ctx.exprContext })
321
+ let domIndex = 0
322
+ let prevWasStaticText = false
323
+
324
+ const claimRangeAnchor = (marker: HydrationMarker, open: string, close: string): string => {
325
+ if (marker !== 'range')
326
+ return 'null'
327
+ const v = requestTreeChild(ctx, tree, elVar, domIndex)
328
+ html += open + close
329
+ addSlot(tree.rangeSlotsByParent, elVar, domIndex + 1)
330
+ domIndex += 2
331
+ return v
332
+ }
333
+
334
+ const emitInsert = (valueCode: string, marker: HydrationMarker, open: string, close: string): void => {
335
+ if (marker === 'none') {
336
+ tree.ops.push(`${ctx.use('insert')}(${elVar}, () => ${valueCode}, null, null);`)
241
337
  }
242
- const renameSlot = (map: Map<string, Set<number>>, from: string, to: string) => {
243
- const slots = map.get(from)
244
- if (slots !== undefined) {
245
- map.delete(from)
246
- map.set(to, slots)
247
- }
338
+ else if (marker === 'range-open') {
339
+ const startVar = requestTreeChild(ctx, tree, elVar, domIndex)
340
+ html += open
341
+ domIndex++
342
+ tree.ops.push(`${ctx.use('insert')}(${elVar}, () => ${valueCode}, null, ${startVar});`)
248
343
  }
249
-
250
- function requestChild(parentVar: string, index: number): string {
251
- const key = `${parentVar}:${index}`
252
- const existing = childRefs.get(key)
253
- if (existing !== undefined)
254
- return existing
255
- const v = freshVar('_e')
256
- childRefs.set(key, v)
257
- walkPlan.push({ parentVar, index, varName: v })
258
- return v
344
+ else {
345
+ const startVar = requestTreeChild(ctx, tree, elVar, domIndex)
346
+ const endVar = requestTreeChild(ctx, tree, elVar, domIndex + 1)
347
+ html += open + close
348
+ addSlot(tree.rangeSlotsByParent, elVar, domIndex + 1)
349
+ domIndex += 2
350
+ tree.ops.push(`${ctx.use('insert')}(${elVar}, () => ${valueCode}, ${endVar}, ${startVar});`)
259
351
  }
352
+ }
353
+
354
+ const prevSvgDepth = ctx.svgDepth
355
+ if (tag === 'svg')
356
+ ctx.svgDepth = 1
357
+ else if (tag === 'foreignObject' || tag === 'math')
358
+ ctx.svgDepth = 0
260
359
 
261
- function buildHtml(el: JSXElement, elVar: string): string {
262
- const tag = jsxTagName(el.openingElement.name)
263
- const rawTextTag = RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined
264
- const postChildOps: string[] = []
265
- const attrHtml = compileElementAttributes({
266
- el,
267
- tag,
268
- elVar,
269
- scopeRewrites,
270
- staticStyleNames,
271
- ops,
272
- postChildOps,
273
- delegatedEvents,
274
- use,
275
- freshVar,
276
- compileExpression,
277
- })
278
-
279
- let html = `<${tag}${attrHtml}>`
280
- if (VOID_ELEMENTS.has(tag))
281
- return html
282
-
283
- if (rawTextTag !== undefined) {
284
- html += compileRawTextChildren(el, rawTextTag, elVar, scopeRewrites, ops, use, compileExpression)
285
- html += `</${tag}>`
286
- return html
360
+ try {
361
+ for (const { slot, marker, open, close, nodeCapable } of planned) {
362
+ if (slot.kind === 'static-text') {
363
+ html += escapeStaticText(slot.fromLiteral ? slot.text : decodeHtmlEntities(slot.text))
364
+ if (!prevWasStaticText) {
365
+ domIndex++
366
+ prevWasStaticText = true
367
+ }
368
+ continue
287
369
  }
288
370
 
289
- const planned = planChildSlots(el.children, { jsxNodes, exprContext })
290
- let domIndex = 0
291
- let prevWasStaticText = false
292
-
293
- const claimRangeAnchor = (marker: HydrationMarker, open: string, close: string): string => {
294
- if (marker !== 'range')
295
- return 'null'
296
- const v = requestChild(elVar, domIndex)
297
- html += open + close
298
- addSlot(rangeSlotsByParent, elVar, domIndex + 1)
299
- domIndex += 2
300
- return v
371
+ prevWasStaticText = false
372
+
373
+ if (slot.kind === 'element') {
374
+ const subOpsBefore = tree.ops.length
375
+ const subWalkBefore = tree.walkPlan.length
376
+ const placeholderVar = `__SUB_${ctx.nextVarId()}`
377
+ const subHtml = buildElementHtml(ctx, tree, slot.node, placeholderVar, scopeRewrites)
378
+ if (tree.ops.length > subOpsBefore || tree.walkPlan.length > subWalkBefore)
379
+ tree.varAliases.set(placeholderVar, requestTreeChild(ctx, tree, elVar, domIndex))
380
+ html += subHtml
381
+ domIndex++
382
+ continue
301
383
  }
302
384
 
303
- const emitInsert = (valueCode: string, marker: HydrationMarker, open: string, close: string): void => {
304
- if (marker === 'none') {
305
- ops.push(`${use('insert')}(${elVar}, () => ${valueCode}, null, null);`)
306
- }
307
- else if (marker === 'range-open') {
308
- const startVar = requestChild(elVar, domIndex)
309
- html += open
310
- domIndex++
311
- ops.push(`${use('insert')}(${elVar}, () => ${valueCode}, null, ${startVar});`)
312
- }
313
- else {
314
- const startVar = requestChild(elVar, domIndex)
315
- const endVar = requestChild(elVar, domIndex + 1)
316
- html += open + close
317
- addSlot(rangeSlotsByParent, elVar, domIndex + 1)
318
- domIndex += 2
319
- ops.push(`${use('insert')}(${elVar}, () => ${valueCode}, ${endVar}, ${startVar});`)
320
- }
385
+ if (slot.kind === 'component' || slot.kind === 'fragment') {
386
+ const renderedCode = slot.kind === 'component'
387
+ ? compileComponentCall(ctx, slot.node, scopeRewrites)
388
+ : compileRootJsx(ctx, slot.node, scopeRewrites)
389
+ emitInsert(renderedCode, marker, open, close)
390
+ continue
321
391
  }
322
392
 
323
- const prevSvgDepth = svgDepth
324
- if (tag === 'svg')
325
- svgDepth = 1
326
- else if (tag === 'foreignObject')
327
- svgDepth = 0
328
-
329
- try {
330
- for (const { slot, marker, open, close, nodeCapable } of planned) {
331
- if (slot.kind === 'static-text') {
332
- html += escapeStaticText(slot.fromLiteral ? slot.text : decodeHtmlEntities(slot.text))
333
- if (!prevWasStaticText) {
334
- domIndex++
335
- prevWasStaticText = true
336
- }
337
- continue
338
- }
339
-
340
- prevWasStaticText = false
341
-
342
- if (slot.kind === 'element') {
343
- const subOpsBefore = ops.length
344
- const subWalkBefore = walkPlan.length
345
- const placeholderVar = `__SUB_${varCounter++}`
346
- const subHtml = buildHtml(slot.node, placeholderVar)
347
- const needed = ops.length > subOpsBefore || walkPlan.length > subWalkBefore
348
- if (needed) {
349
- const realVar = requestChild(elVar, domIndex)
350
- for (let k = subOpsBefore; k < ops.length; k++)
351
- ops[k] = ops[k]!.replaceAll(placeholderVar, realVar)
352
- for (let k = subWalkBefore; k < walkPlan.length; k++) {
353
- if (walkPlan[k]!.parentVar === placeholderVar)
354
- walkPlan[k]!.parentVar = realVar
355
- }
356
- renameSlot(textSlotsByParent, placeholderVar, realVar)
357
- renameSlot(rangeSlotsByParent, placeholderVar, realVar)
358
- }
359
- html += subHtml
360
- domIndex++
361
- continue
362
- }
363
-
364
- if (slot.kind === 'component' || slot.kind === 'fragment') {
365
- const renderedCode = slot.kind === 'component'
366
- ? compileComponentCall(slot.node, scopeRewrites)
367
- : compileRootJsx(slot.node, scopeRewrites)
368
- emitInsert(renderedCode, marker, open, close)
369
- continue
370
- }
371
-
372
- if (slot.kind === 'loop') {
373
- const anchorVar = claimRangeAnchor(marker, open, close)
374
- const skipArg = marker === 'none' && domIndex > 0 ? `, ${domIndex}` : ''
375
- const compiled = compileLoopCall(slot.match, scopeRewrites, elVar, anchorVar, skipArg)
376
- ops.push(`${compiled.call(elVar, anchorVar)};`)
377
- continue
378
- }
379
-
380
- if (slot.kind === 'and-show') {
381
- const anchorVar = claimRangeAnchor(marker, open, close)
382
- const whenCode = compileExpression(slot.expr.left, scopeRewrites)
383
- const trueCode = compileRootJsx(slot.right, scopeRewrites)
384
- ops.push(`${use('show')}(${elVar}, ${anchorVar}, () => ${whenCode}, () => ${trueCode});`)
385
- continue
386
- }
387
-
388
- if (slot.kind === 'ternary-show') {
389
- const anchorVar = claimRangeAnchor(marker, open, close)
390
- const whenCode = compileExpression(slot.expr.test, scopeRewrites)
391
- const trueCode = isJsxNode(slot.cons)
392
- ? compileRootJsx(slot.cons, scopeRewrites)
393
- : compileExpression(slot.cons, scopeRewrites)
394
- const falseCode = isJsxNode(slot.alt)
395
- ? compileRootJsx(slot.alt, scopeRewrites)
396
- : compileExpression(slot.alt, scopeRewrites)
397
- ops.push(`${use('show')}(${elVar}, ${anchorVar}, () => ${whenCode}, () => ${trueCode}, () => ${falseCode});`)
398
- continue
399
- }
400
-
401
- // Generic expression slot
402
- const exprCode = compileExpression(slot.expr, scopeRewrites)
403
- if (nodeCapable) {
404
- emitInsert(exprCode, marker, open, close)
405
- }
406
- else {
407
- const txtVar = freshVar('_txt')
408
- if (marker === 'none') {
409
- html += ' '
410
- domIndex++
411
- ops.push(`const ${txtVar} = ${use('firstText')}(${elVar});`)
412
- }
413
- else {
414
- const markerVar = requestChild(elVar, domIndex)
415
- if (marker === 'text') {
416
- html += `${open} ${close}`
417
- addSlot(textSlotsByParent, elVar, domIndex + 1)
418
- domIndex += 3
419
- }
420
- else {
421
- html += `${open} `
422
- domIndex += 2
423
- }
424
- ops.push(`const ${txtVar} = ${use('textAfter')}(${markerVar});`)
425
- }
426
- ops.push(formatSetTextOp(txtVar, exprCode, slot.expr, scopeRewrites, use))
427
- }
428
- }
393
+ if (slot.kind === 'loop') {
394
+ const anchorVar = claimRangeAnchor(marker, open, close)
395
+ const skipArg = marker === 'none' && domIndex > 0 ? `, ${domIndex}` : ''
396
+ const compiled = compileLoopCall(ctx, slot.match, scopeRewrites, skipArg)
397
+ tree.ops.push(`${compiled.call(elVar, anchorVar)};`)
398
+ continue
429
399
  }
430
- finally {
431
- svgDepth = prevSvgDepth
400
+
401
+ if (slot.kind === 'and-show') {
402
+ const anchorVar = claimRangeAnchor(marker, open, close)
403
+ const whenCode = ctx.compileExpression(slot.expr.left, scopeRewrites)
404
+ const trueCode = compileRootJsx(ctx, slot.right, scopeRewrites)
405
+ tree.ops.push(`${ctx.use('show')}(${elVar}, ${anchorVar}, () => ${whenCode}, () => ${trueCode});`)
406
+ continue
432
407
  }
433
408
 
434
- for (const op of postChildOps)
435
- ops.push(op)
409
+ if (slot.kind === 'ternary-show') {
410
+ const anchorVar = claimRangeAnchor(marker, open, close)
411
+ const whenCode = ctx.compileExpression(slot.expr.test, scopeRewrites)
412
+ const trueCode = isJsxNode(slot.cons) ? compileRootJsx(ctx, slot.cons, scopeRewrites) : ctx.compileExpression(slot.cons, scopeRewrites)
413
+ const falseCode = isJsxNode(slot.alt) ? compileRootJsx(ctx, slot.alt, scopeRewrites) : ctx.compileExpression(slot.alt, scopeRewrites)
414
+ tree.ops.push(`${ctx.use('show')}(${elVar}, ${anchorVar}, () => ${whenCode}, () => ${trueCode}, () => ${falseCode});`)
415
+ continue
416
+ }
436
417
 
437
- html += `</${tag}>`
438
- return html
418
+ const exprCode = ctx.compileExpression(slot.expr, scopeRewrites)
419
+ if (nodeCapable) {
420
+ emitInsert(exprCode, marker, open, close)
421
+ }
422
+ else {
423
+ const res = emitTextSlotOp(ctx, tree, elVar, domIndex, marker, open, close, exprCode, slot.expr, scopeRewrites)
424
+ html += res.html
425
+ domIndex = res.nextIndex
426
+ }
439
427
  }
428
+ }
429
+ finally {
430
+ ctx.svgDepth = prevSvgDepth
431
+ }
440
432
 
441
- const html = buildHtml(rootEl, rootVar)
442
- const rootTag = jsxTagName(rootEl.openingElement.name)
443
- const tmplName = `_t${templates.length}`
444
- const isSvg = svgDepth > 0 ? rootTag !== 'svg' : SVG_CHILD_TAGS.has(rootTag)
445
- templates.push({ name: tmplName, html, isSvg })
446
-
447
- const walkStmts = emitWalkStatements(rootVar, walkPlan, textSlotsByParent, rangeSlotsByParent, use)
433
+ for (const op of postChildOps)
434
+ tree.ops.push(op)
448
435
 
449
- if (walkStmts.length === 0 && ops.length === 0)
450
- return `${tmplName}()`
436
+ return `${html}</${tag}>`
437
+ }
451
438
 
452
- return `(() => { const ${rootVar} = ${tmplName}(); ${walkStmts.join(' ')} ${ops.join(' ')} return ${rootVar}; })()`
439
+ function compileElementTree(ctx: DomCompilerCtx, rootEl: JSXElement, scopeRewrites: ReadonlyMap<string, string>): string {
440
+ const rootVar = ctx.freshVar('_e')
441
+ const tree: ElementTreeState = {
442
+ ops: [],
443
+ walkPlan: [],
444
+ childRefs: new Map(),
445
+ textSlotsByParent: new Map(),
446
+ rangeSlotsByParent: new Map(),
447
+ varAliases: new Map(),
453
448
  }
454
449
 
455
- function compileFragmentChildren(children: readonly JSXChild[], scopeRewrites: ReadonlyMap<string, string>): string {
456
- const planned = planChildSlots(children, { jsxNodes, exprContext, inFragment: true })
457
- if (planned.length === 0)
458
- return 'null'
450
+ const html = buildElementHtml(ctx, tree, rootEl, rootVar, scopeRewrites)
451
+ resolveElementAliases(tree)
459
452
 
460
- const hasSiblings = planned.length > 1
461
- // Coalesce consecutive static-text slots (e.g. `<>a{"b"}c</>`) so DOM matches the single merged SSR text node.
462
- const items: string[] = []
463
- let pendingStatic: string | undefined
464
- const flushStatic = () => {
465
- if (pendingStatic !== undefined) {
466
- items.push(`${use('fragText')}(${JSON.stringify(pendingStatic)})`)
467
- pendingStatic = undefined
468
- }
469
- }
453
+ const rootTag = jsxTagName(rootEl.openingElement.name)
454
+ const tmplName = `_t${ctx.templates.length}`
455
+ const isSvg = ctx.svgDepth > 0 ? rootTag !== 'svg' : SVG_CHILD_TAGS.has(rootTag)
456
+ ctx.templates.push({ name: tmplName, html, isSvg })
457
+
458
+ const walkStmts = emitWalkStatements(rootVar, tree.walkPlan, tree.textSlotsByParent, tree.rangeSlotsByParent, ctx.use)
459
+ if (walkStmts.length === 0 && tree.ops.length === 0)
460
+ return `${tmplName}()`
470
461
 
471
- const emitFragRangeOp = (hydrateCall: string, mountCall: string, needsRemoveChild: boolean): string => {
472
- const removeProp = needsRemoveChild ? ', removeChild: (n) => n.parentNode && n.parentNode.removeChild(n)' : ''
473
- return `(() => { const _s = ${use('claimRange')}(); if (_s !== null) { ${hydrateCall}; return null; } const _f = document.createDocumentFragment(); _f.appendChild(document.createComment("")); const _m = _f.appendChild(document.createComment("")); const _p = { insertBefore: (n, r) => (_m.parentNode || _f).insertBefore(n, r)${removeProp} }; ${mountCall}; return _f; })()`
462
+ return `(() => { const ${rootVar} = ${tmplName}(); ${walkStmts.join(' ')} ${tree.ops.join(' ')} return ${rootVar}; })()`
463
+ }
464
+
465
+ function compileFragmentChildren(ctx: DomCompilerCtx, children: readonly JSXChild[], scopeRewrites: ReadonlyMap<string, string>): string {
466
+ const planned = planChildSlots(children, { jsxNodes: ctx.jsxNodes, exprContext: ctx.exprContext, inFragment: true })
467
+ if (planned.length === 0)
468
+ return 'null'
469
+
470
+ const hasSiblings = planned.length > 1
471
+ // Coalesce consecutive static-text slots (e.g. `<>a{"b"}c</>`) so DOM matches the single merged SSR text node.
472
+ const items: string[] = []
473
+ let pendingStatic: string | undefined
474
+ const flushStatic = () => {
475
+ if (pendingStatic !== undefined) {
476
+ items.push(`${ctx.use('fragText')}(${JSON.stringify(pendingStatic)})`)
477
+ pendingStatic = undefined
474
478
  }
479
+ }
475
480
 
476
- for (const { slot, marker } of planned) {
477
- if (slot.kind === 'static-text') {
478
- const decoded = slot.fromLiteral ? slot.text : decodeHtmlEntities(slot.text)
479
- pendingStatic = pendingStatic === undefined ? decoded : pendingStatic + decoded
480
- continue
481
- }
482
- flushStatic()
481
+ const emitFragRangeOp = (hydrateCall: string, mountCall: string, needsRemoveChild: boolean): string => {
482
+ const removeProp = needsRemoveChild ? ', removeChild: (n) => n.parentNode && n.parentNode.removeChild(n)' : ''
483
+ return `(() => { const _s = ${ctx.use('claimRange')}(); if (_s !== null) { ${hydrateCall}; return null; } const _f = document.createDocumentFragment(); _f.appendChild(document.createComment("")); const _m = _f.appendChild(document.createComment("")); const _p = { insertBefore: (n, r) => (_m.parentNode || _f).insertBefore(n, r)${removeProp} }; ${mountCall}; return _f; })()`
484
+ }
483
485
 
484
- if (slot.kind === 'element') {
485
- items.push(compileRootJsx(slot.node, scopeRewrites))
486
- }
487
- else if (slot.kind === 'component' || slot.kind === 'fragment') {
488
- const rendered = compileRootJsx(slot.node, scopeRewrites)
489
- items.push(hasSiblings ? `${use('fragInsert')}(() => ${rendered})` : rendered)
490
- }
491
- else if (slot.kind === 'loop') {
492
- const compiled = compileLoopCall(slot.match, scopeRewrites, '_s.parentNode', '_s')
493
- if (compiled.isStatic)
494
- items.push(`(() => { const _s = ${use('claimRange')}(); if (_s !== null) { ${compiled.call('_s.parentNode', '_s')}; return null; } const _f = document.createDocumentFragment(); ${compiled.call('_f', 'null')}; return _f; })()`)
495
- else
496
- items.push(emitFragRangeOp(compiled.call('_s.parentNode', '_s'), compiled.call('_p', '_m'), true))
497
- }
498
- else if (slot.kind === 'and-show') {
499
- const whenCode = compileExpression(slot.expr.left, scopeRewrites)
500
- const trueCode = compileRootJsx(slot.right, scopeRewrites)
501
- items.push(emitFragRangeOp(
502
- `${use('show')}(_s.parentNode, _s, () => ${whenCode}, () => ${trueCode})`,
503
- `${use('show')}(_p, _m, () => ${whenCode}, () => ${trueCode})`,
504
- false,
505
- ))
506
- }
507
- else if (slot.kind === 'ternary-show') {
508
- const whenCode = compileExpression(slot.expr.test, scopeRewrites)
509
- const trueCode = isJsxNode(slot.cons)
510
- ? compileRootJsx(slot.cons, scopeRewrites)
511
- : compileExpression(slot.cons, scopeRewrites)
512
- const falseCode = isJsxNode(slot.alt)
513
- ? compileRootJsx(slot.alt, scopeRewrites)
514
- : compileExpression(slot.alt, scopeRewrites)
515
- items.push(emitFragRangeOp(
516
- `${use('show')}(_s.parentNode, _s, () => ${whenCode}, () => ${trueCode}, () => ${falseCode})`,
517
- `${use('show')}(_p, _m, () => ${whenCode}, () => ${trueCode}, () => ${falseCode})`,
518
- false,
519
- ))
520
- }
521
- else {
522
- const exprCode = compileExpression(slot.expr, scopeRewrites)
523
- if (marker === 'range')
524
- items.push(`${use('fragInsert')}(() => (${exprCode}))`)
525
- else
526
- items.push(`(() => { const _t = ${use('fragText')}("", true); ${formatSetTextOp('_t', `(${exprCode})`, slot.expr, scopeRewrites, use)} return _t; })()`)
527
- }
486
+ for (const { slot, marker } of planned) {
487
+ if (slot.kind === 'static-text') {
488
+ const decoded = slot.fromLiteral ? slot.text : decodeHtmlEntities(slot.text)
489
+ pendingStatic = pendingStatic === undefined ? decoded : pendingStatic + decoded
490
+ continue
528
491
  }
529
492
  flushStatic()
530
493
 
531
- if (items.length === 1)
532
- return items[0]!
533
- return `${use('frag')}(${items.join(', ')})`
494
+ if (slot.kind === 'element') {
495
+ items.push(compileRootJsx(ctx, slot.node, scopeRewrites))
496
+ }
497
+ else if (slot.kind === 'component' || slot.kind === 'fragment') {
498
+ const rendered = compileRootJsx(ctx, slot.node, scopeRewrites)
499
+ items.push(hasSiblings ? `${ctx.use('fragInsert')}(() => ${rendered})` : rendered)
500
+ }
501
+ else if (slot.kind === 'loop') {
502
+ const compiled = compileLoopCall(ctx, slot.match, scopeRewrites)
503
+ if (compiled.isStatic)
504
+ items.push(`(() => { const _s = ${ctx.use('claimRange')}(); if (_s !== null) { ${compiled.call('_s.parentNode', '_s')}; return null; } const _f = document.createDocumentFragment(); ${compiled.call('_f', 'null')}; return _f; })()`)
505
+ else
506
+ items.push(emitFragRangeOp(compiled.call('_s.parentNode', '_s'), compiled.call('_p', '_m'), true))
507
+ }
508
+ else if (slot.kind === 'and-show') {
509
+ const whenCode = ctx.compileExpression(slot.expr.left, scopeRewrites)
510
+ const trueCode = compileRootJsx(ctx, slot.right, scopeRewrites)
511
+ items.push(emitFragRangeOp(
512
+ `${ctx.use('show')}(_s.parentNode, _s, () => ${whenCode}, () => ${trueCode})`,
513
+ `${ctx.use('show')}(_p, _m, () => ${whenCode}, () => ${trueCode})`,
514
+ false,
515
+ ))
516
+ }
517
+ else if (slot.kind === 'ternary-show') {
518
+ const whenCode = ctx.compileExpression(slot.expr.test, scopeRewrites)
519
+ const trueCode = isJsxNode(slot.cons) ? compileRootJsx(ctx, slot.cons, scopeRewrites) : ctx.compileExpression(slot.cons, scopeRewrites)
520
+ const falseCode = isJsxNode(slot.alt) ? compileRootJsx(ctx, slot.alt, scopeRewrites) : ctx.compileExpression(slot.alt, scopeRewrites)
521
+ items.push(emitFragRangeOp(
522
+ `${ctx.use('show')}(_s.parentNode, _s, () => ${whenCode}, () => ${trueCode}, () => ${falseCode})`,
523
+ `${ctx.use('show')}(_p, _m, () => ${whenCode}, () => ${trueCode}, () => ${falseCode})`,
524
+ false,
525
+ ))
526
+ }
527
+ else {
528
+ const exprCode = ctx.compileExpression(slot.expr, scopeRewrites)
529
+ if (marker === 'range')
530
+ items.push(`${ctx.use('fragInsert')}(() => (${exprCode}))`)
531
+ else
532
+ items.push(`(() => { const _t = ${ctx.use('fragText')}("", true); ${formatSetTextOp('_t', `(${exprCode})`, slot.expr, scopeRewrites, ctx.use)} return _t; })()`)
533
+ }
534
534
  }
535
+ flushStatic()
536
+
537
+ return items.length === 1 ? items[0]! : `${ctx.use('frag')}(${items.join(', ')})`
538
+ }
539
+
540
+ function compileRootJsx(ctx: DomCompilerCtx, node: JSXElement | JSXFragment, scopeRewrites: ReadonlyMap<string, string>): string {
541
+ if (node.type === 'JSXFragment')
542
+ return compileFragmentChildren(ctx, node.children, scopeRewrites)
543
+ return isComponentTag(jsxTagName(node.openingElement.name))
544
+ ? compileComponentCall(ctx, node, scopeRewrites)
545
+ : compileElementTree(ctx, node, scopeRewrites)
546
+ }
535
547
 
536
- function compileRootJsx(node: JSXElement | JSXFragment, scopeRewrites: ReadonlyMap<string, string>): string {
537
- if (node.type === 'JSXFragment')
538
- return compileFragmentChildren(node.children, scopeRewrites)
548
+ export function compileDom(filename: string, code: string, options: CompileDomOptions = {}): CompileDomResult {
549
+ const program = options.analysis?.program ?? parseTsx(filename, code)
550
+ const analysis = options.analysis ?? analyzeModule(filename, code, program)
539
551
 
540
- const tag = jsxTagName(node.openingElement.name)
541
- if (isComponentTag(tag))
542
- return compileComponentCall(node, scopeRewrites)
552
+ if (!analysis.hasJsx && !analysis.hasLoadExport)
553
+ return { code, analysis }
543
554
 
544
- return compileElementTree(node, scopeRewrites)
555
+ const staticArrays = literalArrayConsts(program)
556
+ const loadNodes = new Set<Node>(loadDeclarations(program))
557
+ const jsxNodes = analysis.jsxNodes
558
+ const exprContext = getExprContext(analysis)
559
+ const staticStyleNames = collectStaticStyleNames(program, exprContext.primitiveVars)
560
+ const devSrc = createDevSourceAttr(filename, code, options.devSourceRoot)
561
+
562
+ const editor = new SourceEditor(code)
563
+ const used = new Set<string>()
564
+ const templates: { name: string, html: string, isSvg?: boolean }[] = []
565
+ const delegatedEvents = new Set<string>()
566
+ let varCounter = 0
567
+
568
+ const use = (name: string): string => {
569
+ used.add(name)
570
+ return `__${name}`
571
+ }
572
+ const freshVar = (prefix = '_e'): string => `${prefix}${varCounter++}`
573
+
574
+ // Client builds keep the `load` binding, so every export form stays valid, and drop its server-only code.
575
+ for (const node of loadNodes) {
576
+ if (node.type === 'FunctionDeclaration' && node.id !== null)
577
+ editor.replace(node.start, node.end, `const ${node.id.name} = undefined`)
578
+ else
579
+ editor.replace(node.start, node.end, 'undefined')
580
+ }
581
+
582
+ const { compileLoopRow, withPrelude, extractDestructuredParam, buildCompiledFunction, processFunction } = createPropCompiler({
583
+ code,
584
+ editor,
585
+ jsxNodes,
586
+ use,
587
+ freshVar,
588
+ compileExpression: (node, rewrites) => compileExpression(node, rewrites),
589
+ })
590
+
591
+ function compileNestedComponent(fn: ArrowFunctionExpression | OxcFunction, outerRewrites: ReadonlyMap<string, string>): string | undefined {
592
+ if (!containsJsx(fn.body, jsxNodes))
593
+ return undefined
594
+ if (extractDestructuredParam(fn.params[0]) === undefined)
595
+ return undefined
596
+ return buildCompiledFunction(fn, outerRewrites)
597
+ }
598
+
599
+ function compileExpression(node: Node, scopeRewrites: ReadonlyMap<string, string>): string {
600
+ return rewriteFreeIdentifiers(code, node, scopeRewrites, jsxNodes, (n, r) => compileRootJsx(ctx, n, r), compileNestedComponent)
601
+ }
602
+
603
+ const ctx: DomCompilerCtx = {
604
+ code,
605
+ analysis,
606
+ jsxNodes,
607
+ exprContext,
608
+ staticArrays,
609
+ staticStyleNames,
610
+ devSrc,
611
+ templates,
612
+ delegatedEvents,
613
+ svgDepth: 0,
614
+ use,
615
+ freshVar,
616
+ nextVarId: () => varCounter++,
617
+ compileExpression,
618
+ compileLoopRow,
619
+ withPrelude,
545
620
  }
546
621
 
547
622
  walk(program, (node) => {
@@ -552,7 +627,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
552
627
  return false
553
628
  }
554
629
  if (isJsxNode(node)) {
555
- editor.replace(node.start, node.end, compileRootJsx(node, new Map()))
630
+ editor.replace(node.start, node.end, compileRootJsx(ctx, node, new Map()))
556
631
  return false
557
632
  }
558
633
  return undefined