Backtestsvuerun-20261007-145226#15126
compileScript drops template imports from returned when analysis re-runs on a transformed template AST
The merged fix was judged better than our patch.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches fix the root cause the same way: when the shared template AST has already been transformed, they re-parse a fresh AST before running import-usage and v-model analysis, mirroring the guard in compileTemplate. The difference is in how they re-parse. - **Patch A** always calls compiler-dom's `parse` with only `prefixIdentifiers` and `parseMode: 'sfc'`. It ignores any user-supplied compiler/parser options, such as custom `delimiters`, `isCustomElement` or a custom compiler. For an SFC using custom delimiters, the re-parsed AST would treat `[[ foo ]]` as plain text, so `foo` would still be dropped from `__returned__`. That is the same bug under a non-default configuration. - **Patch B** extracts the exact compileTemplate guard into a shared `resolveTemplateAST` helper. It threads `options.templateOptions` (compiler, compilerOptions, ssr) from compileScript into the analysis, so the re-parse honours the same options compileTemplate uses. This is a more faithful mirror of the existing guard, as the issue requests, and removes duplicated logic. The compileTemplate refactor preserves behaviour: same parse call, same `createRoot`, same `onError` handling. Tests: - Patch A's tests are broader. They cover template expressions, v-for, v-model demotion, recoverable parse errors and `hmrShouldReload`. They would fail before the fix. - Patch B's single test explicitly simulates cache eviction on a transformed AST, using custom delimiters. That exercises exactly the scenario where Patch A would still fail. Scope and craft: - Patch B has more churn: it exports the cache for tests and adds a new helper module. That churn serves the fix through deduplication and consistency rather than adding risk. - Patch A is smaller and has good tests, but it is less correct across configurations. On correctness, which weighs most, Patch B is better.
The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.
Solve
5m 29s
Wall-clock time in the container
Full test suite
No new failures
3,638 passed · 6 skipped · 3,644 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
130vs 173 merged
Changed lines, ours vs merged
The issue
View on GitHubVue version
3.5.40
Link to minimal reproduction
https://stackblitz.com/edit/vitejs-vite-evwepvbu?file=package.json
Steps to reproduce
Compile more than 500 unique SFCs for client + SSR (non-inline mode), share each file's descriptor between the two passes (the same way @vitejs/plugin-vue does). The client pass compileTemplate changes the shared template.ast in place, when the analysis cache (capped at 500) evicts a file entry, its SSR compileScript pass re-runs the import usage analysis on that already transformed AST
What is expected?
__returned__ contains every import the template references, same output as when fewer than 500 templates are compiled. The analysis should re-parse when the AST was already transformed, the same guard compileTemplate has with if (inAST?.transformed) in line 214.
What is actually happening?
Imports referenced only from template expressions or with v-for are dropped from __returned__. While the render function still emits $setup.foo(...) and throws TypeError: $setup.foo is not a function at runtime. Because it only happens with more than 500 unique templates it only comes up in large apps in development, in production builds the template are inlined and are unaffected.
System Info
Any additional comments?
Might be the cause for vitejs/vite-plugin-vue#764, vitest-dev/vitest#9855?
The two patches
packages/compiler-sfc/__tests__/compileScript/importUsageCheck.spec.tsindex 210fa0968..ff8b6d9c9 100644@@ -1,4 +1,7 @@-import { assertCode, compileSFCScript as compile } from '../utils'+import { assertCode, compileSFCScript as compile, mockId } from '../utils'+import { BindingTypes } from '@vue/compiler-core'+import { compileScript, compileTemplate, parse } from '../../src'+import { hmrShouldReload } from '../../src/parse' // in dev mode, declared bindings are returned as an object from setup() // when using TS, users may import types which should not be returned as@@ -265,3 +268,96 @@ test('shorthand binding w/ kebab-case', () => { ) expect(content).toMatch('return { get fooBar() { return fooBar }') })++// analysis must not run on a template AST that compileTemplate() has already+// transformed in place (e.g. shared descriptor between client & SSR passes)+describe('template AST already transformed', () => {+ function transformTemplateAST(src: string, ssr = false) {+ const { descriptor } = parse(src)+ compileTemplate({+ id: mockId,+ filename: 'test.vue',+ source: descriptor.template!.content,+ ast: descriptor.template!.ast,+ ssr,+ })+ expect(descriptor.template!.ast!.transformed).toBe(true)+ return descriptor+ }++ test('imports used in template expressions and v-for', () => {+ const descriptor = transformTemplateAST(`+ <script setup lang="ts">+ import { fooTransformed, listTransformed, Comp } from './x'+ </script>+ <template>+ <div>{{ fooTransformed(1) }}</div>+ <span v-for="i in listTransformed" :key="i">{{ i }}</span>+ <Comp v-if="true" />+ </template>+ `)+ const { content } = compileScript(descriptor, {+ id: mockId,+ inlineTemplate: false,+ templateOptions: { ssr: true },+ })+ expect(content).toMatch(+ 'return { get fooTransformed() { return fooTransformed }, ' ++ 'get listTransformed() { return listTransformed }, ' ++ 'get Comp() { return Comp } }',+ )+ })++ test('v-model target nested in v-if', () => {+ const descriptor = transformTemplateAST(`+ <script setup lang="ts">+ import { reactive } from 'vue'+ const nameTransformed = reactive({ first: 'john' })+ </script>+ <template>+ <div v-if="true"><MyComponent v-model="nameTransformed" /></div>+ </template>+ `)+ const { content, bindings } = compileScript(descriptor, {+ id: mockId,+ inlineTemplate: false,+ })+ expect(content).toMatch(`let nameTransformed = reactive(`)+ expect(bindings!.nameTransformed).toBe(BindingTypes.SETUP_LET)+ })++ test('template with recoverable parse errors', () => {+ const descriptor = transformTemplateAST(`+ <script setup lang="ts">+ import { errFooTransformed } from './x'+ </script>+ <template>+ <div>{{ errFooTransformed }}</span></div>+ </template>+ `)+ const { content } = compileScript(descriptor, {+ id: mockId,+ inlineTemplate: false,+ })+ expect(content).toMatch(+ 'return { get errFooTransformed() { return errFooTransformed } }',+ )+ })++ test('hmrShouldReload', () => {+ const prev = parse(`+ <script setup lang="ts">+ import { hmrFooTransformed } from './x'+ </script>+ <template><div /></template>+ `).descriptor+ const prevImports = compileScript(prev, { id: mockId }).imports!+ const next = transformTemplateAST(`+ <script setup lang="ts">+ import { hmrFooTransformed } from './x'+ </script>+ <template><div v-if="true">{{ hmrFooTransformed }}</div></template>+ `)+ expect(hmrShouldReload(prevImports, next)).toBe(true)+ })+})packages/compiler-sfc/src/script/importUsageCheck.tsindex 9c087b466..09432be2d 100644@@ -1,10 +1,13 @@ import type { SFCDescriptor } from '../parse' import {+ type ElementNode, type ExpressionNode, NodeTypes,+ type RootNode, type SimpleExpressionNode, type TemplateChildNode, isSimpleIdentifier,+ parse, parserOptions, walkIdentifiers, } from '@vue/compiler-dom'@@ -42,7 +45,7 @@ function resolveTemplateAnalysisResult( usedIds?: Set<string> vModelIds: Set<string> } {- const { content, ast } = sfc.template!+ const { content } = sfc.template! const cached = templateAnalysisCache.get(content) if (cached && (!collectUsedIds || cached.usedIds)) { return cached@@ -53,7 +56,7 @@ function resolveTemplateAnalysisResult( const ids = collectUsedIds ? new Set<string>() : undefined const vModelIds = new Set<string>() - ast!.children.forEach(walk)+ resolveUntransformedTemplateChildren(sfc.template!.ast!).forEach(walk) function walk(node: TemplateChildNode) { switch (node.type) {@@ -134,6 +137,31 @@ function resolveTemplateAnalysisResult( return result } +/**+ * The descriptor's template AST may be shared with compileTemplate(), which+ * transforms it in place (e.g. a client compile followed by an SSR compile of+ * the same descriptor). A transformed AST no longer carries the original+ * directives / expressions, so re-parse a fresh one from the SFC source,+ * mirroring the same guard in compileTemplate().+ */+function resolveUntransformedTemplateChildren(+ ast: RootNode,+): TemplateChildNode[] {+ if (!ast.transformed) {+ return ast.children+ }+ const newAST = parse(ast.source, {+ prefixIdentifiers: true,+ parseMode: 'sfc',+ // errors were already reported on the descriptor by the original parse+ onError: () => {},+ })+ const template = newAST.children.find(+ node => node.type === NodeTypes.ELEMENT && node.tag === 'template',+ ) as ElementNode+ return template.children+}+ function extractIdentifiers(ids: Set<string>, node: ExpressionNode) { if (node.ast) { walkIdentifiers(node.ast, n => ids.add(n.name))
packages/compiler-sfc/__tests__/compileScript.spec.tsindex 5e547f6b2..d54541019 100644@@ -7,6 +7,8 @@ import { mockId, } from './utils' import { type RawSourceMap, SourceMapConsumer } from 'source-map-js'+import { compileScript, compileTemplate, parse } from '../src'+import { templateAnalysisCache } from '../src/script/importUsageCheck' vi.mock('../src/warn', () => ({ warn: vi.fn(),@@ -345,6 +347,43 @@ describe('SFC compile <script setup>', () => { expect(content).toMatch(`import { useCssVars, ref } from 'vue'`) }) + test('should re-analyze a transformed template after cache invalidation', () => {+ const delimiters: [string, string] = ['[[', ']]']+ const { descriptor } = parse(+ `+ <script setup lang="ts">+ import { cachedMsg } from './cachedMsg'+ </script>+ <template><p>[[ cachedMsg ]]</p></template>+ `,+ { templateParseOptions: { delimiters } },+ )++ const templateOptions = { compilerOptions: { delimiters } }+ compileScript(descriptor, { id: mockId, templateOptions })+ expect(templateAnalysisCache.has(descriptor.template!.content)).toBe(true)++ compileTemplate({+ filename: 'example.vue',+ id: mockId,+ source: descriptor.template!.content,+ ast: descriptor.template!.ast,+ compilerOptions: { delimiters },+ })+ expect(descriptor.template!.ast!.transformed).toBe(true)++ templateAnalysisCache.clear()+ expect(templateAnalysisCache.has(descriptor.template!.content)).toBe(+ false,+ )++ const { content } = compileScript(descriptor, {+ id: mockId,+ templateOptions,+ })+ expect(content).toMatch(`return { get cachedMsg() { return cachedMsg } }`)+ })+ test('import dedupe between <script> and <script setup>', () => { const { content } = compile(` <script>packages/compiler-sfc/src/compileScript.tsindex a60aba17a..d2047c5b2 100644@@ -266,7 +266,7 @@ export function compileScript( !sfc.template.src && !sfc.template.lang ) {- isUsedInTemplate = isImportUsed(local, sfc)+ isUsedInTemplate = isImportUsed(local, sfc, options.templateOptions) } ctx.userImports[local] = {@@ -769,7 +769,10 @@ export function compileScript( // which requires a SETUP_LET binding (getter + setter) to keep script state in sync. // In inline mode, it generates `foo = $event`, which also requires `let`. if (sfc.template && !sfc.template.src && sfc.template.ast) {- const vModelIds = resolveTemplateVModelIdentifiers(sfc)+ const vModelIds = resolveTemplateVModelIdentifiers(+ sfc,+ options.templateOptions,+ ) if (vModelIds.size) { const toDemote = new Set<string>() for (const id of vModelIds) {packages/compiler-sfc/src/compileTemplate.tsindex b043cf813..6c8ad3988 100644@@ -1,14 +1,11 @@-import {- type CodegenResult,- type CompilerError,- type CompilerOptions,- type ElementNode,- type NodeTransform,- NodeTypes,- type ParserOptions,- type RawSourceMap,- type RootNode,- createRoot,+import type {+ CodegenResult,+ CompilerError,+ CompilerOptions,+ NodeTransform,+ ParserOptions,+ RawSourceMap,+ RootNode, } from '@vue/compiler-core' import { SourceMapConsumer, SourceMapGenerator } from 'source-map-js' import {@@ -28,6 +25,7 @@ import * as CompilerSSR from '@vue/compiler-ssr' import consolidate from '@vue/consolidate' import { warnOnce } from './warn' import { genCssVarsFromList } from './style/cssVars'+import { resolveTemplateAST } from './template/resolveTemplateAST' export interface TemplateCompiler { compile(source: string | RootNode, options: CompilerOptions): CodegenResult@@ -211,21 +209,12 @@ function doCompileTemplate({ inAST = undefined } - if (inAST?.transformed) {- // If input AST has already been transformed, then it cannot be reused.- // We need to parse a fresh one. Can't just use `source` here since we need- // the AST location info to be relative to the entire SFC.- const newAST = (ssr ? CompilerDOM : compiler).parse(inAST.source, {- prefixIdentifiers: true,- ...compilerOptions,- parseMode: 'sfc',- onError: e => errors.push(e),- })- const template = newAST.children.find(- node => node.type === NodeTypes.ELEMENT && node.tag === 'template',- ) as ElementNode- inAST = createRoot(template.children, inAST.source)- }+ inAST = resolveTemplateAST(inAST, {+ compiler,+ compilerOptions,+ ssr,+ onError: e => errors.push(e),+ }) let { code, ast, preamble, map } = compiler.compile(inAST || source, { mode: 'module',packages/compiler-sfc/src/script/importUsageCheck.tsindex 9c087b466..fa16a1adc 100644@@ -1,4 +1,5 @@ import type { SFCDescriptor } from '../parse'+import type { SFCTemplateCompileOptions } from '../compileTemplate' import { type ExpressionNode, NodeTypes,@@ -8,36 +9,57 @@ import { parserOptions, walkIdentifiers, } from '@vue/compiler-dom'+import type { LRUCache } from 'lru-cache' import { createCache } from '../cache' import { camelize, capitalize, isBuiltInDirective } from '@vue/shared'+import { resolveTemplateAST } from '../template/resolveTemplateAST'++type TemplateOptions = Pick<+ SFCTemplateCompileOptions,+ 'compiler' | 'compilerOptions' | 'ssr'+> /** * Check if an import is used in the SFC's template. This is used to determine * the properties that should be included in the object returned from setup() * when not using inline mode. */-export function isImportUsed(local: string, sfc: SFCDescriptor): boolean {- return resolveTemplateUsedIdentifiers(sfc).has(local)+export function isImportUsed(+ local: string,+ sfc: SFCDescriptor,+ options?: TemplateOptions,+): boolean {+ return resolveTemplateUsedIdentifiers(sfc, options).has(local) } -const templateAnalysisCache = createCache<{+type TemplateAnalysisResult = { usedIds?: Set<string> vModelIds: Set<string>-}>()+}++export const templateAnalysisCache:+ | Map<string, TemplateAnalysisResult>+ | LRUCache<string, TemplateAnalysisResult> =+ createCache<TemplateAnalysisResult>() export function resolveTemplateVModelIdentifiers( sfc: SFCDescriptor,+ options?: TemplateOptions, ): Set<string> {- return resolveTemplateAnalysisResult(sfc, false).vModelIds+ return resolveTemplateAnalysisResult(sfc, false, options).vModelIds } -function resolveTemplateUsedIdentifiers(sfc: SFCDescriptor): Set<string> {- return resolveTemplateAnalysisResult(sfc).usedIds!+function resolveTemplateUsedIdentifiers(+ sfc: SFCDescriptor,+ options?: TemplateOptions,+): Set<string> {+ return resolveTemplateAnalysisResult(sfc, true, options).usedIds! } function resolveTemplateAnalysisResult( sfc: SFCDescriptor, collectUsedIds = true,+ options?: TemplateOptions, ): { usedIds?: Set<string> vModelIds: Set<string>@@ -53,7 +75,15 @@ function resolveTemplateAnalysisResult( const ids = collectUsedIds ? new Set<string>() : undefined const vModelIds = new Set<string>() - ast!.children.forEach(walk)+ const root = resolveTemplateAST(ast, {+ compiler: options?.compiler,+ compilerOptions: options?.compilerOptions,+ ssr: options?.ssr,+ // ignore errors since they were already reported by the SFC parser+ onError: () => {},+ })++ root!.children.forEach(walk) function walk(node: TemplateChildNode) { switch (node.type) {packages/compiler-sfc/src/template/resolveTemplateAST.tsnew file mode 100644index 000000000..b2897e56d@@ -0,0 +1,40 @@+import {+ type CompilerError,+ type ElementNode,+ NodeTypes,+ type ParserOptions,+ type RootNode,+ createRoot,+} from '@vue/compiler-core'+import * as CompilerDOM from '@vue/compiler-dom'++interface TemplateParser {+ parse(template: string, options: ParserOptions): RootNode+}++export function resolveTemplateAST(+ inAST: RootNode | undefined,+ options: {+ compiler?: TemplateParser+ compilerOptions?: ParserOptions+ ssr?: boolean+ onError: (error: CompilerError) => void+ },+): RootNode | undefined {+ if (!inAST?.transformed) {+ return inAST+ }++ // Parse the full SFC source to preserve template locations relative to it.+ const { compiler = CompilerDOM, compilerOptions, ssr, onError } = options+ const newAST = (ssr ? CompilerDOM : compiler).parse(inAST.source, {+ prefixIdentifiers: true,+ ...compilerOptions,+ parseMode: 'sfc',+ onError,+ })+ const template = newAST.children.find(+ node => node.type === NodeTypes.ELEMENT && node.tag === 'template',+ ) as ElementNode+ return createRoot(template.children, inAST.source)+}