@mun-ui/compiler 0.0.0-stage → 0.2.0

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