Repository navigation
fix(vite): scan top-level imports with Vite's native parser #11634
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| import { describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| // parseAst (Oxc) rejected → the Babel fallback must produce identical records. | ||
| vi.mock('vite', async (importOriginal) => { | ||
| const original = await importOriginal<typeof import('vite')>(); | ||
| return { | ||
| ...original, | ||
| parseAst: () => { | ||
| throw new Error('simulated Oxc parse failure'); | ||
| }, | ||
| }; | ||
| }); | ||
|
|
||
| const { collectTopLevelImportRecords } = await import('./websocket-served-module-helpers.js'); | ||
| const { ensureNativeScriptModuleBindings } = await import('./websocket-module-bindings.js'); | ||
|
|
||
| describe('collectTopLevelImportRecords (Babel fallback)', () => { | ||
| it('produces the same records when parseAst throws', () => { | ||
| const code = `const s = "héllo→";\nimport def, { a, b as c, "d-e" as f } from "pkg";\nimport type { T } from "./t";`; | ||
| const records = collectTopLevelImportRecords(code); | ||
| expect(records).toHaveLength(2); | ||
| expect(records[0].source).toBe('pkg'); | ||
| expect(records[0].text).toBe(`import def, { a, b as c, "d-e" as f } from "pkg";`); | ||
| expect(records[0].hasOnlyNamedSpecifiers).toBe(false); | ||
| expect(records[0].namedBindings).toEqual([ | ||
| { importedName: 'a', text: 'a' }, | ||
| { importedName: 'b', text: 'b as c' }, | ||
| { importedName: 'd-e', text: '"d-e" as f' }, | ||
| ]); | ||
| expect(records[1].source).toBe('./t'); | ||
| }); | ||
|
|
||
| it('still rewrites a vendor plugin import through the Babel fallback', () => { | ||
| const input = `import { defineStore } from "pinia";\nexport const useServices = defineStore('services', () => ({}));\n`; | ||
| const out = ensureNativeScriptModuleBindings(input); | ||
| expect(out).not.toMatch(/from\s+["']pinia["']/); | ||
| expect(out).toContain('globalThis.__nsVendorRegistry'); | ||
| }); | ||
| }); | ||
|
|
||
| const { collectStaticImportDefaultIntents } = await import('./websocket-served-module-helpers.js'); | ||
|
|
||
| describe('collectStaticImportDefaultIntents (Babel fallback)', () => { | ||
| it('produces the same intents when parseAst throws', () => { | ||
| const code = `import def, { a } from "x";\nimport { b } from "y";\nimport type { T } from "./t";`; | ||
| expect(collectStaticImportDefaultIntents(code)).toEqual([ | ||
| { src: 'x', wantsDefault: true }, | ||
| { src: 'y', wantsDefault: false }, | ||
| { src: './t', wantsDefault: false }, | ||
| ]); | ||
| }); | ||
| }); |
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -1,7 +1,11 @@ | ||||||||||||||||||||||
| import { parse as babelParse } from '@babel/parser'; | ||||||||||||||||||||||
| import traverse from '@babel/traverse'; | ||||||||||||||||||||||
| import * as t from '@babel/types'; | ||||||||||||||||||||||
| import { existsSync, readFileSync } from 'fs'; | ||||||||||||||||||||||
| import * as path from 'path'; | ||||||||||||||||||||||
| import { parseAst } from 'vite'; | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| const babelTraverse: any = (traverse as any)?.default || (traverse as any); | ||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit: the Babel fallback is repeated in three places (here, in |
||||||||||||||||||||||
|
|
||||||||||||||||||||||
| import * as PAT from './constants.js'; | ||||||||||||||||||||||
| import { isDeepCoreSubpath } from './core-sanitize.js'; | ||||||||||||||||||||||
|
|
@@ -130,41 +134,90 @@ export type TopLevelImportRecord = { | |||||||||||||||||||||
| namedBindings: Array<{ importedName: string; text: string }>; | ||||||||||||||||||||||
| }; | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| /** | ||||||||||||||||||||||
| * Top-level statements via Vite's native (Oxc) parser. Babel's block-comment | ||||||||||||||||||||||
| * line tracking rescans to the next line break for every comment, so long | ||||||||||||||||||||||
| * minified lines with many comments parse quadratically. Returns null when | ||||||||||||||||||||||
| * Oxc rejects the code so callers can fall back to Babel. | ||||||||||||||||||||||
| */ | ||||||||||||||||||||||
| export function parseTopLevelStatements(code: string): any[] | null { | ||||||||||||||||||||||
| try { | ||||||||||||||||||||||
| const ast = parseAst(code, { lang: 'tsx' }) as any; | ||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Perf:
These scans run ~6–8× per
|
||||||||||||||||||||||
| return Array.isArray(ast?.body) ? ast.body : null; | ||||||||||||||||||||||
| } catch { | ||||||||||||||||||||||
| return null; | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| /** | ||||||||||||||||||||||
| * Static import sources and whether each asks for a default binding. | ||||||||||||||||||||||
| */ | ||||||||||||||||||||||
| export function collectStaticImportDefaultIntents(code: string): Array<{ src: string; wantsDefault: boolean }> { | ||||||||||||||||||||||
| const body = parseTopLevelStatements(code); | ||||||||||||||||||||||
| if (body) { | ||||||||||||||||||||||
| const imports: Array<{ src: string; wantsDefault: boolean }> = []; | ||||||||||||||||||||||
| for (const node of body) { | ||||||||||||||||||||||
| if (node?.type !== 'ImportDeclaration' || typeof node.source?.value !== 'string') continue; | ||||||||||||||||||||||
| imports.push({ | ||||||||||||||||||||||
| src: node.source.value, | ||||||||||||||||||||||
| wantsDefault: Array.isArray(node.specifiers) && node.specifiers.some((s: any) => s?.type === 'ImportDefaultSpecifier'), | ||||||||||||||||||||||
| }); | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
| return imports; | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
| const ast = babelParse(code, { | ||||||||||||||||||||||
| sourceType: 'module', | ||||||||||||||||||||||
| plugins: MODULE_IMPORT_ANALYSIS_PLUGINS, | ||||||||||||||||||||||
| }) as any; | ||||||||||||||||||||||
| const imports: Array<{ src: string; wantsDefault: boolean }> = []; | ||||||||||||||||||||||
| babelTraverse(ast, { | ||||||||||||||||||||||
| ImportDeclaration(p: any) { | ||||||||||||||||||||||
| const src = p.node.source.value; | ||||||||||||||||||||||
| if (typeof src !== 'string') return; | ||||||||||||||||||||||
| imports.push({ src, wantsDefault: p.node.specifiers.some((s: any) => s.type === 'ImportDefaultSpecifier') }); | ||||||||||||||||||||||
| }, | ||||||||||||||||||||||
| }); | ||||||||||||||||||||||
| return imports; | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| export function collectTopLevelImportRecords(code: string): TopLevelImportRecord[] { | ||||||||||||||||||||||
| if (!code || typeof code !== 'string' || !/\bimport\b/.test(code)) { | ||||||||||||||||||||||
| return []; | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| try { | ||||||||||||||||||||||
| const ast = babelParse(code, { | ||||||||||||||||||||||
| sourceType: 'module', | ||||||||||||||||||||||
| plugins: MODULE_IMPORT_ANALYSIS_PLUGINS, | ||||||||||||||||||||||
| }) as any; | ||||||||||||||||||||||
| const body = ast?.program?.body; | ||||||||||||||||||||||
| if (!Array.isArray(body)) { | ||||||||||||||||||||||
| return []; | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| return body | ||||||||||||||||||||||
| .filter((node: any) => t.isImportDeclaration(node) && typeof node.start === 'number' && typeof node.end === 'number' && typeof node.source?.value === 'string') | ||||||||||||||||||||||
| .map((node: any) => ({ | ||||||||||||||||||||||
| start: node.start as number, | ||||||||||||||||||||||
| end: node.end as number, | ||||||||||||||||||||||
| text: code.slice(node.start as number, node.end as number), | ||||||||||||||||||||||
| source: node.source.value as string, | ||||||||||||||||||||||
| hasOnlyNamedSpecifiers: Array.isArray(node.specifiers) && node.specifiers.length > 0 && node.specifiers.every((spec: any) => t.isImportSpecifier(spec)), | ||||||||||||||||||||||
| namedBindings: Array.isArray(node.specifiers) | ||||||||||||||||||||||
| ? node.specifiers | ||||||||||||||||||||||
| .filter((spec: any) => t.isImportSpecifier(spec) && typeof spec.start === 'number' && typeof spec.end === 'number') | ||||||||||||||||||||||
| .map((spec: any) => ({ | ||||||||||||||||||||||
| importedName: t.isIdentifier(spec.imported) ? spec.imported.name : String(spec.imported?.value || ''), | ||||||||||||||||||||||
| text: code.slice(spec.start as number, spec.end as number), | ||||||||||||||||||||||
| })) | ||||||||||||||||||||||
| : [], | ||||||||||||||||||||||
| })); | ||||||||||||||||||||||
| } catch { | ||||||||||||||||||||||
| let body = parseTopLevelStatements(code); | ||||||||||||||||||||||
| if (!body) { | ||||||||||||||||||||||
| try { | ||||||||||||||||||||||
| body = | ||||||||||||||||||||||
| ( | ||||||||||||||||||||||
| babelParse(code, { | ||||||||||||||||||||||
| sourceType: 'module', | ||||||||||||||||||||||
| plugins: MODULE_IMPORT_ANALYSIS_PLUGINS, | ||||||||||||||||||||||
| }) as any | ||||||||||||||||||||||
| )?.program?.body ?? null; | ||||||||||||||||||||||
| } catch {} | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
| if (!Array.isArray(body)) { | ||||||||||||||||||||||
| return []; | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| return body | ||||||||||||||||||||||
| .filter((node: any) => node?.type === 'ImportDeclaration' && typeof node.start === 'number' && typeof node.end === 'number' && typeof node.source?.value === 'string') | ||||||||||||||||||||||
| .map((node: any) => ({ | ||||||||||||||||||||||
| start: node.start as number, | ||||||||||||||||||||||
| end: node.end as number, | ||||||||||||||||||||||
| text: code.slice(node.start as number, node.end as number), | ||||||||||||||||||||||
| source: node.source.value as string, | ||||||||||||||||||||||
| hasOnlyNamedSpecifiers: Array.isArray(node.specifiers) && node.specifiers.length > 0 && node.specifiers.every((spec: any) => spec?.type === 'ImportSpecifier'), | ||||||||||||||||||||||
| namedBindings: Array.isArray(node.specifiers) | ||||||||||||||||||||||
| ? node.specifiers | ||||||||||||||||||||||
| .filter((spec: any) => spec?.type === 'ImportSpecifier' && typeof spec.start === 'number' && typeof spec.end === 'number') | ||||||||||||||||||||||
| .map((spec: any) => ({ | ||||||||||||||||||||||
| importedName: spec.imported?.type === 'Identifier' ? spec.imported.name : String(spec.imported?.value || ''), | ||||||||||||||||||||||
| text: code.slice(spec.start as number, spec.end as number), | ||||||||||||||||||||||
| })) | ||||||||||||||||||||||
| : [], | ||||||||||||||||||||||
| })); | ||||||||||||||||||||||
| } | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| export function hoistTopLevelStaticImports(code: string): string { | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nit: machine-specific timings belong in the PR description rather than the source (
tools/notes/CodeComments.md). Also, the wall-clock< 2sassertions on 20 MB+ inputs are fine today (~0.05 s) but timing-based; asserting the Oxc path was taken would be sturdier. Small gaps: theimport typetest only checkssource, not that bindings still seeisTypeOnly === true; and a few imports sit mid-file (:48,:49,:116, and a mid-fileawait importinwebsocket-import-records-fallback.spec.ts:42).