@mun-ui/compiler 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/LICENSE +21 -0
  2. package/dist/analysis.d.ts +11 -0
  3. package/dist/analysis.d.ts.map +1 -0
  4. package/dist/analysis.js +80 -0
  5. package/dist/analysis.js.map +1 -0
  6. package/dist/ast.d.ts +121 -0
  7. package/dist/ast.d.ts.map +1 -0
  8. package/dist/ast.js +1022 -0
  9. package/dist/ast.js.map +1 -0
  10. package/dist/builtins.d.ts +47 -0
  11. package/dist/builtins.d.ts.map +1 -0
  12. package/dist/builtins.js +259 -0
  13. package/dist/builtins.js.map +1 -0
  14. package/dist/collection-specialization.d.ts +2 -0
  15. package/dist/collection-specialization.d.ts.map +1 -0
  16. package/dist/collection-specialization.js +475 -0
  17. package/dist/collection-specialization.js.map +1 -0
  18. package/dist/diagnostics.d.ts +12 -0
  19. package/dist/diagnostics.d.ts.map +1 -0
  20. package/dist/diagnostics.js +182 -0
  21. package/dist/diagnostics.js.map +1 -0
  22. package/dist/effect-analysis.d.ts +54 -0
  23. package/dist/effect-analysis.d.ts.map +1 -0
  24. package/dist/effect-analysis.js +318 -0
  25. package/dist/effect-analysis.js.map +1 -0
  26. package/dist/execution-plan.d.ts +63 -0
  27. package/dist/execution-plan.d.ts.map +1 -0
  28. package/dist/execution-plan.js +223 -0
  29. package/dist/execution-plan.js.map +1 -0
  30. package/dist/gpu-island-ir.d.ts +85 -0
  31. package/dist/gpu-island-ir.d.ts.map +1 -0
  32. package/dist/gpu-island-ir.js +159 -0
  33. package/dist/gpu-island-ir.js.map +1 -0
  34. package/dist/gpu-region.d.ts +28 -0
  35. package/dist/gpu-region.d.ts.map +1 -0
  36. package/dist/gpu-region.js +136 -0
  37. package/dist/gpu-region.js.map +1 -0
  38. package/dist/index.d.ts +29 -0
  39. package/dist/index.d.ts.map +1 -0
  40. package/dist/index.js +56 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/kernel-ir.d.ts +13 -0
  43. package/dist/kernel-ir.d.ts.map +1 -0
  44. package/dist/kernel-ir.js +221 -0
  45. package/dist/kernel-ir.js.map +1 -0
  46. package/dist/language-catalog.d.ts +26 -0
  47. package/dist/language-catalog.d.ts.map +1 -0
  48. package/dist/language-catalog.js +27 -0
  49. package/dist/language-catalog.js.map +1 -0
  50. package/dist/lifecycle.d.ts +15 -0
  51. package/dist/lifecycle.d.ts.map +1 -0
  52. package/dist/lifecycle.js +122 -0
  53. package/dist/lifecycle.js.map +1 -0
  54. package/dist/native-contract.d.ts +27 -0
  55. package/dist/native-contract.d.ts.map +1 -0
  56. package/dist/native-contract.js +163 -0
  57. package/dist/native-contract.js.map +1 -0
  58. package/dist/native-member-contract.d.ts +13 -0
  59. package/dist/native-member-contract.d.ts.map +1 -0
  60. package/dist/native-member-contract.js +10 -0
  61. package/dist/native-member-contract.js.map +1 -0
  62. package/dist/native-values.d.ts +43 -0
  63. package/dist/native-values.d.ts.map +1 -0
  64. package/dist/native-values.js +450 -0
  65. package/dist/native-values.js.map +1 -0
  66. package/dist/observable.d.ts +19 -0
  67. package/dist/observable.d.ts.map +1 -0
  68. package/dist/observable.js +203 -0
  69. package/dist/observable.js.map +1 -0
  70. package/dist/pipeline.d.ts +11 -0
  71. package/dist/pipeline.d.ts.map +1 -0
  72. package/dist/pipeline.js +2290 -0
  73. package/dist/pipeline.js.map +1 -0
  74. package/dist/resident-fusion.d.ts +102 -0
  75. package/dist/resident-fusion.d.ts.map +1 -0
  76. package/dist/resident-fusion.js +423 -0
  77. package/dist/resident-fusion.js.map +1 -0
  78. package/dist/resident-js.d.ts +7 -0
  79. package/dist/resident-js.d.ts.map +1 -0
  80. package/dist/resident-js.js +106 -0
  81. package/dist/resident-js.js.map +1 -0
  82. package/dist/resident-planner.d.ts +58 -0
  83. package/dist/resident-planner.d.ts.map +1 -0
  84. package/dist/resident-planner.js +101 -0
  85. package/dist/resident-planner.js.map +1 -0
  86. package/dist/resident-wasm.d.ts +56 -0
  87. package/dist/resident-wasm.d.ts.map +1 -0
  88. package/dist/resident-wasm.js +867 -0
  89. package/dist/resident-wasm.js.map +1 -0
  90. package/dist/scanner.d.ts +63 -0
  91. package/dist/scanner.d.ts.map +1 -0
  92. package/dist/scanner.js +760 -0
  93. package/dist/scanner.js.map +1 -0
  94. package/dist/semantic.d.ts +100 -0
  95. package/dist/semantic.d.ts.map +1 -0
  96. package/dist/semantic.js +669 -0
  97. package/dist/semantic.js.map +1 -0
  98. package/dist/shorthand.d.ts +16 -0
  99. package/dist/shorthand.d.ts.map +1 -0
  100. package/dist/shorthand.js +324 -0
  101. package/dist/shorthand.js.map +1 -0
  102. package/dist/source-map.d.ts +26 -0
  103. package/dist/source-map.d.ts.map +1 -0
  104. package/dist/source-map.js +228 -0
  105. package/dist/source-map.js.map +1 -0
  106. package/dist/specialization.d.ts +34 -0
  107. package/dist/specialization.d.ts.map +1 -0
  108. package/dist/specialization.js +1996 -0
  109. package/dist/specialization.js.map +1 -0
  110. package/dist/state-specialization.d.ts +3 -0
  111. package/dist/state-specialization.d.ts.map +1 -0
  112. package/dist/state-specialization.js +227 -0
  113. package/dist/state-specialization.js.map +1 -0
  114. package/dist/struct-state.d.ts +39 -0
  115. package/dist/struct-state.d.ts.map +1 -0
  116. package/dist/struct-state.js +225 -0
  117. package/dist/struct-state.js.map +1 -0
  118. package/dist/types.d.ts +70 -0
  119. package/dist/types.d.ts.map +1 -0
  120. package/dist/types.js +2 -0
  121. package/dist/types.js.map +1 -0
  122. package/dist/ui-ir.d.ts +151 -0
  123. package/dist/ui-ir.d.ts.map +1 -0
  124. package/dist/ui-ir.js +2793 -0
  125. package/dist/ui-ir.js.map +1 -0
  126. package/dist/value-types.d.ts +74 -0
  127. package/dist/value-types.d.ts.map +1 -0
  128. package/dist/value-types.js +246 -0
  129. package/dist/value-types.js.map +1 -0
  130. package/dist/vite.d.ts +33 -0
  131. package/dist/vite.d.ts.map +1 -0
  132. package/dist/vite.js +233 -0
  133. package/dist/vite.js.map +1 -0
  134. package/dist/vue-host.d.ts +25 -0
  135. package/dist/vue-host.d.ts.map +1 -0
  136. package/dist/vue-host.js +103 -0
  137. package/dist/vue-host.js.map +1 -0
  138. package/dist/web-analysis.d.ts +7 -0
  139. package/dist/web-analysis.d.ts.map +1 -0
  140. package/dist/web-analysis.js +81 -0
  141. package/dist/web-analysis.js.map +1 -0
  142. package/package.json +29 -3
  143. package/README.md +0 -3
