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