@@ -0,0 +1,1996 @@
1
+ import * as ts from "typescript";
2
+ import * as Core from "@mun-ui/core/compat";
3
+ import { initializersOf, swiftUIStaticModifierNames } from "@mun-ui/core/compat";
4
+ import { motionPropertyBit, motionPropertyMask } from "@mun-ui/core/internal/motion-abi";
5
+ import { lowerImplicitMemberShorthand, lowerShorthand } from "./shorthand.js";
6
+ function compilerRootFileName(fileName) {
7
+ const resolvePath = ts.sys.resolvePath;
8
+ if (resolvePath)
9
+ return resolvePath(fileName);
10
+ return /^(?:[A-Za-z]:[\\/]|\/)/.test(fileName)
11
+ ? fileName
12
+ : `${ts.sys.getCurrentDirectory().replace(/[\\/]$/, "")}/${fileName}`;
13
+ }
14
+ const externalSourceFiles = new Map();
15
+ const previousPrograms = new Map();
16
+ const maximumProgramCacheSize = 32;
17
+ const maximumExternalSourceFileCacheSize = 4096;
18
+ const staticSyntaxSourceFiles = new Map();
19
+ const maximumStaticSyntaxSourceFileCacheSize = 32;
20
+ function staticSyntaxSourceFile(source) {
21
+ const cached = staticSyntaxSourceFiles.get(source);
22
+ if (cached) {
23
+ staticSyntaxSourceFiles.delete(source);
24
+ staticSyntaxSourceFiles.set(source, cached);
25
+ return cached;
26
+ }
27
+ const file = ts.createSourceFile("mun-static-plan.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
28
+ staticSyntaxSourceFiles.set(source, file);
29
+ while (staticSyntaxSourceFiles.size > maximumStaticSyntaxSourceFileCacheSize) {
30
+ const oldest = staticSyntaxSourceFiles.keys().next().value;
31
+ if (oldest === undefined)
32
+ break;
33
+ staticSyntaxSourceFiles.delete(oldest);
34
+ }
35
+ return file;
36
+ }
37
+ function rememberProgram(root, program) {
38
+ previousPrograms.delete(root);
39
+ previousPrograms.set(root, program);
40
+ while (previousPrograms.size > maximumProgramCacheSize) {
41
+ const oldest = previousPrograms.keys().next().value;
42
+ if (!oldest)
43
+ break;
44
+ previousPrograms.delete(oldest);
45
+ }
46
+ }
47
+ function rememberExternalSourceFile(key, cached) {
48
+ // TypeScript can touch a very large dependency graph in a long-lived Vite
49
+ // process. Keep hot SourceFiles reusable without letting the compiler cache
50
+ // grow forever as projects, generated declarations, or package versions
51
+ // change underneath the dev server.
52
+ externalSourceFiles.delete(key);
53
+ externalSourceFiles.set(key, cached);
54
+ while (externalSourceFiles.size > maximumExternalSourceFileCacheSize) {
55
+ const oldest = externalSourceFiles.keys().next().value;
56
+ if (!oldest)
57
+ break;
58
+ externalSourceFiles.delete(oldest);
59
+ }
60
+ }
61
+ function createMunTypeScriptProgram(source, fileName) {
62
+ const rootFileName = compilerRootFileName(fileName);
63
+ const currentDirectory = ts.sys.getCurrentDirectory();
64
+ let workspaceSelfReference = false;
65
+ try {
66
+ const packageSource = ts.sys.readFile(`${currentDirectory.replace(/[\\/]$/, "")}/package.json`);
67
+ workspaceSelfReference = packageSource ? JSON.parse(packageSource).name === "@mun-ui/ui" : false;
68
+ }
69
+ catch {
70
+ workspaceSelfReference = false;
71
+ }
72
+ const options = {
73
+ allowJs: false,
74
+ module: ts.ModuleKind.ESNext,
75
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
76
+ noEmit: true,
77
+ skipLibCheck: true,
78
+ target: ts.ScriptTarget.ES2022,
79
+ ...(workspaceSelfReference ? {
80
+ baseUrl: currentDirectory,
81
+ paths: { "@mun-ui/ui": ["./src/index.ts"] },
82
+ } : {}),
83
+ };
84
+ const host = ts.createCompilerHost(options, true);
85
+ const normalize = (value) => value.replaceAll("\\", "/");
86
+ const root = normalize(rootFileName);
87
+ const originalReadFile = host.readFile.bind(host);
88
+ const originalFileExists = host.fileExists.bind(host);
89
+ host.fileExists = requested => normalize(requested) === root || originalFileExists(requested);
90
+ host.readFile = requested => normalize(requested) === root ? source : originalReadFile(requested);
91
+ host.getSourceFile = (requested, languageVersion, onError) => {
92
+ if (normalize(requested) === root)
93
+ return ts.createSourceFile(requested, source, languageVersion, true, ts.ScriptKind.TS);
94
+ const text = originalReadFile(requested);
95
+ if (text === undefined) {
96
+ onError?.(`Unable to read ${requested}`);
97
+ return undefined;
98
+ }
99
+ const cacheKey = normalize(requested);
100
+ const languageVersionKey = typeof languageVersion === "number" ? String(languageVersion) : JSON.stringify(languageVersion);
101
+ const cached = externalSourceFiles.get(cacheKey);
102
+ if (cached && cached.text === text && cached.languageVersionKey === languageVersionKey) {
103
+ // Touch on hit so eviction is LRU rather than insertion-order FIFO.
104
+ rememberExternalSourceFile(cacheKey, cached);
105
+ return cached.sourceFile;
106
+ }
107
+ const extension = requested.toLowerCase().split(".").pop();
108
+ const scriptKind = extension === "tsx" ? ts.ScriptKind.TSX
109
+ : extension === "jsx" ? ts.ScriptKind.JSX
110
+ : extension === "js" || extension === "mjs" || extension === "cjs" ? ts.ScriptKind.JS
111
+ : extension === "json" ? ts.ScriptKind.JSON
112
+ : ts.ScriptKind.TS;
113
+ const sourceFile = ts.createSourceFile(requested, text, languageVersion, true, scriptKind);
114
+ rememberExternalSourceFile(cacheKey, { text, languageVersionKey, sourceFile });
115
+ return sourceFile;
116
+ };
117
+ let program;
118
+ try {
119
+ program = ts.createProgram([rootFileName], options, host, previousPrograms.get(root));
120
+ rememberProgram(root, program);
121
+ }
122
+ catch {
123
+ previousPrograms.delete(root);
124
+ return undefined;
125
+ }
126
+ const sourceFile = program.getSourceFile(rootFileName);
127
+ return sourceFile ? { sourceFile, checker: program.getTypeChecker() } : undefined;
128
+ }
129
+ export const staticModifierNames = new Set(swiftUIStaticModifierNames);
130
+ const compilerMotionProperties = new Map([
131
+ ["padding", ["padding"]],
132
+ ["margin", ["margin"]],
133
+ ["gap", ["gap"]],
134
+ ["font", ["font"]],
135
+ ["fontSize", ["font-size"]],
136
+ ["bold", ["font-weight"]],
137
+ ["foreground", ["color"]],
138
+ ["foregroundStyle", ["color"]],
139
+ ["background", ["background"]],
140
+ ["opacity", ["opacity"]],
141
+ ["scaleEffect", ["scale"]],
142
+ ["rotationEffect", ["rotate"]],
143
+ ["offset", ["translate"]],
144
+ ["position", ["left", "top", "transform"]],
145
+ ["zIndex", ["z-index"]],
146
+ ["kerning", ["letter-spacing"]],
147
+ ["tracking", ["letter-spacing"]],
148
+ ["baselineOffset", ["top"]],
149
+ ["shadow", ["box-shadow"]],
150
+ ["blur", ["filter"]],
151
+ ["brightness", ["filter"]],
152
+ ["contrast", ["filter"]],
153
+ ["saturation", ["filter"]],
154
+ ["grayscale", ["filter"]],
155
+ ["hueRotation", ["filter"]],
156
+ ["contentTransition", ["--mun-content"]],
157
+ ]);
158
+ function cssPropertyFromCompilerKey(value) {
159
+ if (value.startsWith("--") || value.includes("-"))
160
+ return value;
161
+ return value.replace(/[A-Z]/g, character => `-${character.toLowerCase()}`);
162
+ }
163
+ const frameMotionProperties = Object.freeze(["width", "height", "min-width", "max-width", "min-height", "max-height"]);
164
+ function objectLiteralMotionProperties(value) {
165
+ if (!value || !ts.isObjectLiteralExpression(value))
166
+ return undefined;
167
+ const properties = [];
168
+ for (const item of value.properties) {
169
+ if (!ts.isPropertyAssignment(item) && !ts.isShorthandPropertyAssignment(item))
170
+ continue;
171
+ const key = item.name && (ts.isIdentifier(item.name) || ts.isStringLiteralLike(item.name) || ts.isNumericLiteral(item.name))
172
+ ? item.name.text : undefined;
173
+ if (key)
174
+ properties.push(cssPropertyFromCompilerKey(key));
175
+ }
176
+ return properties;
177
+ }
178
+ function inferredMotionProperties(name, call) {
179
+ const known = compilerMotionProperties.get(name);
180
+ if (known)
181
+ return known;
182
+ if (name === "frame") {
183
+ const exact = objectLiteralMotionProperties(call.arguments[0]);
184
+ return exact?.filter(property => frameMotionProperties.includes(property)) ?? frameMotionProperties;
185
+ }
186
+ if (name === "style")
187
+ return objectLiteralMotionProperties(call.arguments[0]) ?? [];
188
+ return [];
189
+ }
190
+ function compiledAutoMotionArgumentsSource(properties) {
191
+ const unique = [...new Set(properties)];
192
+ const mask = motionPropertyMask(unique);
193
+ const extras = unique.filter(property => motionPropertyBit(property) === 0);
194
+ return extras.length > 0 ? `${mask}, ${JSON.stringify(extras)}` : String(mask);
195
+ }
196
+ function lowerSymbolEffectArgument(source) {
197
+ const value = source.trim();
198
+ if (value === ".automatic")
199
+ return "SymbolEffect.automatic";
200
+ if (value === ".byLayer")
201
+ return "SymbolEffect.byLayer";
202
+ if (value === ".wholeSymbol")
203
+ return "SymbolEffect.wholeSymbol";
204
+ if (value === ".magicReplace")
205
+ return "SymbolEffect.magicReplace()";
206
+ const magic = value.match(/^\.magicReplace\s*\(([\s\S]*)\)$/);
207
+ if (magic) {
208
+ const argument = magic[1].trim();
209
+ if (!argument)
210
+ return "SymbolEffect.magicReplace()";
211
+ const fallback = argument.replace(/^fallback\s*:\s*/, "").trim();
212
+ const implicit = fallback.match(/^\.([A-Za-z_$][A-Za-z0-9_$]*)$/);
213
+ return `SymbolEffect.magicReplace(${implicit ? JSON.stringify(implicit[1]) : lowerImplicitMemberShorthand(lowerShorthand(fallback))})`;
214
+ }
215
+ return lowerImplicitMemberShorthand(lowerShorthand(value));
216
+ }
217
+ export function lowerContentTransitionArgument(source) {
218
+ const value = source.trim();
219
+ if (value === ".identity")
220
+ return "ContentTransition.identity";
221
+ if (value === ".opacity")
222
+ return "ContentTransition.opacity";
223
+ if (value === ".interpolate")
224
+ return "ContentTransition.interpolate";
225
+ const blur = value.match(/^\.blurReplace\s*\(([\s\S]*)\)$/);
226
+ if (blur) {
227
+ const argument = blur[1].trim().replace(/^radius\s*:\s*/, "");
228
+ return argument ? `ContentTransition.blurReplace(${lowerImplicitMemberShorthand(lowerShorthand(argument))})` : "ContentTransition.blurReplace()";
229
+ }
230
+ const push = value.match(/^\.push\s*\(([\s\S]*)\)$/);
231
+ if (push) {
232
+ const argument = push[1].trim().replace(/^(?:from|direction)\s*:\s*/, "");
233
+ if (!argument)
234
+ return "ContentTransition.push()";
235
+ const implicit = argument.match(/^\.([A-Za-z_$][A-Za-z0-9_$]*)$/);
236
+ return `ContentTransition.push(${implicit ? JSON.stringify(implicit[1]) : lowerImplicitMemberShorthand(lowerShorthand(argument))})`;
237
+ }
238
+ const scale = value.match(/^\.scale\s*\(([\s\S]*)\)$/);
239
+ if (scale) {
240
+ const argument = scale[1].trim().replace(/^scale\s*:\s*/, "");
241
+ return argument ? `ContentTransition.scale(${lowerImplicitMemberShorthand(lowerShorthand(argument))})` : "ContentTransition.scale()";
242
+ }
243
+ const numeric = value.match(/^\.numericText\s*\(([\s\S]*)\)$/);
244
+ if (numeric) {
245
+ const argument = numeric[1].trim().replace(/^value\s*:\s*/, "");
246
+ return argument
247
+ ? `ContentTransition.numericText(${lowerImplicitMemberShorthand(lowerShorthand(argument))})`
248
+ : "ContentTransition.numericText()";
249
+ }
250
+ const symbol = value.match(/^\.symbolEffect\s*\(([\s\S]*)\)$/);
251
+ if (symbol) {
252
+ const argument = symbol[1].trim();
253
+ return argument ? `ContentTransition.symbolEffect(${lowerSymbolEffectArgument(argument)})` : "ContentTransition.symbolEffect()";
254
+ }
255
+ return lowerImplicitMemberShorthand(lowerShorthand(value));
256
+ }
257
+ function isMunViewType(checker, type) {
258
+ if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never))
259
+ return false;
260
+ const alias = type.aliasSymbol?.escapedName;
261
+ if (alias === "View" || alias === "ModifiableViewNode")
262
+ return true;
263
+ if (type.isUnion())
264
+ return type.types.length > 0 && type.types.every(item => isMunViewType(checker, item));
265
+ const rendered = checker.typeToString(type);
266
+ return rendered === "View" || rendered === "ModifiableViewNode";
267
+ }
268
+ function staticModifierChain(node) {
269
+ const calls = [];
270
+ let current = node;
271
+ while (ts.isCallExpression(current) && ts.isPropertyAccessExpression(current.expression)) {
272
+ const name = current.expression.name.text;
273
+ // These methods perform runtime overload/content normalization. Raw tuples
274
+ // cannot replace them (e.g. onTapGesture(action) becomes [1, action], and a
275
+ // background closure must run before it reaches the renderer).
276
+ if (!staticModifierNames.has(name) || requiresRuntimeModifier(name, current)
277
+ || current.expression.questionDotToken || current.arguments.some(ts.isSpreadElement))
278
+ break;
279
+ calls.unshift({ name, node: current });
280
+ current = current.expression.expression;
281
+ }
282
+ return calls.length > 0 ? { base: current, calls } : undefined;
283
+ }
284
+ const runtimeNormalizedModifiers = new Set(["onTapGesture", "background", "overlay", "listRowBackground", "shadow"]);
285
+ function requiresRuntimeModifier(name, call) {
286
+ if (!runtimeNormalizedModifiers.has(name))
287
+ return false;
288
+ // Plain CSS strings already have canonical graph arguments. Retain their
289
+ // common fast path without treating Color objects or builders as strings.
290
+ if (call.arguments[0] && ts.isStringLiteralLike(call.arguments[0])) {
291
+ if (name === "shadow" || name === "listRowBackground")
292
+ return false;
293
+ if (name === "background" && (call.arguments.length === 1
294
+ || call.arguments.length === 2 && ts.isStringLiteralLike(call.arguments[1])))
295
+ return false;
296
+ }
297
+ return true;
298
+ }
299
+ export function lowerStaticModifierChains(source, fileName) {
300
+ if (!Array.from(staticModifierNames).some(name => new RegExp(`\\.${name}\\s*\\(`).test(source)))
301
+ return source;
302
+ // A maximal modifier chain is lowered in one edit, so reparsing the complete
303
+ // module up to eight times only repeated TypeScript program construction.
304
+ // One semantic pass is sufficient: every disjoint maximal chain is collected
305
+ // before any source edit is applied.
306
+ const program = createMunTypeScriptProgram(source, fileName);
307
+ if (!program)
308
+ return source;
309
+ const candidates = [];
310
+ const visit = (node) => {
311
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
312
+ const chain = staticModifierChain(node);
313
+ const parent = node.parent;
314
+ const isNestedChain = ts.isCallExpression(parent)
315
+ && ts.isPropertyAccessExpression(parent.expression)
316
+ && parent.expression.expression === node
317
+ && staticModifierNames.has(parent.expression.name.text);
318
+ if (chain && !isNestedChain && isMunViewType(program.checker, program.checker.getTypeAtLocation(chain.base))) {
319
+ candidates.push({ node, chain });
320
+ return;
321
+ }
322
+ }
323
+ ts.forEachChild(node, visit);
324
+ };
325
+ visit(program.sourceFile);
326
+ if (candidates.length === 0)
327
+ return source;
328
+ const edits = candidates.map(({ node, chain }) => {
329
+ const base = source.slice(chain.base.getStart(program.sourceFile), chain.base.end);
330
+ // Argument expressions keep Mun authoring syntax (`$binding`, `.member`),
331
+ // so they must pass through the same lowering as labeled modifier
332
+ // arguments before being emitted into generated code.
333
+ const pendingMotionProperties = new Set();
334
+ const modifiers = chain.calls.map(({ name, node: call }) => {
335
+ if (name === "animation" && call.arguments.length === 0) {
336
+ const motionArguments = compiledAutoMotionArgumentsSource(pendingMotionProperties);
337
+ pendingMotionProperties.clear();
338
+ return `["animationAuto", [${motionArguments}]]`;
339
+ }
340
+ const argumentsSource = call.arguments.length === 0 && (name === "padding" || name === "margin")
341
+ ? name === "padding" ? "16" : "0"
342
+ : call.arguments.map(argument => {
343
+ // An implicit member argument (`.red`) is not valid TypeScript, so
344
+ // the parser recovers with a zero-width base and the node's start
345
+ // lands after the dot. Re-attach a directly-preceding dot (unless
346
+ // it belongs to a real member access like `theme.red`) so the
347
+ // shorthand lowering sees the authored form.
348
+ let start = argument.getStart(program.sourceFile);
349
+ let cursor = start - 1;
350
+ while (cursor >= 0 && /\s/.test(source[cursor]))
351
+ cursor -= 1;
352
+ // The dot must not belong to a real member access (`theme.red`,
353
+ // `arr[0].red`, `"str".red`) or to spread punctuation (`...values`).
354
+ if (source[cursor] === "." && !(cursor > 0 && /[A-Za-z0-9_$.)"'\]]/.test(source[cursor - 1])))
355
+ start = cursor;
356
+ const raw = source.slice(start, argument.end);
357
+ return name === "contentTransition" ? lowerContentTransitionArgument(raw) : lowerImplicitMemberShorthand(lowerShorthand(raw));
358
+ }).join(", ");
359
+ if (name === "animation")
360
+ pendingMotionProperties.clear();
361
+ else
362
+ for (const property of inferredMotionProperties(name, call))
363
+ pendingMotionProperties.add(property);
364
+ return `[${JSON.stringify(name)}, [${argumentsSource}]]`;
365
+ }).join(", ");
366
+ return {
367
+ start: node.getStart(program.sourceFile),
368
+ end: node.end,
369
+ replacement: `modifiedContentCompiled(${base}, [${modifiers}])`,
370
+ };
371
+ }).sort((left, right) => right.start - left.start);
372
+ let result = source;
373
+ for (const edit of edits)
374
+ result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);
375
+ return result;
376
+ }
377
+ function isNamedArgumentsCarrier(node) {
378
+ return ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "namedArguments";
379
+ }
380
+ function containsUnsafeCompiledType(type, checker, seen = new Set()) {
381
+ if (seen.has(type))
382
+ return false;
383
+ seen.add(type);
384
+ if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never))
385
+ return true;
386
+ if (type.isUnionOrIntersection())
387
+ return type.types.some(item => containsUnsafeCompiledType(item, checker, seen));
388
+ // A callable value can look safe at the outer object level while returning
389
+ // `any`/`unknown`. That is particularly dangerous for @ViewBuilder inputs:
390
+ // the trusted compiled path deliberately skips the runtime generic-builder
391
+ // validation performed by createNodeSpecialized(). Keep those calls on the
392
+ // guarded path unless the callable's input/output types are also known.
393
+ for (const signature of checker.getSignaturesOfType(type, ts.SignatureKind.Call)) {
394
+ if (containsUnsafeCompiledType(checker.getReturnTypeOfSignature(signature), checker, seen))
395
+ return true;
396
+ for (const parameter of signature.parameters) {
397
+ const declaration = parameter.valueDeclaration ?? parameter.declarations?.[0];
398
+ if (!declaration)
399
+ continue;
400
+ try {
401
+ if (containsUnsafeCompiledType(checker.getTypeOfSymbolAtLocation(parameter, declaration), checker, seen))
402
+ return true;
403
+ }
404
+ catch {
405
+ return true;
406
+ }
407
+ }
408
+ }
409
+ if (type.flags & ts.TypeFlags.Object) {
410
+ const object = type;
411
+ if (object.objectFlags & ts.ObjectFlags.Reference) {
412
+ try {
413
+ if (checker.getTypeArguments(object).some(item => containsUnsafeCompiledType(item, checker, seen)))
414
+ return true;
415
+ }
416
+ catch {
417
+ return true;
418
+ }
419
+ }
420
+ }
421
+ return false;
422
+ }
423
+ function parameterType(checker, signature, index, location) {
424
+ const parameter = signature.parameters[index];
425
+ if (!parameter)
426
+ return undefined;
427
+ const declaration = parameter.valueDeclaration ?? parameter.declarations?.[0] ?? location;
428
+ try {
429
+ return checker.getTypeOfSymbolAtLocation(parameter, declaration);
430
+ }
431
+ catch {
432
+ return undefined;
433
+ }
434
+ }
435
+ function isViewBuilderParameter(checker, signature, index, location) {
436
+ const type = parameterType(checker, signature, index, location);
437
+ if (!type)
438
+ return false;
439
+ const rendered = checker.typeToString(type);
440
+ return /\bViewBuilder(?:Closure|Content)\b/.test(rendered);
441
+ }
442
+ function stripSimpleViewBuilder(rendered) {
443
+ const expression = /^\s*\(\s*\)\s*=>\s*(\[[\s\S]*\])\s*$/.exec(rendered);
444
+ if (expression)
445
+ return expression[1];
446
+ const block = /^\s*\(\s*\)\s*=>\s*\{\s*return\s+(\[[\s\S]*\])\s*;?\s*\}\s*$/.exec(rendered);
447
+ return block?.[1];
448
+ }
449
+ const canonicalRuntimeModules = new Set(["@mun-ui/core/compat", "@mun-ui/react"]);
450
+ function runtimeViewImports(sourceFile) {
451
+ const result = new Map();
452
+ for (const statement of sourceFile.statements) {
453
+ if (!ts.isImportDeclaration(statement) || !statement.importClause || !ts.isStringLiteral(statement.moduleSpecifier))
454
+ continue;
455
+ if (!canonicalRuntimeModules.has(statement.moduleSpecifier.text))
456
+ continue;
457
+ const named = statement.importClause.namedBindings;
458
+ if (!named || !ts.isNamedImports(named))
459
+ continue;
460
+ for (const element of named.elements) {
461
+ const exported = element.propertyName?.text ?? element.name.text;
462
+ const value = Core[exported];
463
+ if (typeof value === "function" && initializersOf(value).length > 0)
464
+ result.set(element.name.text, exported);
465
+ }
466
+ }
467
+ return result;
468
+ }
469
+ function namedCarrierProperties(node) {
470
+ if (!isNamedArgumentsCarrier(node) || node.arguments.length !== 1 || !ts.isObjectLiteralExpression(node.arguments[0]))
471
+ return undefined;
472
+ const result = [];
473
+ for (const property of node.arguments[0].properties) {
474
+ if (ts.isPropertyAssignment(property)) {
475
+ const key = ts.isIdentifier(property.name) || ts.isStringLiteralLike(property.name) || ts.isNumericLiteral(property.name)
476
+ ? property.name.text
477
+ : undefined;
478
+ if (key === undefined)
479
+ return undefined;
480
+ result.push({ key, value: property.initializer });
481
+ continue;
482
+ }
483
+ if (ts.isShorthandPropertyAssignment(property)) {
484
+ result.push({ key: property.name.text, value: property.name });
485
+ continue;
486
+ }
487
+ return undefined;
488
+ }
489
+ return result;
490
+ }
491
+ function canNormalizeCompiledArguments(args, parameters, checker) {
492
+ const carriers = args.flatMap((argument, index) => isNamedArgumentsCarrier(argument) ? [{ argument, index }] : []);
493
+ if (carriers.length === 0)
494
+ return true;
495
+ if (carriers.length !== 1 || !parameters || parameters.some(parameter => parameter.variadic))
496
+ return false;
497
+ const properties = namedCarrierProperties(carriers[0].argument);
498
+ if (!properties || properties.length === 0)
499
+ return false;
500
+ if (properties.some(property => containsUnsafeCompiledType(checker.getTypeAtLocation(property.value), checker)))
501
+ return false;
502
+ const keys = new Set(properties.map(property => property.key));
503
+ const filled = new Set();
504
+ const optionIndex = parameters.findIndex(parameter => {
505
+ const allowed = parameter.properties;
506
+ return !!allowed && keys.size > 0 && [...keys].every(key => allowed.includes(key));
507
+ });
508
+ if (optionIndex >= 0) {
509
+ filled.add(optionIndex);
510
+ }
511
+ else {
512
+ for (const property of properties) {
513
+ const index = parameters.findIndex(parameter => parameter.label === property.key);
514
+ if (index < 0 || filled.has(index))
515
+ return false;
516
+ filled.add(index);
517
+ }
518
+ }
519
+ let positional = args.length - 1;
520
+ for (let index = 0; index < parameters.length && positional > 0; index += 1) {
521
+ if (filled.has(index))
522
+ continue;
523
+ filled.add(index);
524
+ positional -= 1;
525
+ }
526
+ if (positional !== 0)
527
+ return false;
528
+ return parameters.every((parameter, index) => filled.has(index) || parameter.required === false);
529
+ }
530
+ /**
531
+ * Resolve imported Mun constructor overloads with the TypeChecker. Calls with
532
+ * fully-known positional types use the trusted AOT initializer path; calls
533
+ * involving named carriers, any/unknown values, or variadics keep the guarded
534
+ * specialization path. Simple zero-argument ViewBuilder closures are lowered
535
+ * to their produced child arrays so runtime closure allocation/execution is
536
+ * avoided entirely.
537
+ */
538
+ export function lowerStaticImportedCalls(source, fileName) {
539
+ const syntax = ts.createSourceFile("mun-imports.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
540
+ const importedNames = new Set();
541
+ const runtimeImports = runtimeViewImports(syntax);
542
+ for (const statement of syntax.statements) {
543
+ if (!ts.isImportDeclaration(statement) || !statement.importClause)
544
+ continue;
545
+ if (statement.importClause.name)
546
+ importedNames.add(statement.importClause.name.text);
547
+ const bindings = statement.importClause.namedBindings;
548
+ if (bindings && ts.isNamedImports(bindings)) {
549
+ for (const element of bindings.elements)
550
+ importedNames.add(element.name.text);
551
+ }
552
+ }
553
+ if (!Array.from(importedNames).some(name => new RegExp(`\\b${name}\\s*\\(`).test(source)))
554
+ return source;
555
+ const program = createMunTypeScriptProgram(source, fileName);
556
+ if (!program)
557
+ return source;
558
+ const { sourceFile, checker } = program;
559
+ const hasRestParameter = (signature) => signature.parameters.some(parameter => (parameter.declarations?.some(declaration => ts.isParameter(declaration) && declaration.dotDotDotToken) ?? false));
560
+ const candidates = new Map();
561
+ const visit = (node) => {
562
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
563
+ const type = checker.getTypeAtLocation(node.expression);
564
+ const viewType = checker.getPropertyOfType(type, "viewType");
565
+ const signatures = checker.getSignaturesOfType(type, ts.SignatureKind.Call);
566
+ const resolved = checker.getResolvedSignature(node);
567
+ const initializerIndex = resolved
568
+ ? signatures.findIndex(signature => signature === resolved || signature.declaration === resolved.declaration)
569
+ : -1;
570
+ const selected = initializerIndex < 0 ? undefined : signatures[initializerIndex];
571
+ if (viewType && selected && !hasRestParameter(selected)) {
572
+ const runtimeName = runtimeImports.get(node.expression.text);
573
+ const runtimeInitializers = runtimeName ? initializersOf(Core[runtimeName]) : [];
574
+ let runtimeIndex = initializerIndex;
575
+ let runtimeParameters = runtimeInitializers[runtimeIndex]?.parameters;
576
+ if (node.arguments.some(isNamedArgumentsCarrier) && runtimeInitializers.length > 0) {
577
+ const matches = runtimeInitializers.flatMap((initializer, index) => initializer.parameters
578
+ && canNormalizeCompiledArguments(node.arguments, initializer.parameters, checker)
579
+ ? [{ index, parameters: initializer.parameters }]
580
+ : []);
581
+ if (matches.length === 1) {
582
+ runtimeIndex = matches[0].index;
583
+ runtimeParameters = matches[0].parameters;
584
+ }
585
+ }
586
+ const normalized = canNormalizeCompiledArguments(node.arguments, runtimeParameters, checker);
587
+ // `namedArguments(...)` is a compiler carrier and can resolve to `any`
588
+ // in partially-built workspaces. Its individual property expressions
589
+ // were already checked by canNormalizeCompiledArguments(), so do not
590
+ // let the synthetic wrapper alone disable an otherwise trusted call.
591
+ const safeTypes = node.arguments.every((argument, argumentIndex) => {
592
+ if (isNamedArgumentsCarrier(argument))
593
+ return normalized;
594
+ // A compiler-lowered ViewBuilder is a structural array factory. Once
595
+ // its simple closure shape is recognized, the closure's broad TS
596
+ // return type (often `any` in generated/custom View boundaries) does
597
+ // not make the initializer unsafe: the builder contents remain graph
598
+ // values and are validated/materialized independently. This is what
599
+ // lets an intrinsic container become a compiled template even when a
600
+ // custom View child must stay as a dynamic slot.
601
+ if (isViewBuilderParameter(checker, selected, argumentIndex, argument)) {
602
+ const text = source.slice(argument.getStart(sourceFile), argument.end);
603
+ if (stripSimpleViewBuilder(text) !== undefined)
604
+ return true;
605
+ }
606
+ return !containsUnsafeCompiledType(checker.getTypeAtLocation(argument), checker);
607
+ });
608
+ candidates.set(node, { initializerIndex: runtimeIndex, signature: selected, compiled: normalized && safeTypes, runtimeParameters });
609
+ }
610
+ }
611
+ ts.forEachChild(node, visit);
612
+ };
613
+ visit(sourceFile);
614
+ if (candidates.size === 0)
615
+ return source;
616
+ const ordered = [...candidates.keys()].sort((left, right) => left.getStart(sourceFile) - right.getStart(sourceFile) || right.end - left.end);
617
+ const children = new Map();
618
+ const stack = [];
619
+ for (const candidate of ordered) {
620
+ while (stack.length > 0 && candidate.getStart(sourceFile) >= stack[stack.length - 1].end)
621
+ stack.pop();
622
+ const parent = stack[stack.length - 1];
623
+ const siblings = children.get(parent) ?? [];
624
+ siblings.push(candidate);
625
+ children.set(parent, siblings);
626
+ stack.push(candidate);
627
+ }
628
+ const replacements = new Map();
629
+ const renderCandidate = (candidate) => {
630
+ const cached = replacements.get(candidate);
631
+ if (cached)
632
+ return cached;
633
+ const plan = candidates.get(candidate);
634
+ const renderNode = (argument) => {
635
+ let rendered = source.slice(argument.getStart(sourceFile), argument.end);
636
+ const nested = (children.get(candidate) ?? [])
637
+ .filter(child => child.getStart(sourceFile) >= argument.getStart(sourceFile) && child.end <= argument.end)
638
+ .sort((left, right) => right.getStart(sourceFile) - left.getStart(sourceFile));
639
+ for (const child of nested) {
640
+ const replacement = renderCandidate(child);
641
+ const start = child.getStart(sourceFile) - argument.getStart(sourceFile);
642
+ const end = child.end - argument.getStart(sourceFile);
643
+ rendered = rendered.slice(0, start) + replacement + rendered.slice(end);
644
+ }
645
+ return rendered;
646
+ };
647
+ const renderedArguments = candidate.arguments.map(renderNode);
648
+ let compiledArguments;
649
+ if (plan.compiled && plan.runtimeParameters) {
650
+ const carrierIndex = candidate.arguments.findIndex(isNamedArgumentsCarrier);
651
+ if (carrierIndex >= 0) {
652
+ const carrierProperties = namedCarrierProperties(candidate.arguments[carrierIndex]);
653
+ if (carrierProperties) {
654
+ const values = Array(plan.runtimeParameters.length).fill(undefined);
655
+ const keys = new Set(carrierProperties.map(property => property.key));
656
+ const optionIndex = plan.runtimeParameters.findIndex(parameter => {
657
+ const allowed = parameter.properties;
658
+ return !!allowed && keys.size > 0 && [...keys].every(key => allowed.includes(key));
659
+ });
660
+ if (optionIndex >= 0) {
661
+ values[optionIndex] = `{ ${carrierProperties.map(property => `${JSON.stringify(property.key)}: ${renderNode(property.value)}`).join(", ")} }`;
662
+ }
663
+ else {
664
+ for (const property of carrierProperties) {
665
+ const parameterIndex = plan.runtimeParameters.findIndex(parameter => parameter.label === property.key);
666
+ if (parameterIndex >= 0)
667
+ values[parameterIndex] = renderNode(property.value);
668
+ }
669
+ }
670
+ let positionalIndex = 0;
671
+ for (let index = 0; index < plan.runtimeParameters.length; index += 1) {
672
+ if (values[index] !== undefined)
673
+ continue;
674
+ while (positionalIndex < candidate.arguments.length && positionalIndex === carrierIndex)
675
+ positionalIndex += 1;
676
+ if (positionalIndex < candidate.arguments.length) {
677
+ values[index] = renderedArguments[positionalIndex];
678
+ positionalIndex += 1;
679
+ while (positionalIndex < candidate.arguments.length && positionalIndex === carrierIndex)
680
+ positionalIndex += 1;
681
+ }
682
+ else if (plan.runtimeParameters[index].required === false) {
683
+ values[index] = "undefined";
684
+ }
685
+ }
686
+ // Structural validity was proven by canNormalizeCompiledArguments().
687
+ // At this stage we only need to ensure every runtime slot received a
688
+ // concrete source expression (including explicit `undefined` for an
689
+ // omitted optional parameter).
690
+ if (values.every(value => value !== undefined))
691
+ compiledArguments = values;
692
+ }
693
+ }
694
+ }
695
+ if (!compiledArguments) {
696
+ compiledArguments = renderedArguments.map((rendered, argumentIndex) => {
697
+ const argument = candidate.arguments[argumentIndex];
698
+ if (plan.compiled && isViewBuilderParameter(checker, plan.signature, argumentIndex, argument)) {
699
+ return stripSimpleViewBuilder(rendered) ?? rendered;
700
+ }
701
+ return rendered;
702
+ });
703
+ }
704
+ else {
705
+ compiledArguments = compiledArguments.map((rendered, argumentIndex) => {
706
+ const parameter = plan.runtimeParameters?.[argumentIndex];
707
+ return parameter?.kind === "viewBuilder" ? stripSimpleViewBuilder(rendered) ?? rendered : rendered;
708
+ });
709
+ }
710
+ const argumentsSource = compiledArguments.join(", ");
711
+ const method = plan.compiled ? "createNodeCompiled" : "createNodeSpecialized";
712
+ const replacement = `${candidate.expression.getText(sourceFile)}.viewType.${method}(${plan.initializerIndex}, [${argumentsSource}])`;
713
+ replacements.set(candidate, replacement);
714
+ return replacement;
715
+ };
716
+ let result = source;
717
+ for (const candidate of (children.get(undefined) ?? []).sort((left, right) => right.getStart(sourceFile) - left.getStart(sourceFile))) {
718
+ const start = candidate.getStart(sourceFile);
719
+ result = result.slice(0, start) + renderCandidate(candidate) + result.slice(candidate.end);
720
+ }
721
+ return result;
722
+ }
723
+ function createSemanticSpecializationSnapshot(source, fileName) {
724
+ const program = createMunTypeScriptProgram(source, fileName);
725
+ if (!program)
726
+ return undefined;
727
+ return {
728
+ sourceFile: program.sourceFile,
729
+ checker: program.checker,
730
+ runtimeImports: runtimeViewImports(program.sourceFile),
731
+ };
732
+ }
733
+ function collectSemanticImportedCandidates(source, snapshot) {
734
+ const { sourceFile, checker, runtimeImports } = snapshot;
735
+ const hasRestParameter = (signature) => signature.parameters.some(parameter => (parameter.declarations?.some(declaration => ts.isParameter(declaration) && declaration.dotDotDotToken) ?? false));
736
+ const result = [];
737
+ const visit = (node) => {
738
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
739
+ const type = checker.getTypeAtLocation(node.expression);
740
+ const viewType = checker.getPropertyOfType(type, "viewType");
741
+ const signatures = checker.getSignaturesOfType(type, ts.SignatureKind.Call);
742
+ const resolved = checker.getResolvedSignature(node);
743
+ const initializerIndex = resolved
744
+ ? signatures.findIndex(signature => signature === resolved || signature.declaration === resolved.declaration)
745
+ : -1;
746
+ const selected = initializerIndex < 0 ? undefined : signatures[initializerIndex];
747
+ if (viewType && selected && !hasRestParameter(selected)) {
748
+ const runtimeName = runtimeImports.get(node.expression.text);
749
+ const runtimeInitializers = runtimeName ? initializersOf(Core[runtimeName]) : [];
750
+ let runtimeIndex = initializerIndex;
751
+ let runtimeParameters = runtimeInitializers[runtimeIndex]?.parameters;
752
+ if (node.arguments.some(isNamedArgumentsCarrier) && runtimeInitializers.length > 0) {
753
+ const matches = runtimeInitializers.flatMap((initializer, index) => initializer.parameters
754
+ && canNormalizeCompiledArguments(node.arguments, initializer.parameters, checker)
755
+ ? [{ index, parameters: initializer.parameters }]
756
+ : []);
757
+ if (matches.length === 1) {
758
+ runtimeIndex = matches[0].index;
759
+ runtimeParameters = matches[0].parameters;
760
+ }
761
+ }
762
+ const normalized = canNormalizeCompiledArguments(node.arguments, runtimeParameters, checker);
763
+ const safeTypes = node.arguments.every((argument, argumentIndex) => {
764
+ if (isNamedArgumentsCarrier(argument))
765
+ return normalized;
766
+ if (isViewBuilderParameter(checker, selected, argumentIndex, argument)) {
767
+ const rendered = source.slice(argument.getStart(sourceFile), argument.end);
768
+ if (stripSimpleViewBuilder(rendered) !== undefined)
769
+ return true;
770
+ }
771
+ return !containsUnsafeCompiledType(checker.getTypeAtLocation(argument), checker);
772
+ });
773
+ result.push({
774
+ kind: "imported",
775
+ node,
776
+ plan: { initializerIndex: runtimeIndex, signature: selected, compiled: normalized && safeTypes, runtimeParameters },
777
+ });
778
+ }
779
+ }
780
+ ts.forEachChild(node, visit);
781
+ };
782
+ visit(sourceFile);
783
+ return result;
784
+ }
785
+ function collectSemanticModifierCandidates(snapshot) {
786
+ const { sourceFile, checker } = snapshot;
787
+ const result = [];
788
+ const visit = (node) => {
789
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
790
+ const chain = staticModifierChain(node);
791
+ const parent = node.parent;
792
+ const isNestedChain = ts.isCallExpression(parent)
793
+ && ts.isPropertyAccessExpression(parent.expression)
794
+ && parent.expression.expression === node
795
+ && staticModifierNames.has(parent.expression.name.text);
796
+ if (chain && !isNestedChain && isMunViewType(checker, checker.getTypeAtLocation(chain.base))) {
797
+ result.push({ kind: "modifier", node, chain });
798
+ // Only maximal chains are semantic candidates. Imported constructor
799
+ // candidates are collected by the independent traversal above, so
800
+ // descending into this chain would create overlapping modifier roots.
801
+ return;
802
+ }
803
+ }
804
+ ts.forEachChild(node, visit);
805
+ };
806
+ visit(sourceFile);
807
+ return result;
808
+ }
809
+ function semanticCandidateStart(candidate, sourceFile) {
810
+ return candidate.node.getStart(sourceFile);
811
+ }
812
+ function semanticCandidateEnd(candidate) {
813
+ return candidate.node.end;
814
+ }
815
+ /**
816
+ * Run every TypeChecker-dependent specialization from one immutable semantic
817
+ * snapshot. Candidates are arranged by source containment before emission, so
818
+ * imported constructor lowering and modifier lowering can freely nest without
819
+ * reparsing the rewritten source or dropping an overlapping child rewrite.
820
+ */
821
+ export function lowerStaticSemanticSpecializations(source, fileName) {
822
+ const hasModifierHint = Array.from(staticModifierNames).some(name => new RegExp(`\\.${name}\\s*\\(`).test(source));
823
+ // Imported constructor specialization only recognizes the canonical runtime
824
+ // modules below. Avoid constructing a TypeScript Program for ordinary helper
825
+ // modules merely because they contain function calls; modifier chains remain
826
+ // eligible because their View type can arrive through a local/transitive import.
827
+ const hintFile = ts.createSourceFile("mun-semantic-hint.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
828
+ const runtimeImports = runtimeViewImports(hintFile);
829
+ const hasNamedRuntimeCall = [...runtimeImports.keys()].some(name => new RegExp(`\\b${name}\\s*\\(`).test(source));
830
+ const namespaceImports = hintFile.statements.flatMap(statement => {
831
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)
832
+ || !canonicalRuntimeModules.has(statement.moduleSpecifier.text))
833
+ return [];
834
+ const bindings = statement.importClause?.namedBindings;
835
+ return bindings && ts.isNamespaceImport(bindings) ? [bindings.name.text] : [];
836
+ });
837
+ const hasNamespaceRuntimeCall = namespaceImports.some(namespace => new RegExp(`\\b${namespace}\\s*\\.\\s*[A-Z][A-Za-z0-9_$]*\\s*\\(`).test(source));
838
+ if (!hasModifierHint && !hasNamedRuntimeCall && !hasNamespaceRuntimeCall)
839
+ return source;
840
+ const snapshot = createSemanticSpecializationSnapshot(source, fileName);
841
+ if (!snapshot)
842
+ return source;
843
+ const imported = collectSemanticImportedCandidates(source, snapshot);
844
+ const modifiers = hasModifierHint ? collectSemanticModifierCandidates(snapshot) : [];
845
+ const candidates = [...imported, ...modifiers];
846
+ if (candidates.length === 0)
847
+ return source;
848
+ const { sourceFile, checker } = snapshot;
849
+ const ordered = [...candidates].sort((left, right) => {
850
+ const startDelta = semanticCandidateStart(left, sourceFile) - semanticCandidateStart(right, sourceFile);
851
+ return startDelta || semanticCandidateEnd(right) - semanticCandidateEnd(left);
852
+ });
853
+ const children = new Map();
854
+ const stack = [];
855
+ for (const candidate of ordered) {
856
+ const start = semanticCandidateStart(candidate, sourceFile);
857
+ const end = semanticCandidateEnd(candidate);
858
+ while (stack.length > 0) {
859
+ const parent = stack[stack.length - 1];
860
+ if (start >= semanticCandidateStart(parent, sourceFile) && end <= semanticCandidateEnd(parent))
861
+ break;
862
+ stack.pop();
863
+ }
864
+ const parent = stack[stack.length - 1];
865
+ const siblings = children.get(parent) ?? [];
866
+ siblings.push(candidate);
867
+ children.set(parent, siblings);
868
+ stack.push(candidate);
869
+ }
870
+ const replacements = new Map();
871
+ let renderCandidate;
872
+ const renderRange = (start, end, owner) => {
873
+ let rendered = source.slice(start, end);
874
+ const nested = (children.get(owner) ?? [])
875
+ .filter(candidate => semanticCandidateStart(candidate, sourceFile) >= start && semanticCandidateEnd(candidate) <= end)
876
+ .sort((left, right) => semanticCandidateStart(right, sourceFile) - semanticCandidateStart(left, sourceFile));
877
+ for (const child of nested) {
878
+ const childStart = semanticCandidateStart(child, sourceFile);
879
+ const childEnd = semanticCandidateEnd(child);
880
+ rendered = rendered.slice(0, childStart - start) + renderCandidate(child) + rendered.slice(childEnd - start);
881
+ }
882
+ return rendered;
883
+ };
884
+ renderCandidate = (candidate) => {
885
+ const cached = replacements.get(candidate);
886
+ if (cached !== undefined)
887
+ return cached;
888
+ if (candidate.kind === "modifier") {
889
+ const { node, chain } = candidate;
890
+ const base = renderRange(chain.base.getStart(sourceFile), chain.base.end, candidate);
891
+ const pendingMotionProperties = new Set();
892
+ const modifiersSource = chain.calls.map(({ name, node: call }) => {
893
+ if (name === "animation" && call.arguments.length === 0) {
894
+ const motionArguments = compiledAutoMotionArgumentsSource(pendingMotionProperties);
895
+ pendingMotionProperties.clear();
896
+ return `["animationAuto", [${motionArguments}]]`;
897
+ }
898
+ const argumentsSource = call.arguments.length === 0 && (name === "padding" || name === "margin")
899
+ ? name === "padding" ? "16" : "0"
900
+ : call.arguments.map(argument => {
901
+ let start = argument.getStart(sourceFile);
902
+ let cursor = start - 1;
903
+ while (cursor >= 0 && /\s/.test(source[cursor]))
904
+ cursor -= 1;
905
+ if (source[cursor] === "." && !(cursor > 0 && /[A-Za-z0-9_$.)"'\]]/.test(source[cursor - 1])))
906
+ start = cursor;
907
+ const raw = renderRange(start, argument.end, candidate);
908
+ return name === "contentTransition" ? lowerContentTransitionArgument(raw) : lowerImplicitMemberShorthand(lowerShorthand(raw));
909
+ }).join(", ");
910
+ if (name === "animation")
911
+ pendingMotionProperties.clear();
912
+ else
913
+ for (const property of inferredMotionProperties(name, call))
914
+ pendingMotionProperties.add(property);
915
+ return `[${JSON.stringify(name)}, [${argumentsSource}]]`;
916
+ }).join(", ");
917
+ const replacement = `modifiedContentCompiled(${base}, [${modifiersSource}])`;
918
+ replacements.set(candidate, replacement);
919
+ return replacement;
920
+ }
921
+ const { node, plan } = candidate;
922
+ const renderNode = (argument) => renderRange(argument.getStart(sourceFile), argument.end, candidate);
923
+ const renderedArguments = node.arguments.map(renderNode);
924
+ let compiledArguments;
925
+ if (plan.compiled && plan.runtimeParameters) {
926
+ const carrierIndex = node.arguments.findIndex(isNamedArgumentsCarrier);
927
+ if (carrierIndex >= 0) {
928
+ const carrierProperties = namedCarrierProperties(node.arguments[carrierIndex]);
929
+ if (carrierProperties) {
930
+ const values = Array(plan.runtimeParameters.length).fill(undefined);
931
+ const keys = new Set(carrierProperties.map(property => property.key));
932
+ const optionIndex = plan.runtimeParameters.findIndex(parameter => {
933
+ const allowed = parameter.properties;
934
+ return !!allowed && keys.size > 0 && [...keys].every(key => allowed.includes(key));
935
+ });
936
+ if (optionIndex >= 0) {
937
+ values[optionIndex] = `{ ${carrierProperties.map(property => `${JSON.stringify(property.key)}: ${renderNode(property.value)}`).join(", ")} }`;
938
+ }
939
+ else {
940
+ for (const property of carrierProperties) {
941
+ const parameterIndex = plan.runtimeParameters.findIndex(parameter => parameter.label === property.key);
942
+ if (parameterIndex >= 0)
943
+ values[parameterIndex] = renderNode(property.value);
944
+ }
945
+ }
946
+ let positionalIndex = 0;
947
+ for (let index = 0; index < plan.runtimeParameters.length; index += 1) {
948
+ if (values[index] !== undefined)
949
+ continue;
950
+ while (positionalIndex < node.arguments.length && positionalIndex === carrierIndex)
951
+ positionalIndex += 1;
952
+ if (positionalIndex < node.arguments.length) {
953
+ values[index] = renderedArguments[positionalIndex];
954
+ positionalIndex += 1;
955
+ while (positionalIndex < node.arguments.length && positionalIndex === carrierIndex)
956
+ positionalIndex += 1;
957
+ }
958
+ else if (plan.runtimeParameters[index].required === false) {
959
+ values[index] = "undefined";
960
+ }
961
+ }
962
+ if (values.every(value => value !== undefined))
963
+ compiledArguments = values;
964
+ }
965
+ }
966
+ }
967
+ if (!compiledArguments) {
968
+ compiledArguments = renderedArguments.map((rendered, argumentIndex) => {
969
+ const argument = node.arguments[argumentIndex];
970
+ return plan.compiled && isViewBuilderParameter(checker, plan.signature, argumentIndex, argument)
971
+ ? stripSimpleViewBuilder(rendered) ?? rendered
972
+ : rendered;
973
+ });
974
+ }
975
+ else {
976
+ compiledArguments = compiledArguments.map((rendered, argumentIndex) => (plan.runtimeParameters?.[argumentIndex]?.kind === "viewBuilder" ? stripSimpleViewBuilder(rendered) ?? rendered : rendered));
977
+ }
978
+ const method = plan.compiled ? "createNodeCompiled" : "createNodeSpecialized";
979
+ const replacement = `${node.expression.getText(sourceFile)}.viewType.${method}(${plan.initializerIndex}, [${compiledArguments.join(", ")}])`;
980
+ replacements.set(candidate, replacement);
981
+ return replacement;
982
+ };
983
+ let result = source;
984
+ for (const candidate of (children.get(undefined) ?? []).sort((left, right) => semanticCandidateStart(right, sourceFile) - semanticCandidateStart(left, sourceFile))) {
985
+ const start = semanticCandidateStart(candidate, sourceFile);
986
+ result = result.slice(0, start) + renderCandidate(candidate) + result.slice(semanticCandidateEnd(candidate));
987
+ }
988
+ return result;
989
+ }
990
+ function importedBindingsOf(sourceFile) {
991
+ const bindings = new Set();
992
+ for (const statement of sourceFile.statements) {
993
+ if (!ts.isImportDeclaration(statement) || !statement.importClause)
994
+ continue;
995
+ if (statement.importClause.name)
996
+ bindings.add(statement.importClause.name.text);
997
+ const named = statement.importClause.namedBindings;
998
+ if (named && ts.isNamedImports(named))
999
+ for (const element of named.elements)
1000
+ bindings.add(element.name.text);
1001
+ if (named && ts.isNamespaceImport(named))
1002
+ bindings.add(named.name.text);
1003
+ }
1004
+ return bindings;
1005
+ }
1006
+ function animationBindingsOf(sourceFile) {
1007
+ const named = new Set();
1008
+ const namespaces = new Set();
1009
+ for (const statement of sourceFile.statements) {
1010
+ if (!ts.isImportDeclaration(statement) || !statement.importClause || !ts.isStringLiteral(statement.moduleSpecifier))
1011
+ continue;
1012
+ const moduleName = statement.moduleSpecifier.text;
1013
+ if (!moduleName.startsWith("@mun-ui/"))
1014
+ continue;
1015
+ const bindings = statement.importClause.namedBindings;
1016
+ if (bindings && ts.isNamedImports(bindings)) {
1017
+ for (const element of bindings.elements) {
1018
+ if ((element.propertyName?.text ?? element.name.text) === "Animation")
1019
+ named.add(element.name.text);
1020
+ }
1021
+ }
1022
+ else if (bindings && ts.isNamespaceImport(bindings)) {
1023
+ namespaces.add(bindings.name.text);
1024
+ }
1025
+ }
1026
+ return { named, namespaces };
1027
+ }
1028
+ const staticAnimationFactories = new Set([
1029
+ "linear", "easeIn", "easeOut", "easeInOut", "spring", "interactiveSpring", "smooth", "snappy", "bouncy",
1030
+ ]);
1031
+ const staticAnimationTransforms = new Set(["delay", "speed", "repeatCount", "repeatForever"]);
1032
+ function isAnimationTypeExpression(node, bindings) {
1033
+ if (ts.isIdentifier(node))
1034
+ return bindings.named.has(node.text);
1035
+ return ts.isPropertyAccessExpression(node)
1036
+ && node.name.text === "Animation"
1037
+ && ts.isIdentifier(node.expression)
1038
+ && bindings.namespaces.has(node.expression.text);
1039
+ }
1040
+ function hasOnlyStaticArguments(node) {
1041
+ return node.arguments.every(argument => !ts.isSpreadElement(argument) && staticExpressionValue(argument).ok);
1042
+ }
1043
+ /** True only for immutable Animation values whose entire descriptor is known at compile time. */
1044
+ function isStaticAnimationExpression(node, bindings) {
1045
+ let expression = node;
1046
+ while (ts.isParenthesizedExpression(expression) || ts.isAsExpression(expression) || ts.isTypeAssertionExpression(expression) || ts.isNonNullExpression(expression) || ts.isSatisfiesExpression(expression)) {
1047
+ expression = expression.expression;
1048
+ }
1049
+ if (ts.isPropertyAccessExpression(expression) && expression.name.text === "default") {
1050
+ return isAnimationTypeExpression(expression.expression, bindings);
1051
+ }
1052
+ if (!ts.isCallExpression(expression) || !ts.isPropertyAccessExpression(expression.expression) || !hasOnlyStaticArguments(expression))
1053
+ return false;
1054
+ const access = expression.expression;
1055
+ if (staticAnimationFactories.has(access.name.text))
1056
+ return isAnimationTypeExpression(access.expression, bindings);
1057
+ return staticAnimationTransforms.has(access.name.text) && isStaticAnimationExpression(access.expression, bindings);
1058
+ }
1059
+ function isStaticLiteralExpression(node, imported) {
1060
+ if (ts.isStringLiteralLike(node) || ts.isNumericLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
1061
+ return true;
1062
+ if (node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword || node.kind === ts.SyntaxKind.NullKeyword)
1063
+ return true;
1064
+ if (ts.isIdentifier(node))
1065
+ return node.text === "undefined";
1066
+ if (ts.isParenthesizedExpression(node))
1067
+ return isStaticLiteralExpression(node.expression, imported);
1068
+ if (ts.isPrefixUnaryExpression(node))
1069
+ return (node.operator === ts.SyntaxKind.PlusToken || node.operator === ts.SyntaxKind.MinusToken) && isStaticLiteralExpression(node.operand, imported);
1070
+ if (ts.isArrayLiteralExpression(node))
1071
+ return node.elements.every(element => ts.isExpression(element) && isStaticLiteralExpression(element, imported));
1072
+ if (ts.isObjectLiteralExpression(node))
1073
+ return node.properties.every(property => {
1074
+ if (!ts.isPropertyAssignment(property))
1075
+ return false;
1076
+ if (property.name && ts.isComputedPropertyName(property.name))
1077
+ return false;
1078
+ return isStaticLiteralExpression(property.initializer, imported);
1079
+ });
1080
+ return isStaticGraphExpression(node, imported);
1081
+ }
1082
+ function compiledViewReceiver(node, imported) {
1083
+ if (!ts.isPropertyAccessExpression(node) || node.name.text !== "createNodeCompiled")
1084
+ return false;
1085
+ const viewType = node.expression;
1086
+ return ts.isPropertyAccessExpression(viewType)
1087
+ && viewType.name.text === "viewType"
1088
+ && ts.isIdentifier(viewType.expression)
1089
+ && imported.has(viewType.expression.text);
1090
+ }
1091
+ function isStaticGraphExpression(node, imported) {
1092
+ if (!ts.isCallExpression(node))
1093
+ return false;
1094
+ if (compiledViewReceiver(node.expression, imported)) {
1095
+ return node.arguments.length === 2
1096
+ && ts.isNumericLiteral(node.arguments[0])
1097
+ && ts.isArrayLiteralExpression(node.arguments[1])
1098
+ && isStaticLiteralExpression(node.arguments[1], imported);
1099
+ }
1100
+ if (ts.isIdentifier(node.expression) && node.expression.text === "modifiedContentCompiled" && imported.has(node.expression.text)) {
1101
+ return node.arguments.length === 2
1102
+ && isStaticGraphExpression(node.arguments[0], imported)
1103
+ && isStaticLiteralExpression(node.arguments[1], imported);
1104
+ }
1105
+ return false;
1106
+ }
1107
+ function isTopLevelInitializer(node) {
1108
+ let current = node;
1109
+ while (ts.isParenthesizedExpression(current.parent)
1110
+ || ts.isAsExpression(current.parent)
1111
+ || ts.isTypeAssertionExpression(current.parent)
1112
+ || ts.isSatisfiesExpression(current.parent)
1113
+ || ts.isNonNullExpression(current.parent))
1114
+ current = current.parent;
1115
+ const declaration = current.parent;
1116
+ if (!ts.isVariableDeclaration(declaration) || declaration.initializer !== current)
1117
+ return false;
1118
+ const declarationList = declaration.parent;
1119
+ const statement = declarationList.parent;
1120
+ return ts.isVariableDeclarationList(declarationList)
1121
+ && ts.isVariableStatement(statement)
1122
+ && ts.isSourceFile(statement.parent);
1123
+ }
1124
+ function staticPrimitiveSource(value) {
1125
+ if (value === undefined)
1126
+ return "undefined";
1127
+ if (value === null)
1128
+ return "null";
1129
+ if (typeof value === "string")
1130
+ return JSON.stringify(value);
1131
+ if (typeof value === "boolean")
1132
+ return value ? "true" : "false";
1133
+ if (typeof value === "bigint")
1134
+ return `${value}n`;
1135
+ if (typeof value === "number") {
1136
+ if (!Number.isFinite(value))
1137
+ return undefined;
1138
+ if (Object.is(value, -0))
1139
+ return "-0";
1140
+ return String(value);
1141
+ }
1142
+ return undefined;
1143
+ }
1144
+ function staticExpressionValue(node) {
1145
+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isTypeAssertionExpression(node) || ts.isNonNullExpression(node) || ts.isSatisfiesExpression(node)) {
1146
+ return staticExpressionValue(node.expression);
1147
+ }
1148
+ if (ts.isStringLiteralLike(node))
1149
+ return { ok: true, value: node.text };
1150
+ if (ts.isNumericLiteral(node))
1151
+ return { ok: true, value: Number(node.text) };
1152
+ if (ts.isBigIntLiteral(node))
1153
+ return { ok: true, value: BigInt(node.text.slice(0, -1).replaceAll("_", "")) };
1154
+ if (node.kind === ts.SyntaxKind.TrueKeyword)
1155
+ return { ok: true, value: true };
1156
+ if (node.kind === ts.SyntaxKind.FalseKeyword)
1157
+ return { ok: true, value: false };
1158
+ if (node.kind === ts.SyntaxKind.NullKeyword)
1159
+ return { ok: true, value: null };
1160
+ if (ts.isIdentifier(node) && node.text === "undefined")
1161
+ return { ok: true, value: undefined };
1162
+ if (ts.isPrefixUnaryExpression(node)) {
1163
+ const operand = staticExpressionValue(node.operand);
1164
+ if (!operand.ok)
1165
+ return { ok: false };
1166
+ if (node.operator === ts.SyntaxKind.ExclamationToken)
1167
+ return { ok: true, value: !operand.value };
1168
+ if (node.operator === ts.SyntaxKind.TildeToken && (typeof operand.value === "number" || typeof operand.value === "bigint"))
1169
+ return { ok: true, value: ~operand.value };
1170
+ if (node.operator === ts.SyntaxKind.MinusToken && (typeof operand.value === "number" || typeof operand.value === "bigint"))
1171
+ return { ok: true, value: -operand.value };
1172
+ if (node.operator === ts.SyntaxKind.PlusToken && typeof operand.value === "number")
1173
+ return { ok: true, value: operand.value };
1174
+ return { ok: false };
1175
+ }
1176
+ if (ts.isTemplateExpression(node)) {
1177
+ let value = node.head.text;
1178
+ for (const span of node.templateSpans) {
1179
+ const expression = staticExpressionValue(span.expression);
1180
+ if (!expression.ok || (typeof expression.value === "symbol"))
1181
+ return { ok: false };
1182
+ value += String(expression.value) + span.literal.text;
1183
+ }
1184
+ return { ok: true, value };
1185
+ }
1186
+ if (ts.isConditionalExpression(node)) {
1187
+ const condition = staticExpressionValue(node.condition);
1188
+ return condition.ok ? staticExpressionValue(condition.value ? node.whenTrue : node.whenFalse) : { ok: false };
1189
+ }
1190
+ if (ts.isBinaryExpression(node)) {
1191
+ const left = staticExpressionValue(node.left);
1192
+ if (!left.ok)
1193
+ return { ok: false };
1194
+ const operator = node.operatorToken.kind;
1195
+ if (operator === ts.SyntaxKind.AmpersandAmpersandToken)
1196
+ return left.value ? staticExpressionValue(node.right) : left;
1197
+ if (operator === ts.SyntaxKind.BarBarToken)
1198
+ return left.value ? left : staticExpressionValue(node.right);
1199
+ if (operator === ts.SyntaxKind.QuestionQuestionToken)
1200
+ return left.value !== null && left.value !== undefined ? left : staticExpressionValue(node.right);
1201
+ const right = staticExpressionValue(node.right);
1202
+ if (!right.ok)
1203
+ return { ok: false };
1204
+ try {
1205
+ switch (operator) {
1206
+ case ts.SyntaxKind.PlusToken: return { ok: true, value: left.value + right.value };
1207
+ case ts.SyntaxKind.MinusToken: return { ok: true, value: left.value - right.value };
1208
+ case ts.SyntaxKind.AsteriskToken: return { ok: true, value: left.value * right.value };
1209
+ case ts.SyntaxKind.SlashToken: return { ok: true, value: left.value / right.value };
1210
+ case ts.SyntaxKind.PercentToken: return { ok: true, value: left.value % right.value };
1211
+ case ts.SyntaxKind.AsteriskAsteriskToken: return { ok: true, value: left.value ** right.value };
1212
+ case ts.SyntaxKind.LessThanLessThanToken: return { ok: true, value: left.value << right.value };
1213
+ case ts.SyntaxKind.GreaterThanGreaterThanToken: return { ok: true, value: left.value >> right.value };
1214
+ case ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken: return { ok: true, value: left.value >>> right.value };
1215
+ case ts.SyntaxKind.AmpersandToken: return { ok: true, value: left.value & right.value };
1216
+ case ts.SyntaxKind.BarToken: return { ok: true, value: left.value | right.value };
1217
+ case ts.SyntaxKind.CaretToken: return { ok: true, value: left.value ^ right.value };
1218
+ case ts.SyntaxKind.LessThanToken: return { ok: true, value: left.value < right.value };
1219
+ case ts.SyntaxKind.LessThanEqualsToken: return { ok: true, value: left.value <= right.value };
1220
+ case ts.SyntaxKind.GreaterThanToken: return { ok: true, value: left.value > right.value };
1221
+ case ts.SyntaxKind.GreaterThanEqualsToken: return { ok: true, value: left.value >= right.value };
1222
+ case ts.SyntaxKind.EqualsEqualsToken: return { ok: true, value: left.value == right.value };
1223
+ case ts.SyntaxKind.ExclamationEqualsToken: return { ok: true, value: left.value != right.value };
1224
+ case ts.SyntaxKind.EqualsEqualsEqualsToken: return { ok: true, value: left.value === right.value };
1225
+ case ts.SyntaxKind.ExclamationEqualsEqualsToken: return { ok: true, value: left.value !== right.value };
1226
+ default: return { ok: false };
1227
+ }
1228
+ }
1229
+ catch {
1230
+ return { ok: false };
1231
+ }
1232
+ }
1233
+ if (ts.isArrayLiteralExpression(node)) {
1234
+ const values = [];
1235
+ for (const element of node.elements) {
1236
+ if (ts.isSpreadElement(element) || ts.isOmittedExpression(element))
1237
+ return { ok: false };
1238
+ const item = staticExpressionValue(element);
1239
+ if (!item.ok)
1240
+ return { ok: false };
1241
+ values.push(item.value);
1242
+ }
1243
+ return { ok: true, value: values };
1244
+ }
1245
+ if (ts.isObjectLiteralExpression(node)) {
1246
+ const value = {};
1247
+ for (const property of node.properties) {
1248
+ if (!ts.isPropertyAssignment(property))
1249
+ return { ok: false };
1250
+ const key = ts.isIdentifier(property.name) || ts.isStringLiteralLike(property.name) || ts.isNumericLiteral(property.name)
1251
+ ? property.name.text
1252
+ : undefined;
1253
+ if (key === undefined)
1254
+ return { ok: false };
1255
+ const item = staticExpressionValue(property.initializer);
1256
+ if (!item.ok)
1257
+ return { ok: false };
1258
+ value[key] = item.value;
1259
+ }
1260
+ return { ok: true, value };
1261
+ }
1262
+ return { ok: false };
1263
+ }
1264
+ /** Fold side-effect-free expressions whose actual primitive result is known. */
1265
+ export function foldStaticResults(source) {
1266
+ const sourceFile = staticSyntaxSourceFile(source);
1267
+ const edits = [];
1268
+ const visit = (node) => {
1269
+ if (ts.isExpression(node)) {
1270
+ const composite = ts.isPrefixUnaryExpression(node) || ts.isBinaryExpression(node) || ts.isConditionalExpression(node) || ts.isTemplateExpression(node);
1271
+ if (composite) {
1272
+ const result = staticExpressionValue(node);
1273
+ const replacement = result.ok ? staticPrimitiveSource(result.value) : undefined;
1274
+ if (replacement !== undefined) {
1275
+ edits.push({ start: node.getStart(sourceFile), end: node.end, replacement });
1276
+ return;
1277
+ }
1278
+ }
1279
+ }
1280
+ ts.forEachChild(node, visit);
1281
+ };
1282
+ visit(sourceFile);
1283
+ let result = source;
1284
+ for (const edit of edits.sort((left, right) => right.start - left.start))
1285
+ result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);
1286
+ return result;
1287
+ }
1288
+ function compiledViewCallShape(node, runtimeImports) {
1289
+ if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression) || node.expression.name.text !== "createNodeCompiled")
1290
+ return undefined;
1291
+ const viewType = node.expression.expression;
1292
+ if (!ts.isPropertyAccessExpression(viewType) || viewType.name.text !== "viewType" || !ts.isIdentifier(viewType.expression))
1293
+ return undefined;
1294
+ if (node.arguments.length !== 2 || !ts.isNumericLiteral(node.arguments[0]) || !ts.isArrayLiteralExpression(node.arguments[1]))
1295
+ return undefined;
1296
+ const runtimeName = runtimeImports.get(viewType.expression.text);
1297
+ if (!runtimeName)
1298
+ return undefined;
1299
+ return {
1300
+ node,
1301
+ localName: viewType.expression.text,
1302
+ runtimeName,
1303
+ initializerIndex: Number(node.arguments[0].text),
1304
+ args: [...node.arguments[1].elements].filter(ts.isExpression),
1305
+ };
1306
+ }
1307
+ function staticTemplateDataSource(value, seen = new Set()) {
1308
+ if (value === undefined)
1309
+ return "undefined";
1310
+ if (value === null)
1311
+ return "null";
1312
+ if (typeof value === "string")
1313
+ return JSON.stringify(value);
1314
+ if (typeof value === "boolean")
1315
+ return value ? "true" : "false";
1316
+ if (typeof value === "number")
1317
+ return Number.isFinite(value) ? String(value) : undefined;
1318
+ if (typeof value === "bigint")
1319
+ return `${String(value)}n`;
1320
+ if (typeof value !== "object")
1321
+ return undefined;
1322
+ if (seen.has(value))
1323
+ return undefined;
1324
+ seen.add(value);
1325
+ try {
1326
+ if (Array.isArray(value)) {
1327
+ const items = value.map(item => staticTemplateDataSource(item, seen));
1328
+ return items.some(item => item === undefined) ? undefined : `[${items.join(", ")}]`;
1329
+ }
1330
+ const prototype = Object.getPrototypeOf(value);
1331
+ if (prototype !== Object.prototype && prototype !== null)
1332
+ return undefined;
1333
+ const entries = [];
1334
+ for (const key of Reflect.ownKeys(value)) {
1335
+ if (typeof key !== "string")
1336
+ return undefined;
1337
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
1338
+ if (!descriptor || !("value" in descriptor))
1339
+ return undefined;
1340
+ const item = staticTemplateDataSource(descriptor.value, seen);
1341
+ if (item === undefined)
1342
+ return undefined;
1343
+ entries.push(`${JSON.stringify(key)}: ${item}`);
1344
+ }
1345
+ return `{ ${entries.join(", ")} }`;
1346
+ }
1347
+ catch {
1348
+ return undefined;
1349
+ }
1350
+ finally {
1351
+ seen.delete(value);
1352
+ }
1353
+ }
1354
+ function offsetTemplateSlots(value, offset) {
1355
+ if (value !== null && typeof value === "object") {
1356
+ if (value.kind === "slot")
1357
+ return { kind: "slot", index: value.index + offset, identity: value.identity };
1358
+ if (value.kind === "fragment")
1359
+ return { kind: "fragment", children: value.children.map(child => offsetTemplateSlots(child, offset)) };
1360
+ return { ...value, children: value.children.map(child => offsetTemplateSlots(child, offset)) };
1361
+ }
1362
+ return value;
1363
+ }
1364
+ function prefixTemplateIdentity(value, prefix) {
1365
+ if (value !== null && typeof value === "object") {
1366
+ if (value.kind === "slot")
1367
+ return { ...value, identity: [...prefix, ...value.identity] };
1368
+ if (value.kind === "fragment")
1369
+ return { kind: "fragment", children: value.children.map(child => prefixTemplateIdentity(child, prefix)) };
1370
+ return { ...value, children: value.children.map(child => prefixTemplateIdentity(child, prefix)) };
1371
+ }
1372
+ return value;
1373
+ }
1374
+ function compilerTemplateSource(value) {
1375
+ if (value !== null && typeof value === "object") {
1376
+ if (value.kind === "slot")
1377
+ return `{ kind: "slot", index: ${value.index}, identity: [${value.identity.map(item => typeof item === "number" ? String(item) : JSON.stringify(item)).join(", ")}] }`;
1378
+ if (value.kind === "fragment") {
1379
+ const children = value.children.map(compilerTemplateSource);
1380
+ return children.some(item => item === undefined) ? undefined : `{ kind: "fragment", children: [${children.join(", ")}] }`;
1381
+ }
1382
+ const props = value.props === null ? "null" : staticTemplateDataSource(value.props);
1383
+ if (props === undefined)
1384
+ return undefined;
1385
+ const children = value.children.map(compilerTemplateSource);
1386
+ return children.some(item => item === undefined) ? undefined : `{ kind: "element", type: ${JSON.stringify(value.type)}, props: ${props}, children: [${children.join(", ")}] }`;
1387
+ }
1388
+ return staticTemplateDataSource(value);
1389
+ }
1390
+ /**
1391
+ * Assign compiler text slots to the renderer's stable pre-order host-node
1392
+ * table. A generic View slot may expand to an arbitrary node range, so no
1393
+ * positional Patch IR is emitted when one is present.
1394
+ */
1395
+ function compilerTemplateTextPatchLocations(plan) {
1396
+ if (plan.slots.length === 0 || plan.slots.some(slot => slot.kind !== "text"))
1397
+ return [];
1398
+ const locations = Array(plan.slots.length);
1399
+ let nodeIndex = 0;
1400
+ const visit = (value) => {
1401
+ if (value !== null && typeof value === "object") {
1402
+ if (value.kind === "fragment") {
1403
+ for (const child of value.children)
1404
+ visit(child);
1405
+ return;
1406
+ }
1407
+ if (value.kind === "slot") {
1408
+ locations[value.index] = { node: nodeIndex, kind: "text" };
1409
+ nodeIndex += 1;
1410
+ return;
1411
+ }
1412
+ nodeIndex += 1;
1413
+ for (const child of value.children)
1414
+ visit(child);
1415
+ return;
1416
+ }
1417
+ nodeIndex += 1;
1418
+ };
1419
+ visit(plan.root);
1420
+ return locations.every(location => location !== undefined)
1421
+ ? locations
1422
+ : [];
1423
+ }
1424
+ function compilerTemplateCost(value) {
1425
+ if (value !== null && typeof value === "object") {
1426
+ if (value.kind === "slot")
1427
+ return { staticNodes: 0, staticProps: 0, primitiveLeaves: 0 };
1428
+ if (value.kind === "fragment") {
1429
+ return value.children.reduce((total, child) => {
1430
+ const cost = compilerTemplateCost(child);
1431
+ return {
1432
+ staticNodes: total.staticNodes + cost.staticNodes,
1433
+ staticProps: total.staticProps + cost.staticProps,
1434
+ primitiveLeaves: total.primitiveLeaves + cost.primitiveLeaves,
1435
+ };
1436
+ }, { staticNodes: 0, staticProps: 0, primitiveLeaves: 0 });
1437
+ }
1438
+ const childCost = value.children.reduce((total, child) => {
1439
+ const cost = compilerTemplateCost(child);
1440
+ return {
1441
+ staticNodes: total.staticNodes + cost.staticNodes,
1442
+ staticProps: total.staticProps + cost.staticProps,
1443
+ primitiveLeaves: total.primitiveLeaves + cost.primitiveLeaves,
1444
+ };
1445
+ }, { staticNodes: 0, staticProps: 0, primitiveLeaves: 0 });
1446
+ return {
1447
+ staticNodes: childCost.staticNodes + 1,
1448
+ staticProps: childCost.staticProps + Object.keys(value.props ?? {}).length,
1449
+ primitiveLeaves: childCost.primitiveLeaves,
1450
+ };
1451
+ }
1452
+ return { staticNodes: 0, staticProps: 0, primitiveLeaves: 1 };
1453
+ }
1454
+ /**
1455
+ * Tiny cost model used as the compiler's path selector. Runtime allocation and
1456
+ * reconciliation work intentionally outweigh a modest code-size increase in
1457
+ * the default production-oriented profile. A rejected outer template is still
1458
+ * traversed so profitable nested templates can be selected independently.
1459
+ */
1460
+ function shouldCompileTemplatePlan(plan, node, sourceFile) {
1461
+ const rootSource = compilerTemplateSource(plan.root);
1462
+ if (rootSource === undefined)
1463
+ return false;
1464
+ const cost = compilerTemplateCost(plan.root);
1465
+ const textSlots = plan.slots.filter(slot => slot.kind === "text").length;
1466
+ // Zero-slot templates are still valuable: the DOM renderer can carry their
1467
+ // live roots through later dynamic modifier updates without recreating the
1468
+ // immutable host subtree. This is especially common for static Text/Image
1469
+ // content wrapped by a dynamic opacity/frame/style chain.
1470
+ const reusableStaticRoot = plan.slots.length === 0 && cost.staticNodes > 0;
1471
+ const runtimeSavings = cost.staticNodes * 14
1472
+ + cost.staticProps * 3
1473
+ + cost.primitiveLeaves * 2
1474
+ + textSlots * 4
1475
+ + (reusableStaticRoot ? 8 : 0);
1476
+ const slotOverhead = plan.slots.length * 2;
1477
+ const originalBytes = Math.max(1, node.end - node.getStart(sourceFile));
1478
+ const emittedGrowth = Math.max(0, rootSource.length - originalBytes) / 48;
1479
+ return runtimeSavings - slotOverhead - emittedGrowth > 0;
1480
+ }
1481
+ function propertyNameText(name) {
1482
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name))
1483
+ return name.text;
1484
+ return undefined;
1485
+ }
1486
+ function exactReturnedExpression(expression) {
1487
+ let current = expression;
1488
+ while (true) {
1489
+ if (ts.isParenthesizedExpression(current) || ts.isAsExpression(current) || ts.isTypeAssertionExpression(current)
1490
+ || ts.isNonNullExpression(current) || ts.isSatisfiesExpression(current)) {
1491
+ current = current.expression;
1492
+ continue;
1493
+ }
1494
+ if (ts.isCallExpression(current) && current.arguments.length === 0) {
1495
+ let callee = current.expression;
1496
+ while (ts.isParenthesizedExpression(callee))
1497
+ callee = callee.expression;
1498
+ if (ts.isArrowFunction(callee) && callee.parameters.length === 0) {
1499
+ const returned = exactFunctionReturn(callee);
1500
+ if (!returned)
1501
+ return undefined;
1502
+ current = returned;
1503
+ continue;
1504
+ }
1505
+ }
1506
+ return current;
1507
+ }
1508
+ }
1509
+ function exactFunctionReturn(fn) {
1510
+ if (!ts.isBlock(fn.body))
1511
+ return exactReturnedExpression(fn.body);
1512
+ if (fn.body.statements.length === 0)
1513
+ return undefined;
1514
+ const statements = [...fn.body.statements];
1515
+ const last = statements.pop();
1516
+ if (!last || !ts.isReturnStatement(last) || !last.expression)
1517
+ return undefined;
1518
+ // The slot evaluator is produced by replacing only the final compiled View
1519
+ // expression in the original body source. Restrict the prelude to linear
1520
+ // statements so no alternate return/control-flow path can be skipped.
1521
+ if (statements.some(statement => !ts.isVariableStatement(statement) && !ts.isExpressionStatement(statement)))
1522
+ return undefined;
1523
+ return exactReturnedExpression(last.expression);
1524
+ }
1525
+ const directCompiledBodyModifierNames = new Set([
1526
+ "padding", "margin", "gap", "font", "fontSize", "bold",
1527
+ "foreground", "foregroundStyle", "opacity",
1528
+ "fontWeight", "fontDesign", "fontWidth", "italic", "underline", "strikethrough", "monospaced", "monospacedDigit",
1529
+ "kerning", "tracking", "baselineOffset", "lineSpacing", "lineLimit", "minimumScaleFactor", "multilineTextAlignment", "truncationMode", "textCase", "allowsTightening",
1530
+ "scaleEffect", "rotationEffect", "offset", "aspectRatio", "scaledToFit", "scaledToFill", "fixedSize", "layoutPriority", "position", "zIndex",
1531
+ "clipShape", "clipped", "cornerRadius", "resizable", "border", "shadow", "blur", "brightness", "contrast", "saturation", "grayscale", "hueRotation", "colorInvert", "colorMultiply", "blendMode", "compositingGroup", "drawingGroup", "luminanceToAlpha", "tint",
1532
+ "hidden", "allowsHitTesting", "preferredColorScheme", "controlSize", "scrollDisabled", "scrollIndicators", "scrollBounceBehavior", "scrollClipDisabled", "scrollDismissesKeyboard",
1533
+ "accessibilityLabel", "accessibilityHint", "accessibilityValue", "accessibilityHidden", "accessibilityIdentifier", "accessibilityHeading", "accessibilitySortPriority",
1534
+ "style", "className", "animation", "animationAuto", "contentTransition",
1535
+ ]);
1536
+ function directCompiledModifierSpecs(node) {
1537
+ if (!ts.isArrayLiteralExpression(node))
1538
+ return false;
1539
+ return node.elements.every(element => {
1540
+ if (!ts.isArrayLiteralExpression(element) || element.elements.length !== 2)
1541
+ return false;
1542
+ const [name, arguments_] = element.elements;
1543
+ return ts.isStringLiteral(name)
1544
+ && directCompiledBodyModifierNames.has(name.text)
1545
+ && ts.isArrayLiteralExpression(arguments_)
1546
+ && arguments_.elements.every(argument => !ts.isSpreadElement(argument));
1547
+ });
1548
+ }
1549
+ function compilerGeneratedViewDefinition(node) {
1550
+ if (!ts.isCallExpression(node.parent))
1551
+ return false;
1552
+ const call = node.parent;
1553
+ if (!ts.isIdentifier(call.expression))
1554
+ return false;
1555
+ if (call.expression.text === "view")
1556
+ return call.arguments[0] === node;
1557
+ if (call.expression.text === "defineView" || call.expression.text === "structView")
1558
+ return call.arguments[1] === node;
1559
+ return false;
1560
+ }
1561
+ function compilerDependencyNames(property) {
1562
+ if (!property || !ts.isPropertyAssignment(property))
1563
+ return undefined;
1564
+ const initializer = exactReturnedExpression(property.initializer);
1565
+ if (!initializer || !ts.isArrowFunction(initializer) || initializer.parameters.length !== 1)
1566
+ return undefined;
1567
+ const parameter = initializer.parameters[0];
1568
+ if (!ts.isIdentifier(parameter.name))
1569
+ return undefined;
1570
+ const returned = exactFunctionReturn(initializer);
1571
+ if (!returned || !ts.isArrayLiteralExpression(returned))
1572
+ return undefined;
1573
+ const names = [];
1574
+ for (const element of returned.elements) {
1575
+ if (!ts.isPropertyAccessExpression(element)
1576
+ || !ts.isIdentifier(element.expression)
1577
+ || element.expression.text !== parameter.name.text)
1578
+ return undefined;
1579
+ names.push(element.name.text);
1580
+ }
1581
+ return names.length > 0 ? Object.freeze(names) : undefined;
1582
+ }
1583
+ function compilerBodyHasOnlyPropsPrelude(fn) {
1584
+ if (!ts.isBlock(fn.body))
1585
+ return true;
1586
+ if (fn.parameters.length !== 1 || !ts.isIdentifier(fn.parameters[0].name))
1587
+ return false;
1588
+ const parameter = fn.parameters[0].name.text;
1589
+ const statements = fn.body.statements.slice(0, -1);
1590
+ return statements.every(statement => {
1591
+ if (!ts.isVariableStatement(statement) || statement.declarationList.declarations.length !== 1)
1592
+ return false;
1593
+ const declaration = statement.declarationList.declarations[0];
1594
+ return ts.isObjectBindingPattern(declaration.name)
1595
+ && declaration.initializer !== undefined
1596
+ && ts.isIdentifier(declaration.initializer)
1597
+ && declaration.initializer.text === parameter;
1598
+ });
1599
+ }
1600
+ function directSlotDependencyNames(source, dependencyNames) {
1601
+ const sourceFile = staticSyntaxSourceFile(source);
1602
+ const available = new Set(dependencyNames);
1603
+ const found = new Set();
1604
+ const visit = (node) => {
1605
+ if (ts.isIdentifier(node) && available.has(node.text))
1606
+ found.add(node.text);
1607
+ ts.forEachChild(node, visit);
1608
+ };
1609
+ visit(sourceFile);
1610
+ return Object.freeze([...found]);
1611
+ }
1612
+ /**
1613
+ * Turn compiled intrinsic View construction into an immutable host template plus
1614
+ * runtime graph/value slots. The pass evaluates only the already-proven builtin
1615
+ * initializer with static non-builder arguments, so host props/styles come from
1616
+ * core's real View body instead of a second compiler-side semantic table.
1617
+ *
1618
+ * Dynamic Text content and builder children become slots. Any opaque argument,
1619
+ * function-valued prop, non-host graph node, spread builder, or unsupported
1620
+ * builtin simply keeps the existing createNodeCompiled graph path.
1621
+ */
1622
+ export function lowerCompiledViewTemplates(source) {
1623
+ if (!source.includes("createNodeCompiled"))
1624
+ return source;
1625
+ const sourceFile = staticSyntaxSourceFile(source);
1626
+ const runtimeImports = runtimeViewImports(sourceFile);
1627
+ if (runtimeImports.size === 0)
1628
+ return source;
1629
+ const memo = new Map();
1630
+ const building = new Set();
1631
+ const build = (node) => {
1632
+ if (memo.has(node))
1633
+ return memo.get(node) ?? undefined;
1634
+ if (building.has(node))
1635
+ return undefined;
1636
+ const shape = compiledViewCallShape(node, runtimeImports);
1637
+ if (!shape) {
1638
+ memo.set(node, null);
1639
+ return undefined;
1640
+ }
1641
+ const target = Core[shape.runtimeName];
1642
+ const runtimeInitializers = initializersOf(target);
1643
+ const initializer = runtimeInitializers[shape.initializerIndex];
1644
+ const parameters = initializer?.parameters;
1645
+ if (typeof target !== "function" || !initializer || !parameters || parameters.length !== shape.args.length) {
1646
+ memo.set(node, null);
1647
+ return undefined;
1648
+ }
1649
+ building.add(node);
1650
+ try {
1651
+ const markers = new Map();
1652
+ const runtimeArgs = [];
1653
+ const slotMarker = (slot) => {
1654
+ const token = Object.freeze({ __munCompilerTemplateSlot: markers.size });
1655
+ markers.set(token, { token, slot });
1656
+ return token;
1657
+ };
1658
+ const viewMarker = (marker) => {
1659
+ // A real fragment-shaped node safely passes through ViewBuilder content
1660
+ // and is retained by reference by intrinsic host bodies.
1661
+ const token = Core.viewFragment([]);
1662
+ markers.set(token, { token, ...marker });
1663
+ return token;
1664
+ };
1665
+ for (let index = 0; index < shape.args.length; index += 1) {
1666
+ const argument = shape.args[index];
1667
+ const parameter = parameters[index];
1668
+ if (parameter.kind === "viewBuilder") {
1669
+ if (!ts.isArrayLiteralExpression(argument)) {
1670
+ memo.set(node, null);
1671
+ return undefined;
1672
+ }
1673
+ const children = [];
1674
+ for (const child of argument.elements) {
1675
+ if (!ts.isExpression(child) || ts.isSpreadElement(child)) {
1676
+ memo.set(node, null);
1677
+ return undefined;
1678
+ }
1679
+ if (ts.isCallExpression(child)) {
1680
+ const nested = build(child);
1681
+ if (nested) {
1682
+ children.push(viewMarker({ nested }));
1683
+ continue;
1684
+ }
1685
+ }
1686
+ const literal = staticExpressionValue(child);
1687
+ if (literal.ok && (literal.value === null || literal.value === undefined || ["string", "number", "bigint", "boolean"].includes(typeof literal.value))) {
1688
+ children.push(literal.value);
1689
+ continue;
1690
+ }
1691
+ children.push(viewMarker({ slot: { source: source.slice(child.getStart(sourceFile), child.end), kind: "view" } }));
1692
+ }
1693
+ runtimeArgs.push(children);
1694
+ continue;
1695
+ }
1696
+ if (shape.runtimeName === "Text" && shape.initializerIndex === 0 && index === 0) {
1697
+ const literal = staticExpressionValue(argument);
1698
+ if (literal.ok && (typeof literal.value === "string" || typeof literal.value === "number"))
1699
+ runtimeArgs.push(literal.value);
1700
+ else
1701
+ runtimeArgs.push(slotMarker({ source: source.slice(argument.getStart(sourceFile), argument.end), kind: "text" }));
1702
+ continue;
1703
+ }
1704
+ const literal = staticExpressionValue(argument);
1705
+ if (!literal.ok) {
1706
+ memo.set(node, null);
1707
+ return undefined;
1708
+ }
1709
+ runtimeArgs.push(literal.value);
1710
+ }
1711
+ let graph;
1712
+ try {
1713
+ graph = target.viewType.createNodeCompiled(shape.initializerIndex, runtimeArgs);
1714
+ }
1715
+ catch {
1716
+ memo.set(node, null);
1717
+ return undefined;
1718
+ }
1719
+ const slots = [];
1720
+ const serialize = (value, identity = []) => {
1721
+ if (typeof value === "object" && value !== null) {
1722
+ const marker = markers.get(value);
1723
+ if (marker) {
1724
+ if (marker.nested) {
1725
+ const offset = slots.length;
1726
+ slots.push(...marker.nested.slots);
1727
+ return prefixTemplateIdentity(offsetTemplateSlots(marker.nested.root, offset), identity);
1728
+ }
1729
+ if (marker.slot !== undefined) {
1730
+ const index = slots.length;
1731
+ slots.push(marker.slot);
1732
+ return { kind: "slot", index, identity };
1733
+ }
1734
+ }
1735
+ }
1736
+ if (value === null || value === undefined || typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean")
1737
+ return value;
1738
+ if (typeof value !== "object")
1739
+ return undefined;
1740
+ const item = value;
1741
+ if (item.kind === "fragment" && Array.isArray(item.children)) {
1742
+ const children = item.children.map((child, index) => serialize(child, [...identity, "fragment", index]));
1743
+ return children.some(child => child === undefined) ? undefined : { kind: "fragment", children: children };
1744
+ }
1745
+ if (item.kind === "element" && typeof item.type === "string" && Array.isArray(item.children)) {
1746
+ if (item.props !== null && item.props !== undefined && staticTemplateDataSource(item.props) === undefined)
1747
+ return undefined;
1748
+ const children = item.children.map((child, index) => serialize(child, [...identity, "element", index]));
1749
+ return children.some(child => child === undefined) ? undefined : {
1750
+ kind: "element",
1751
+ type: item.type,
1752
+ props: item.props === null || item.props === undefined ? null : item.props,
1753
+ children: children,
1754
+ };
1755
+ }
1756
+ return undefined;
1757
+ };
1758
+ const root = serialize(graph);
1759
+ if (root === undefined) {
1760
+ memo.set(node, null);
1761
+ return undefined;
1762
+ }
1763
+ const plan = { root, slots };
1764
+ memo.set(node, plan);
1765
+ return plan;
1766
+ }
1767
+ finally {
1768
+ building.delete(node);
1769
+ }
1770
+ };
1771
+ const roots = [];
1772
+ const visit = (node, templatedAncestor = false) => {
1773
+ if (ts.isCallExpression(node)) {
1774
+ const plan = build(node);
1775
+ if (plan && !templatedAncestor && shouldCompileTemplatePlan(plan, node, sourceFile)) {
1776
+ roots.push({ node, plan });
1777
+ return;
1778
+ }
1779
+ }
1780
+ ts.forEachChild(node, child => visit(child, templatedAncestor));
1781
+ };
1782
+ visit(sourceFile);
1783
+ if (roots.length === 0)
1784
+ return source;
1785
+ const names = new Set();
1786
+ const collectNames = (node) => { if (ts.isIdentifier(node))
1787
+ names.add(node.text); ts.forEachChild(node, collectNames); };
1788
+ collectNames(sourceFile);
1789
+ let counter = 0;
1790
+ const nextName = () => {
1791
+ let name = `__munTemplate${counter++}`;
1792
+ while (names.has(name))
1793
+ name = `__munTemplate${counter++}`;
1794
+ names.add(name);
1795
+ return name;
1796
+ };
1797
+ const compiledRoots = roots.map(({ node, plan }) => {
1798
+ const rootSource = compilerTemplateSource(plan.root);
1799
+ if (rootSource === undefined)
1800
+ return undefined;
1801
+ return { node, plan, rootSource, name: nextName() };
1802
+ }).filter((value) => value !== undefined);
1803
+ if (compiledRoots.length === 0)
1804
+ return source;
1805
+ const declarations = compiledRoots.map(({ name, rootSource, plan }) => {
1806
+ const locations = compilerTemplateTextPatchLocations(plan);
1807
+ const patchSource = locations.length > 0
1808
+ ? `, [${locations.map(location => `{ node: ${location.node}, kind: "text" }`).join(", ")}]`
1809
+ : "";
1810
+ return `const ${name} = defineCompiledTemplate(${rootSource}, ${plan.slots.length}, [${plan.slots.map(slot => JSON.stringify(slot.kind)).join(", ")}]${patchSource})`;
1811
+ });
1812
+ const edits = compiledRoots.map(({ node, plan, name }) => ({
1813
+ start: node.getStart(sourceFile),
1814
+ end: node.end,
1815
+ replacement: `compiledTemplate(${name}, [${plan.slots.map(slot => slot.source).join(", ")}])`,
1816
+ }));
1817
+ // A View whose dependency set is compiler-proven exhaustive and whose body
1818
+ // returns one compiled template can skip the body/reconciliation path on
1819
+ // State-only updates. Reuse the exact original body as the slot evaluator,
1820
+ // replacing only the final View constructor with its slot array. This keeps
1821
+ // generated aliases/IIFEs and any linear prelude semantically identical.
1822
+ const rootsByNode = new Map();
1823
+ for (const root of compiledRoots)
1824
+ rootsByNode.set(root.node, root);
1825
+ const visitDefinitions = (node) => {
1826
+ if (ts.isObjectLiteralExpression(node) && compilerGeneratedViewDefinition(node)) {
1827
+ const properties = new Map();
1828
+ for (const property of node.properties) {
1829
+ if (!property.name)
1830
+ continue;
1831
+ const name = propertyNameText(property.name);
1832
+ if (name)
1833
+ properties.set(name, property);
1834
+ }
1835
+ const complete = properties.get("dependenciesComplete");
1836
+ const body = properties.get("body");
1837
+ if (!properties.has("compiledBody")
1838
+ && complete && ts.isPropertyAssignment(complete) && complete.initializer.kind === ts.SyntaxKind.TrueKeyword
1839
+ && body && ts.isPropertyAssignment(body) && ts.isArrowFunction(body.initializer)) {
1840
+ const returned = exactFunctionReturn(body.initializer);
1841
+ let root = returned && ts.isCallExpression(returned) ? rootsByNode.get(returned) : undefined;
1842
+ let replaceExpression = root?.node;
1843
+ let modifiersSource;
1844
+ if (!root && returned && ts.isCallExpression(returned)) {
1845
+ const callee = exactReturnedExpression(returned.expression);
1846
+ const content = returned.arguments[0];
1847
+ const modifierSpecs = returned.arguments[1];
1848
+ if (callee && ts.isIdentifier(callee) && callee.text === "modifiedContentCompiled"
1849
+ && content && ts.isCallExpression(content)
1850
+ && modifierSpecs && directCompiledModifierSpecs(modifierSpecs)) {
1851
+ root = rootsByNode.get(content);
1852
+ if (root) {
1853
+ replaceExpression = returned;
1854
+ modifiersSource = source.slice(modifierSpecs.getStart(sourceFile), modifierSpecs.end);
1855
+ }
1856
+ }
1857
+ }
1858
+ if (root && replaceExpression && root.plan.slots.every(slot => slot.kind === "text")) {
1859
+ const functionStart = body.initializer.getStart(sourceFile);
1860
+ const functionEnd = body.initializer.end;
1861
+ const replacementStart = replaceExpression.getStart(sourceFile);
1862
+ const bodySource = source.slice(functionStart, functionEnd);
1863
+ const slotArray = `[${root.plan.slots.map(slot => slot.source).join(", ")}]`;
1864
+ // Patch IR already declares every stable text sink. Do not allocate a
1865
+ // fresh all-dirty bitset in generated code on every State update;
1866
+ // direct Web keeps one immutable full-candidate mask per Patch IR and
1867
+ // then filters it against the last committed values.
1868
+ const evaluation = `({ slots: ${slotArray}${modifiersSource ? `, modifiers: ${modifiersSource}` : ""} })`;
1869
+ const evaluator = bodySource.slice(0, replacementStart - functionStart)
1870
+ + evaluation
1871
+ + bodySource.slice(replaceExpression.end - functionStart);
1872
+ const patchLocations = compilerTemplateTextPatchLocations(root.plan);
1873
+ const dependencyNames = compilerDependencyNames(properties.get("dependencies"));
1874
+ let sparsePatchSource = "";
1875
+ if (!modifiersSource && patchLocations.length === root.plan.slots.length
1876
+ && dependencyNames && compilerBodyHasOnlyPropsPrelude(body.initializer)) {
1877
+ const dependenciesBySlot = root.plan.slots.map(slot => directSlotDependencyNames(slot.source, dependencyNames));
1878
+ const referencedDependencies = new Set(dependenciesBySlot.flatMap(names => [...names]));
1879
+ if (dependenciesBySlot.every(names => names.length > 0)
1880
+ && dependencyNames.every(name => referencedDependencies.has(name))) {
1881
+ const indicesByDependency = new Map(dependencyNames.map(name => [name, []]));
1882
+ dependenciesBySlot.forEach((names, index) => names.forEach(name => indicesByDependency.get(name).push(index)));
1883
+ const dirtyName = nextName();
1884
+ const valuesName = nextName();
1885
+ const propsName = nextName();
1886
+ const patchBody = `(() => { ${root.plan.slots.map((slot, index) => {
1887
+ const word = index >>> 5;
1888
+ const bit = 1 << (index & 31);
1889
+ return `if ((${dirtyName}[${word}] & ${bit >>> 0}) !== 0) ${valuesName}[${index}] = ${slot.source};`;
1890
+ }).join(" ")} })()`;
1891
+ const sparseBody = bodySource.slice(0, replacementStart - functionStart)
1892
+ + patchBody
1893
+ + bodySource.slice(replaceExpression.end - functionStart);
1894
+ const dependencyObject = `{ ${[...indicesByDependency].map(([name, indices]) => `${JSON.stringify(name)}: [${indices.join(", ")}]`).join(", ")} }`;
1895
+ sparsePatchSource = `, patchDependencyIndices: ${dependencyObject}, evaluatePatch: (${propsName}: any, ${dirtyName}: Uint32Array, ${valuesName}: unknown[]) => ((${sparseBody})(${propsName}))`;
1896
+ }
1897
+ }
1898
+ edits.push({
1899
+ start: body.getStart(sourceFile),
1900
+ end: body.getStart(sourceFile),
1901
+ replacement: `compiledBody: { template: ${root.name}${modifiersSource ? ", patchesModifiers: true" : ""}${sparsePatchSource}, evaluate: ${evaluator} }, `,
1902
+ });
1903
+ }
1904
+ }
1905
+ }
1906
+ ts.forEachChild(node, visitDefinitions);
1907
+ };
1908
+ visitDefinitions(sourceFile);
1909
+ let result = source;
1910
+ for (const edit of edits.sort((left, right) => right.start - left.start))
1911
+ result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);
1912
+ const importEnd = sourceFile.statements.filter(ts.isImportDeclaration).at(-1)?.end ?? 0;
1913
+ const prefix = `${importEnd > 0 ? "\n" : ""}${declarations.join("\n")}\n`;
1914
+ return result.slice(0, importEnd) + prefix + result.slice(importEnd);
1915
+ }
1916
+ export function hoistStaticViewSubtrees(source) {
1917
+ // No graph constructor or Animation binding means neither hoist class can
1918
+ // possibly match. Avoid allocating a full AST for ordinary helper modules.
1919
+ if (!source.includes("createNodeCompiled")
1920
+ && !source.includes("modifiedContentCompiled")
1921
+ && !/\bAnimation\b/.test(source))
1922
+ return source;
1923
+ const sourceFile = staticSyntaxSourceFile(source);
1924
+ const imported = importedBindingsOf(sourceFile);
1925
+ const animationBindings = animationBindingsOf(sourceFile);
1926
+ if (imported.size === 0 && animationBindings.named.size === 0 && animationBindings.namespaces.size === 0)
1927
+ return source;
1928
+ const candidates = [];
1929
+ const visit = (node) => {
1930
+ if (ts.isExpression(node)) {
1931
+ if (imported.size > 0 && isStaticGraphExpression(node, imported)) {
1932
+ if (!isTopLevelInitializer(node))
1933
+ candidates.push({ node, kind: "view" });
1934
+ return;
1935
+ }
1936
+ if ((animationBindings.named.size > 0 || animationBindings.namespaces.size > 0)
1937
+ && isStaticAnimationExpression(node, animationBindings)) {
1938
+ if (!isTopLevelInitializer(node))
1939
+ candidates.push({ node, kind: "motion" });
1940
+ // A maximal immutable Animation chain subsumes its factory/base call.
1941
+ return;
1942
+ }
1943
+ }
1944
+ ts.forEachChild(node, visit);
1945
+ };
1946
+ visit(sourceFile);
1947
+ if (candidates.length === 0)
1948
+ return source;
1949
+ const names = new Set();
1950
+ const collectNames = (node) => { if (ts.isIdentifier(node))
1951
+ names.add(node.text); ts.forEachChild(node, collectNames); };
1952
+ collectNames(sourceFile);
1953
+ let staticSuffix = 0;
1954
+ let motionSuffix = 0;
1955
+ const nextName = (kind) => {
1956
+ const prefix = kind === "motion" ? "__munMotion" : "__munStatic";
1957
+ let name;
1958
+ do
1959
+ name = `${prefix}${kind === "motion" ? motionSuffix++ : staticSuffix++}`;
1960
+ while (names.has(name));
1961
+ names.add(name);
1962
+ return name;
1963
+ };
1964
+ // Immutable Animation values may be shared safely. Deduplicating identical
1965
+ // descriptors is particularly valuable because the Web motion planner caches
1966
+ // its compiled execution plan by Animation object identity.
1967
+ const motionNames = new Map();
1968
+ const hoists = candidates.map(candidate => {
1969
+ const expression = source.slice(candidate.node.getStart(sourceFile), candidate.node.end);
1970
+ if (candidate.kind === "motion") {
1971
+ const existing = motionNames.get(expression);
1972
+ if (existing)
1973
+ return { ...candidate, name: existing, expression, declaration: false };
1974
+ const name = nextName(candidate.kind);
1975
+ motionNames.set(expression, name);
1976
+ return { ...candidate, name, expression, declaration: true };
1977
+ }
1978
+ return { ...candidate, name: nextName(candidate.kind), expression, declaration: true };
1979
+ });
1980
+ let result = source;
1981
+ for (const { node, name } of [...hoists].sort((left, right) => right.node.getStart(sourceFile) - left.node.getStart(sourceFile))) {
1982
+ result = result.slice(0, node.getStart(sourceFile)) + name + result.slice(node.end);
1983
+ }
1984
+ let insertion = 0;
1985
+ for (const statement of sourceFile.statements) {
1986
+ if (!ts.isImportDeclaration(statement))
1987
+ break;
1988
+ insertion = statement.end;
1989
+ }
1990
+ const declarations = hoists
1991
+ .filter(candidate => candidate.declaration)
1992
+ .map(({ name, expression }) => `\nconst ${name} = ${expression}`)
1993
+ .join("") + "\n";
1994
+ return result.slice(0, insertion) + declarations + result.slice(insertion);
1995
+ }
1996
+ //# sourceMappingURL=specialization.js.map