before_code
stringlengths
14
465k
reviewer_comment
stringlengths
16
64.5k
after_code
stringlengths
9
467k
diff_context
stringlengths
0
97k
file_path
stringlengths
5
226
comment_line
int32
0
26
language
stringclasses
37 values
quality_score
float32
0.07
1
comment_type
stringclasses
9 values
comment_length
int32
16
64.5k
before_lines
int32
1
17.2k
after_lines
int32
1
12.1k
is_negative
bool
2 classes
pr_title
stringlengths
1
308
pr_number
int32
1
299k
repo_name
stringclasses
533 values
repo_stars
int64
321
419k
repo_language
stringclasses
27 values
reviewer_username
stringlengths
0
39
author_username
stringlengths
2
39
// we are fine with the bug for now because it's not a common case node.imports.clear() } /** * Extracts the inlined source map from the module code and returns the decoded * source map. If the source map is not inlined, it will return null. * @param id Resolved module ID */ getModuleSourceMa...
```suggestion mod.map = new DecodedMap(JSON.parse(decodeBase64(mapString)), mod.file) return mod.map ```
// we are fine with the bug for now because it's not a common case node.imports.clear() } /** * Extracts the inlined source map from the module code and returns the decoded * source map. If the source map is not inlined, it will return null. * @param id Resolved module ID */ getModuleSourceMa...
@@ -108,12 +108,18 @@ export class EvaluatedModules { if (!mod) return null if (mod.map) return mod.map if (!mod.meta || !('code' in mod.meta)) return null + const pattern = `//# ${SOURCEMAPPING_URL}=data:application/json;base64,` + const lastIndex = mod.meta.code.lastIndexOf(pattern) + if (last...
packages/vite/src/module-runner/evaluatedModules.ts
26
TypeScript
1
suggestion
115
51
51
false
fix(module-runner): prevent crash when sourceMappingURL pattern appears in string literals
20,554
vitejs/vite
78,557
TypeScript
sapphi-red
Copilot
' at <root>/fixtures/has-error-first-comment.ts:2:17', ) }) it('deep stacktrace', async ({ runner, server }) => { const methodError = await getError(async () => { const mod = await runner.import('/fixtures/has-error-deep.ts') mod.main() }) expect(serializeStackDeep(server, meth...
@copilot add `expect(serializeStackDeep(...)).toEqual(...)` here
' at <root>/fixtures/has-error-first-comment.ts:2:17', ) }) it('deep stacktrace', async ({ runner, server }) => { const methodError = await getError(async () => { const mod = await runner.import('/fixtures/has-error-deep.ts') mod.main() }) expect(serializeStackDeep(server, meth...
@@ -93,4 +93,16 @@ describe('module runner initialization', async () => { ' at Module.main (<root>/fixtures/has-error-deep.ts:6:3)', ]) }) + + it('should not crash when sourceMappingURL pattern appears in string literals', async ({ + runner, + }) => { + const mod = await runner.import('/fixtur...
packages/vite/src/node/ssr/runtime/__tests__/server-source-maps.spec.ts
26
TypeScript
0.357
suggestion
64
29
33
false
fix(module-runner): prevent crash when sourceMappingURL pattern appears in string literals
20,554
vitejs/vite
78,557
TypeScript
sapphi-red
Copilot
referencedAssets: Set<string> watchedFiles: string[] } type WorkerBundleAsset = { fileName: string /** @deprecated */ originalFileName: string | null originalFileNames: string[] source: string | Uint8Array } class WorkerOutputCache { /** * worker bundle information for each input id * used to bu...
Looks like we can use the `WorkerBundle` type here
referencedAssets: Set<string> watchedFiles: string[] } type WorkerBundleAsset = { fileName: string /** @deprecated */ originalFileName: string | null originalFileNames: string[] source: string | Uint8Array } class WorkerOutputCache { /** * worker bundle information for each input id * used to bu...
@@ -30,17 +40,119 @@ type WorkerBundleAsset = { source: string | Uint8Array } -interface WorkerCache { - // save worker all emit chunk avoid rollup make the same asset unique. - assets: Map<string, WorkerBundleAsset> +class WorkerOutputCache { + /** + * worker bundle information for each input id + * used ...
packages/vite/src/node/plugins/worker.ts
26
TypeScript
0.857
suggestion
50
51
51
false
perf(worker): rebuild only when affected
20,559
vitejs/vite
78,557
TypeScript
bluwy
sapphi-red
import path from 'node:path' import fs from 'node:fs' import { performance } from 'node:perf_hooks' import { cac } from 'cac' import colors from 'picocolors' import { VERSION } from './constants' import type { BuildEnvironmentOptions } from './build' import type { ServerOptions } from './server' import type { CLIShortc...
@copilot return boolean in this function so that we don't need to mock things in the unit test.
import path from 'node:path' import fs from 'node:fs' import { performance } from 'node:perf_hooks' import { cac } from 'cac' import colors from 'picocolors' import { VERSION } from './constants' import type { BuildEnvironmentOptions } from './build' import type { ServerOptions } from './server' import type { CLIShortc...
@@ -12,6 +12,35 @@ import { createLogger } from './logger' import { resolveConfig } from './config' import type { InlineConfig } from './config' +/** + * Check if the current Node.js version is supported + */ +export function checkNodeVersion(): void {
packages/vite/src/node/cli.ts
18
TypeScript
0.143
nitpick
95
43
43
false
feat(cli): add Node.js version warning for unsupported versions
20,638
vitejs/vite
78,557
TypeScript
sapphi-red
Copilot
import { afterEach, beforeEach, describe, expect, test } from 'vitest' import { checkNodeVersion } from '../cli' describe('CLI Node.js version checking', () => { let originalNodeVersion: string beforeEach(() => { originalNodeVersion = process.versions.node }) afterEach(() => { // Restore original ver...
@copilot change this to a table based test.
import { describe, expect, test } from 'vitest' import { checkNodeVersion } from '../cli' describe('CLI Node.js version checking', () => { test.each([ // Unsupported versions ['18.20.0', false], ['20.18.5', false], ['22.11.0', false], // Supported versions ['20.19.0', true], ['20.20.1', t...
@@ -0,0 +1,89 @@ +import { afterEach, beforeEach, describe, expect, test } from 'vitest' +import { checkNodeVersion } from '../cli' + +describe('CLI Node.js version checking', () => { + let originalNodeVersion: string + + beforeEach(() => { + originalNodeVersion = process.versions.node + }) + + afterEach(() => {...
packages/vite/src/node/__tests__/cli.spec.ts
25
TypeScript
0.286
suggestion
43
50
21
false
feat(cli): add Node.js version warning for unsupported versions
20,638
vitejs/vite
78,557
TypeScript
sapphi-red
Copilot
import path from 'node:path' import fs from 'node:fs' import { performance } from 'node:perf_hooks' import { cac } from 'cac' import colors from 'picocolors' import { VERSION } from './constants' import type { BuildEnvironmentOptions } from './build' import type { ServerOptions } from './server' import type { CLIShortc...
@copilot receive `process.versions.node` as a parameter to avoid mocking `process.versions.node`.
import path from 'node:path' import fs from 'node:fs' import { performance } from 'node:perf_hooks' import { cac } from 'cac' import colors from 'picocolors' import { VERSION } from './constants' import type { BuildEnvironmentOptions } from './build' import type { ServerOptions } from './server' import type { CLIShortc...
@@ -12,6 +12,36 @@ import { createLogger } from './logger' import { resolveConfig } from './config' import type { InlineConfig } from './config' +/** + * Check if the current Node.js version is supported + * @returns true if the version is supported, false otherwise + */ +export function checkNodeVersion(): boolean...
packages/vite/src/node/cli.ts
20
TypeScript
0.571
suggestion
97
45
45
false
feat(cli): add Node.js version warning for unsupported versions
20,638
vitejs/vite
78,557
TypeScript
sapphi-red
Copilot
import { describe, expect, test } from 'vitest' import { checkNodeVersion } from '../cli' describe('CLI Node.js version checking', () => { test.each([ // Unsupported versions ['18.20.0', false], ['20.18.5', false], ['22.11.0', false], // Supported versions ['20.19.0', true], ['20.20.1', t...
```suggestion ])('should return %1 for Node.js version %0', (version, expected) => { ```
import { describe, expect, test } from 'vitest' import { checkNodeVersion } from '../cli' describe('CLI Node.js version checking', () => { test.each([ // Unsupported versions ['18.20.0', false], ['20.18.5', false], ['22.11.0', false], // Supported versions ['20.19.0', true], ['20.20.1', t...
@@ -0,0 +1,20 @@ +import { describe, expect, test } from 'vitest' +import { checkNodeVersion } from '../cli' + +describe('CLI Node.js version checking', () => { + test.each([ + // Unsupported versions + ['18.20.0', false], + ['20.18.5', false], + ['22.11.0', false], + // Supported versions + ['20.19....
packages/vite/src/node/__tests__/cli.spec.ts
16
TypeScript
0.857
suggestion
92
21
21
false
feat(cli): add Node.js version warning for unsupported versions
20,638
vitejs/vite
78,557
TypeScript
sapphi-red
Copilot
import type { CLIShortcut } from './shortcuts' import type { LogLevel } from './logger' import { createLogger } from './logger' import { resolveConfig } from './config' import type { InlineConfig } from './config' /** * Check if the current Node.js version is supported * @param nodeVersion - The Node.js version stri...
```suggestion export function checkNodeVersion(nodeVersion: string): boolean { const currentVersion = nodeVersion.split('.') const major = parseInt(currentVersion[0], 10) const minor = parseInt(currentVersion[1], 10) const isSupported = (major === 20 && minor >= 19) || (major === 22 && minor >= 1...
import type { CLIShortcut } from './shortcuts' import type { LogLevel } from './logger' import { createLogger } from './logger' import { resolveConfig } from './config' import type { InlineConfig } from './config' export function checkNodeVersion(nodeVersion: string): boolean { const currentVersion = nodeVersion.spl...
@@ -12,6 +12,37 @@ import { createLogger } from './logger' import { resolveConfig } from './config' import type { InlineConfig } from './config' +/** + * Check if the current Node.js version is supported + * @param nodeVersion - The Node.js version string (e.g., '20.19.0') + * @returns true if the version is suppor...
packages/vite/src/node/cli.ts
26
TypeScript
1
suggestion
373
51
51
false
feat(cli): add Node.js version warning for unsupported versions
20,638
vitejs/vite
78,557
TypeScript
sapphi-red
Copilot
import path from 'node:path' import fs from 'node:fs' import { performance } from 'node:perf_hooks' import { cac } from 'cac' import colors from 'picocolors' import { VERSION } from './constants' import type { BuildEnvironmentOptions } from './build' import type { ServerOptions } from './server' import type { CLIShortc...
```suggestion const isSupported = (major === 20 && minor >= 19) || (major === 22 && minor >= 12) || major > 22 ```
import path from 'node:path' import fs from 'node:fs' import { performance } from 'node:perf_hooks' import { cac } from 'cac' import colors from 'picocolors' import { VERSION } from './constants' import type { BuildEnvironmentOptions } from './build' import type { ServerOptions } from './server' import type { CLIShortc...
@@ -12,6 +12,28 @@ import { createLogger } from './logger' import { resolveConfig } from './config' import type { InlineConfig } from './config' +export function checkNodeVersion(nodeVersion: string): boolean { + const currentVersion = nodeVersion.split('.') + const major = parseInt(currentVersion[0], 10) + cons...
packages/vite/src/node/cli.ts
22
TypeScript
1
suggestion
123
47
47
false
feat(cli): add Node.js version warning for unsupported versions
20,638
vitejs/vite
78,557
TypeScript
sapphi-red
Copilot
if (count >= start) { for (let j = i - range; j <= i + range || end > count; j++) { if (j < 0 || j >= lines.length) continue const line = j + 1 const lineLength = lines[j].length const pad = Math.max(start - (count - lineLength), 0) const underlineLength = Math.max( ...
The magic number 3 represents the length of the ellipsis prefix ('...'). Consider extracting this to a named constant like `ELLIPSIS_LENGTH` to improve code clarity and maintainability. ```suggestion underlinePad = Math.max(0, pad - startIdx) + (startIdx > 0 ? ELLIPSIS.length : 0) } cons...
count += lines[i].length if (count >= start) { for (let j = i - range; j <= i + range || end > count; j++) { if (j < 0 || j >= lines.length) continue const line = j + 1 const lineLength = lines[j].length const pad = Math.max(start - (count - lineLength), 0) const un...
@@ -522,28 +524,50 @@ export function generateCodeFrame( for (let j = i - range; j <= i + range || end > count; j++) { if (j < 0 || j >= lines.length) continue const line = j + 1 + const lineLength = lines[j].length + const pad = Math.max(start - (count - lineLength), 0) + ...
packages/vite/src/node/utils.ts
26
TypeScript
1
refactor
444
51
51
false
feat: support long lines in `generateCodeFrame`
20,640
vitejs/vite
78,557
TypeScript
Copilot
sapphi-red
throw message } } return terserPath } export function terserPlugin(config: ResolvedConfig): Plugin { const { maxWorkers, ...terserOptions } = config.build.terserOptions const makeWorker = () => new WorkerWithFallback( () => async ( terserPath: string, code: stri...
Throwing a plain object instead of an Error instance loses the error's prototype chain and stack trace. Consider using `throw new Error(e.message, { cause: e })` or creating a proper Error object with the necessary properties. ```suggestion // Wrap the error in an Error instance to preserve stack trace and ...
message.stack = e.stack + '\n' + message.stack throw message } } return terserPath } export function terserPlugin(config: ResolvedConfig): Plugin { const { maxWorkers, ...terserOptions } = config.build.terserOptions const makeWorker = () => new WorkerWithFallback( () => async...
@@ -47,10 +47,16 @@ export function terserPlugin(config: ResolvedConfig): Plugin { code: string, options: TerserMinifyOptions, ) => { - // test fails when using `import`. maybe related: https://github.com/nodejs/node/issues/43205 - // eslint-disable-next-line no-restrict...
packages/vite/src/node/plugins/terser.ts
26
TypeScript
1
suggestion
552
51
51
false
feat: generate code frame for parse errors thrown by terser
20,642
vitejs/vite
78,557
TypeScript
Copilot
sapphi-red
return null } // Lazy load worker. worker ||= makeWorker() const terserPath = loadTerserPath(config.root) try { const res = await worker.run(terserPath, code, { safari10: true, ...terserOptions, sourceMap: !!outputOptions.sourcemap, ...
The code assumes that `e.pos` exists on the error object, but this property may not be present on all Terser errors. Consider adding a check like `if (e.pos !== undefined)` before calling `generateCodeFrame`. ```suggestion e.frame = e.pos !== undefined ? generateCodeFrame(code, e.pos) : undefined ```
return null } // Lazy load worker. worker ||= makeWorker() const terserPath = pathToFileURL(loadTerserPath(config.root)).href try { const res = await worker.run(terserPath, code, { safari10: true, ...terserOptions, sourceMap: !!outputOptions....
@@ -100,16 +106,26 @@ export function terserPlugin(config: ResolvedConfig): Plugin { worker ||= makeWorker() const terserPath = loadTerserPath(config.root) - const res = await worker.run(terserPath, code, { - safari10: true, - ...terserOptions, - sourceMap: !!outputOptions.sour...
packages/vite/src/node/plugins/terser.ts
26
TypeScript
1
suggestion
309
36
40
false
feat: generate code frame for parse errors thrown by terser
20,642
vitejs/vite
78,557
TypeScript
Copilot
sapphi-red
) } else { const message = new Error(`terser failed to load:\n${e.message}`) message.stack = e.stack + '\n' + message.stack throw message } } return terserPath } export function terserPlugin(config: ResolvedConfig): Plugin { const { maxWorkers, ...terserOptions } = config.build.te...
Adding `await` here changes the function signature from synchronous to asynchronous, but the function is not declared as `async`. This will cause the function to return a Promise instead of the expected synchronous result.
'terser not found. Since Vite v3, terser has become an optional dependency. You need to install it.', ) } else { const message = new Error(`terser failed to load:\n${e.message}`) message.stack = e.stack + '\n' + message.stack throw message } } return terserPath } export func...
@@ -47,10 +47,16 @@ export function terserPlugin(config: ResolvedConfig): Plugin { code: string, options: TerserMinifyOptions, ) => { - // test fails when using `import`. maybe related: https://github.com/nodejs/node/issues/43205 - // eslint-disable-next-line no-restrict...
packages/vite/src/node/plugins/terser.ts
26
TypeScript
0.786
suggestion
222
51
51
false
feat: generate code frame for parse errors thrown by terser
20,642
vitejs/vite
78,557
TypeScript
Copilot
sapphi-red
'terser not found. Since Vite v3, terser has become an optional dependency. You need to install it.', ) } else { const message = new Error(`terser failed to load:\n${e.message}`) message.stack = e.stack + '\n' + message.stack throw message } } return terserPath } export func...
Should this line be moved out of the `try`? Since here it's trying to handle the errors from minifying.
throw new Error( 'terser not found. Since Vite v3, terser has become an optional dependency. You need to install it.', ) } else { const message = new Error(`terser failed to load:\n${e.message}`) message.stack = e.stack + '\n' + message.stack throw message } } return te...
@@ -47,10 +47,16 @@ export function terserPlugin(config: ResolvedConfig): Plugin { code: string, options: TerserMinifyOptions, ) => { - // test fails when using `import`. maybe related: https://github.com/nodejs/node/issues/43205 - // eslint-disable-next-line no-restrict...
packages/vite/src/node/plugins/terser.ts
26
TypeScript
1
suggestion
103
51
51
false
feat: generate code frame for parse errors thrown by terser
20,642
vitejs/vite
78,557
TypeScript
bluwy
sapphi-red
return null } // Lazy load worker. worker ||= makeWorker() const terserPath = loadTerserPath(config.root) try { const res = await worker.run(terserPath, code, { safari10: true, ...terserOptions, sourceMap: !!outputOptions.sourcemap, ...
```suggestion if (e.line !== undefined && e.col !== undefined) { e.loc = { file: chunk.fileName, line: e.line, column: e.col, } } if (e.pos !== undefined) { e.frame = generateCodeFrame(code, e.pos) } ``` Maybe we can do t...
return null } // Lazy load worker. worker ||= makeWorker() const terserPath = pathToFileURL(loadTerserPath(config.root)).href try { const res = await worker.run(terserPath, code, { safari10: true, ...terserOptions, sourceMap: !!outputOptions....
@@ -100,16 +106,27 @@ export function terserPlugin(config: ResolvedConfig): Plugin { worker ||= makeWorker() const terserPath = loadTerserPath(config.root) - const res = await worker.run(terserPath, code, { - safari10: true, - ...terserOptions, - sourceMap: !!outputOptions.sour...
packages/vite/src/node/plugins/terser.ts
26
TypeScript
1
suggestion
403
37
40
false
feat: generate code frame for parse errors thrown by terser
20,642
vitejs/vite
78,557
TypeScript
bluwy
sapphi-red
message.stack = e.stack + '\n' + message.stack throw message } } return terserPath } export function terserPlugin(config: ResolvedConfig): Plugin { const { maxWorkers, ...terserOptions } = config.build.terserOptions const makeWorker = () => new WorkerWithFallback( () => async...
Should this be handled in artichokie so it tries to rebuild the error object?
const message = new Error(`terser failed to load:\n${e.message}`) message.stack = e.stack + '\n' + message.stack throw message } } return terserPath } export function terserPlugin(config: ResolvedConfig): Plugin { const { maxWorkers, ...terserOptions } = config.build.terserOptions const ...
@@ -47,10 +47,16 @@ export function terserPlugin(config: ResolvedConfig): Plugin { code: string, options: TerserMinifyOptions, ) => { - // test fails when using `import`. maybe related: https://github.com/nodejs/node/issues/43205 - // eslint-disable-next-line no-restrict...
packages/vite/src/node/plugins/terser.ts
26
TypeScript
0.643
question
77
51
51
false
feat: generate code frame for parse errors thrown by terser
20,642
vitejs/vite
78,557
TypeScript
bluwy
sapphi-red
import { describe, expect, test } from 'vitest' import { parseAst } from 'rollup/parseAst' import { assetImportMetaUrlPlugin } from '../../plugins/assetImportMetaUrl' import { resolveConfig } from '../../config' import { PartialEnvironment } from '../../baseEnvironment' import { createCodeFilter } from '../../plugins/p...
@copilot remove this unit tests
import { describe, expect, test } from 'vitest' import { parseAst } from 'rollup/parseAst' import { assetImportMetaUrlPlugin } from '../../plugins/assetImportMetaUrl' import { resolveConfig } from '../../config' import { PartialEnvironment } from '../../baseEnvironment' async function createAssetImportMetaurlPluginTra...
packages/vite/src/node/__tests__/plugins/assetImportMetaUrl.spec.ts
1
TypeScript
0.286
refactor
31
26
26
false
fix: support multiline new URL(..., import.meta.url) expressions
20,644
vitejs/vite
78,557
TypeScript
sapphi-red
Copilot
// Test for multiline new URL(..., import.meta.url) expressions // This is a separate file to ensure the regex filter in assetImportMetaUrlPlugin // correctly detects and processes multiline expressions that span multiple lines. // The bug was that the filter regex didn't include the 's' flag, so multiline // expressio...
```suggestion export const multilineUrl = new URL( './nested/fragment.svg', import.meta.url, ) ``` @copilot a single test case is sufficient
// Test for multiline expressions // This is a separate file to ensure the regex filter in assetImportMetaUrlPlugin // correctly detects and processes multiline expressions that span multiple lines. export const multilineUrl = new URL( './nested/asset.png', import.meta.url, )
@@ -0,0 +1,21 @@ +// Test for multiline new URL(..., import.meta.url) expressions +// This is a separate file to ensure the regex filter in assetImportMetaUrlPlugin +// correctly detects and processes multiline expressions that span multiple lines. +// The bug was that the filter regex didn't include the 's' flag, so m...
playground/assets/multiline-import-meta-url.js
21
JavaScript
1
suggestion
154
22
9
false
fix: support multiline new URL(..., import.meta.url) expressions
20,644
vitejs/vite
78,557
TypeScript
sapphi-red
Copilot
} public clear(): void { this.hotModulesMap.clear() this.disposeMap.clear() this.pruneMap.clear() this.dataMap.clear() this.customListenersMap.clear() this.ctxToListenersMap.clear() } // After an HMR update, some modules are no longer imported on the page // but they may have left be...
```suggestion return fn(this.dataMap.get(path)) ``` Shouldn't this need to return the promise?
} public clear(): void { this.hotModulesMap.clear() this.disposeMap.clear() this.pruneMap.clear() this.dataMap.clear() this.customListenersMap.clear() this.ctxToListenersMap.clear() } // After an HMR update, some modules are no longer imported on the page // but they may have left be...
@@ -219,12 +219,14 @@ export class HMRClient { if (disposer) return disposer(this.dataMap.get(path)) }), ) - paths.forEach((path) => { - const fn = this.pruneMap.get(path) - if (fn) { - fn(this.dataMap.get(path)) - } - }) + await Promise.all( + paths.map((path) =...
packages/vite/src/shared/hmr.ts
26
TypeScript
1
question
105
51
51
false
fix(hmr): wait for `import.meta.hot.prune` callbacks to complete before running other HMRs
20,698
vitejs/vite
78,557
TypeScript
bluwy
sapphi-red
import fs from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import spawn from 'cross-spawn' import mri from 'mri' import * as prompts from '@clack/prompts' import colors from 'picocolors' const { blue, blueBright, cyan, green, greenBright, magenta, red, redBright, r...
one thing that's missing is also using [eslint-plugin-react-hooks@6.0.0-rc.2](https://www.npmjs.com/package/eslint-plugin-react-hooks/v/6.0.0-rc.2). Version 6 will include compiler diagnostics as part of the plugin by default.
return content.replace( /"@vitejs\/plugin-react": ".+?"/, `"@vitejs/plugin-react-swc": "^${reactSwcPluginVersion}"`, ) }) editFile( path.resolve(root, `vite.config.${isTs ? 'ts' : 'js'}`), (content) => { return content.replace('@vitejs/plugin-react', '@vitejs/plugin-react-swc') ...
@@ -639,6 +657,62 @@ function setupReactSwc(root: string, isTs: boolean) { return content.replace('@vitejs/plugin-react', '@vitejs/plugin-react-swc') }, ) + updateReactCompilerReadme( + root, + 'The React Compiler is currently not compatible with SWC. See [this issue](https://github.com/vitejs/vit...
packages/create-vite/src/index.ts
26
TypeScript
0.357
style
226
767
51
false
feat(create-vite): support React Compiler
20,704
vitejs/vite
78,557
TypeScript
poteto
ArnaudBarre
react({ babel: { plugins: [['babel-plugin-react-compiler']], }, }), ],`, ) }, ) updateReactCompilerReadme( root, 'The React Compiler is enabled on this template. See [this documentation](https://react.dev/learn/react-compiler) for more information.', ) } function u...
```suggestion const compilerSectionEnd = content.indexOf('\n## ', bodyStart) if (h2Start === -1 || bodyStart === -1 || compilerSectionEnd === -1) { console.warn('Could not update compiler section in README.md') return content } return content.replace( content.slice(bodyStart + 2, compi...
setupReactCompiler(root, template.endsWith('-ts')) } if (immediate) { install(root, pkgManager) start(root, pkgManager) } else { let doneMessage = '' const cdProjectName = path.relative(cwd, root) doneMessage += `Done. Now run:\n` if (root !== cwd) { doneMessage += `\n cd ${ ...
@@ -639,6 +657,62 @@ function setupReactSwc(root: string, isTs: boolean) { return content.replace('@vitejs/plugin-react', '@vitejs/plugin-react-swc') }, ) + updateReactCompilerReadme( + root, + 'The React Compiler is currently not compatible with SWC. See [this issue](https://github.com/vitejs/vit...
packages/create-vite/src/index.ts
26
TypeScript
1
suggestion
343
51
51
false
feat(create-vite): support React Compiler
20,704
vitejs/vite
78,557
TypeScript
bluwy
ArnaudBarre
} } else { Object.values(os.networkInterfaces()) .flatMap((nInterface) => nInterface ?? []) .filter((detail) => detail.address && detail.family === 'IPv4') .forEach((detail) => { let host = detail.address.replace('127.0.0.1', hostname.name) // ipv6 host if (host.inclu...
```suggestion return new crypto.X509Certificate(cert) ``` I think this conversion is handled internally by `X509Certificate`.
const local: string[] = [] const network: string[] = [] const protocol = options.https ? 'https' : 'http' const port = address.port const base = config.rawBase === './' || config.rawBase === '' ? '/' : config.rawBase if (hostname.host !== undefined && !wildcardHosts.has(hostname.host)) { let hostn...
@@ -1045,19 +1049,27 @@ export function resolveServerUrls( }) } - const cert = - httpsOptions?.cert && !Array.isArray(httpsOptions.cert) - ? new crypto.X509Certificate(httpsOptions.cert) - : undefined - const hostnameFromCert = cert?.subjectAltName - ? extractHostnamesFromSubjectAltName(ce...
packages/vite/src/node/utils.ts
26
TypeScript
1
suggestion
138
51
51
false
feat(utils): support multiple certificates in resolveServerUrls
20,707
vitejs/vite
78,557
TypeScript
sapphi-red
monam2
let host = detail.address.replace('127.0.0.1', hostname.name) // ipv6 host if (host.includes(':')) { host = `[${host}]` } const url = `${protocol}://${host}:${port}${base}` if (detail.address.includes('127.0.0.1')) { local.push(url) } else { ...
```suggestion cert?.subjectAltName ```
config.rawBase === './' || config.rawBase === '' ? '/' : config.rawBase if (hostname.host !== undefined && !wildcardHosts.has(hostname.host)) { let hostnameName = hostname.name // ipv6 host if (hostnameName.includes(':')) { hostnameName = `[${hostnameName}]` } const address = `${protoco...
@@ -1045,19 +1049,27 @@ export function resolveServerUrls( }) } - const cert = - httpsOptions?.cert && !Array.isArray(httpsOptions.cert) - ? new crypto.X509Certificate(httpsOptions.cert) - : undefined - const hostnameFromCert = cert?.subjectAltName - ? extractHostnamesFromSubjectAltName(ce...
packages/vite/src/node/utils.ts
26
TypeScript
0.786
suggestion
46
51
51
false
feat(utils): support multiple certificates in resolveServerUrls
20,707
vitejs/vite
78,557
TypeScript
sapphi-red
monam2
host = `[${host}]` } const url = `${protocol}://${host}:${port}${base}` if (detail.address.includes('127.0.0.1')) { local.push(url) } else { network.push(url) } }) } const certs = httpsOptions?.cert ? arraify(httpsOptions.cert) : [] cons...
Would you extract this part as a function so that we don't have to use mocks in the tests?
let hostnameName = hostname.name // ipv6 host if (hostnameName.includes(':')) { hostnameName = `[${hostnameName}]` } const address = `${protocol}://${hostnameName}:${port}${base}` if (loopbackHosts.has(hostname.host)) { local.push(address) } else { network.push(address) ...
@@ -1045,19 +1049,27 @@ export function resolveServerUrls( }) } - const cert = - httpsOptions?.cert && !Array.isArray(httpsOptions.cert) - ? new crypto.X509Certificate(httpsOptions.cert) - : undefined - const hostnameFromCert = cert?.subjectAltName - ? extractHostnamesFromSubjectAltName(ce...
packages/vite/src/node/utils.ts
26
TypeScript
0.357
refactor
90
51
51
false
feat(utils): support multiple certificates in resolveServerUrls
20,707
vitejs/vite
78,557
TypeScript
sapphi-red
monam2
-----END CERTIFICATE----- `.trim() as any test('should extract hostnames from certificate', () => { const httpsOptions = { cert: [createWorkingCert] } as any const result = extractHostnamesFromCerts(httpsOptions.cert) expect(result).toStrictEqual([ 'localhost', 'foo.localhost', 'vi...
Should we make `extractHostnamesFromCerts` only return unique hosts? IIUC the duplicated ones would end up showing multiple times when printed otherwise.
]) }) }) describe('resolveServerUrls', () => { const createMockServer = ( family: 'IPv4' | 'IPv6' = 'IPv4', address: string = '127.0.0.1', ) => ({ address: () => ({ port: 3000, address, family }), }) as any const createTestConfig = () => ({ options: { https: true } as any, ho...
@@ -908,3 +910,204 @@ describe('getServerUrlByHost', () => { }) } }) + +describe('extractHostnamesFromCerts', () => { + // Test certificate containing domains: 'localhost', 'foo.localhost', 'vite.vite.localhost', + const createWorkingCert = `-----BEGIN CERTIFICATE----- +MIID7zCCAtegAwIBAgIJS9D2rIN7tA8mMA0GCS...
packages/vite/src/node/__tests__/utils.spec.ts
26
TypeScript
0.714
refactor
153
51
51
false
feat(utils): support multiple certificates in resolveServerUrls
20,707
vitejs/vite
78,557
TypeScript
bluwy
monam2
// Test certificate containing domains: 'localhost', 'foo.localhost', 'vite.vite.localhost', const createWorkingCert = `-----BEGIN CERTIFICATE----- MIID7zCCAtegAwIBAgIJS9D2rIN7tA8mMA0GCSqGSIb3DQEBCwUAMGkxFDASBgNV BAMTC2V4YW1wbGUub3JnMQswCQYDVQQGEwJVUzERMA8GA1UECBMIVmlyZ2luaWEx EzARBgNVBAcTCkJsYWNrc2J1cmcxDTALBgNVBA...
Looks like this variable is declared twice here. Maybe it can be hoisted up to the top-level and be shared. Also it would be nice to add a comment for how this cert was generated (the command used) so we can extend/tweak/create them in the future for testing.
const actual = getServerUrlByHost(urls, host) expect(actual).toBe(expected) }) } }) describe('extractHostnamesFromCerts', () => { test('should extract hostnames from certificate', () => { const certs = [WORKING_TEST_CERT] const result = extractHostnamesFromCerts(certs) expect(result).to...
@@ -908,3 +910,201 @@ describe('getServerUrlByHost', () => { }) } }) + +describe('extractHostnamesFromCerts', () => { + // Test certificate containing domains: 'localhost', 'foo.localhost', 'vite.vite.localhost', + const createWorkingCert = `-----BEGIN CERTIFICATE----- +MIID7zCCAtegAwIBAgIJS9D2rIN7tA8mMA0GCS...
packages/vite/src/node/__tests__/utils.spec.ts
26
TypeScript
0.571
suggestion
260
51
51
false
feat(utils): support multiple certificates in resolveServerUrls
20,707
vitejs/vite
78,557
TypeScript
bluwy
monam2
// Use a secure default host = 'localhost' } else if (optionsHost === true) { // If passed --host in the CLI without arguments host = undefined // undefined typically means 0.0.0.0 or :: (listen on all IPs) } else { host = optionsHost } // Set host name to localhost when possible let name...
Sorry for the back and forth, but it seems like this function is unused now.
// Use a secure default host = 'localhost' } else if (optionsHost === true) { // If passed --host in the CLI without arguments host = undefined // undefined typically means 0.0.0.0 or :: (listen on all IPs) } else { host = optionsHost } // Set host name to localhost when possible let name...
@@ -993,6 +993,33 @@ export async function resolveHostname( return { host, name } } +export function bufferify(buffer: string | Buffer): Buffer { + return Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer) +}
packages/vite/src/node/utils.ts
26
TypeScript
0.357
suggestion
77
51
51
false
feat(utils): support multiple certificates in resolveServerUrls
20,707
vitejs/vite
78,557
TypeScript
bluwy
monam2
// Set host name to localhost when possible let name = host === undefined || wildcardHosts.has(host) ? 'localhost' : host if (host === 'localhost') { // See #8647 for more details. const localhostAddr = await getLocalhostAddressIfDiffersFromDNS() if (localhostAddr) { name = localhostAddr } ...
Should we log a warning instead of completely ignoring an invalid cert?
// Set host name to localhost when possible let name = host === undefined || wildcardHosts.has(host) ? 'localhost' : host if (host === 'localhost') { // See #8647 for more details. const localhostAddr = await getLocalhostAddressIfDiffersFromDNS() if (localhostAddr) { name = localhostAddr } ...
@@ -993,6 +993,29 @@ export async function resolveHostname( return { host, name } } +export function extractHostnamesFromCerts( + certs: HttpsServerOptions['cert'] | undefined, +): string[] { + const certList = certs ? arraify(certs) : [] + if (certList.length === 0) return [] + + const hostnames = certList +...
packages/vite/src/node/utils.ts
26
TypeScript
0.357
question
71
51
51
false
feat(utils): support multiple certificates in resolveServerUrls
20,707
vitejs/vite
78,557
TypeScript
EmperorArthur
monam2
// See #8647 for more details. const localhostAddr = await getLocalhostAddressIfDiffersFromDNS() if (localhostAddr) { name = localhostAddr } } return { host, name } } export function resolveServerUrls( server: Server, options: CommonServerOptions, hostname: Hostname, httpsOptions: Ht...
For whatever reason this took me a minute to parse. Have you considered moving from the ternary `.filter((cert) => Boolean(cert?.subjectAltName))`? Quick test to show that should cover all the cases: ``` let c = [{subjectAltName: 'asdf'}, {}, null, {subjectAltName: null}, {subjectAltName: ''}]; c.filter((cert) => Boo...
// See #8647 for more details. const localhostAddr = await getLocalhostAddressIfDiffersFromDNS() if (localhostAddr) { name = localhostAddr } } return { host, name } } export function extractHostnamesFromCerts( certs: HttpsServerOptions['cert'] | undefined, ): string[] { const certList = ...
@@ -993,6 +993,29 @@ export async function resolveHostname( return { host, name } } +export function extractHostnamesFromCerts( + certs: HttpsServerOptions['cert'] | undefined, +): string[] { + const certList = certs ? arraify(certs) : [] + if (certList.length === 0) return [] + + const hostnames = certList +...
packages/vite/src/node/utils.ts
26
TypeScript
1
suggestion
364
51
51
false
feat(utils): support multiple certificates in resolveServerUrls
20,707
vitejs/vite
78,557
TypeScript
EmperorArthur
monam2
isReactSwc = true template = template.replace('-swc', '') } const pkgManager = pkgInfo ? pkgInfo.name : 'npm' const { customCommand } = FRAMEWORKS.flatMap((f) => f.variants).find((v) => v.name === template) ?? {} if (customCommand) { const fullCustomCommand = getFullCustomCommand(customComman...
Why is this disabled when `argTempalte`?
options: framework.variants.map((variant) => { const variantColor = variant.color const command = variant.customCommand ? getFullCustomCommand(variant.customCommand, pkgInfo).replace( / TARGET_DIR$/, '', ) : undefined ...
@@ -499,6 +499,22 @@ async function init() { process.exit(status ?? 0) } + const useRolldownVite = argTemplate + ? false + : await prompts.select({
packages/create-vite/src/index.ts
26
TypeScript
0.286
question
40
51
51
false
feat(create-vite): scaffold with rolldown-vite
20,739
vitejs/vite
78,557
TypeScript
hi-ogawa
sapphi-red
let doneMessage = '' const cdProjectName = path.relative(cwd, root) doneMessage += `Done. Now run:\n` if (root !== cwd) { doneMessage += `\n cd ${ cdProjectName.includes(' ') ? `"${cdProjectName}"` : cdProjectName }` } switch (pkgManager) { case 'yarn': doneMessage += '\n yarn' ...
https://vite.dev/guide/rolldown.html#how-to-try-rolldown
write(file) } const pkg = JSON.parse( fs.readFileSync(path.join(templateDir, `package.json`), 'utf-8'), ) pkg.name = packageName if (useRolldownVite) { // renovate: datasource=npm depName=rolldown-vite const rolldownViteVersion = '7.1.12' const pkgVersion = `npm:rolldown-vite@${rolldown...
@@ -527,6 +543,27 @@ async function init() { pkg.name = packageName + if (useRolldownVite) { + // renovate: datasource=npm depName=rolldown-vite + const rolldownViteVersion = '7.1.9' + const pkgVersion = `npm:rolldown-vite@${rolldownViteVersion}` + pkg.devDependencies.vite = pkgVersion + switch (...
packages/create-vite/src/index.ts
26
TypeScript
0.357
suggestion
56
51
51
false
feat(create-vite): scaffold with rolldown-vite
20,739
vitejs/vite
78,557
TypeScript
sapphi-red
sapphi-red
// into: // (function(){ <esbuild helpers> /*actual content/* })() // Not using regex because it's too hard to rule out performance issues like #8738 #8099 #10900 #14065 // Instead, using plain string index manipulation (indexOf, slice) which is simple and performant // We don't need to create a MagicString here bec...
```suggestion return esbuildCode } ```
// into: // (function(){ <esbuild helpers> /*actual content/* })() // Not using regex because it's too hard to rule out performance issues like #8738 #8099 #10900 #14065 // Instead, using plain string index manipulation (indexOf, slice) which is simple and performant // We don't need to create a MagicString here bec...
@@ -318,6 +318,37 @@ const rollupToEsbuildFormatMap: Record< iife: undefined, } +// #7188, esbuild adds helpers out of the UMD and IIFE wrappers, and the +// names are minified potentially causing collision with other globals. +// We inject the helpers inside the wrappers. +// e.g. turn: +// <esbuild helpers> ...
packages/vite/src/node/plugins/esbuild.ts
26
TypeScript
0.786
suggestion
45
51
51
false
fix(esbuild): inject esbuild helper functions with minified `$` variables correctly
20,761
vitejs/vite
78,557
TypeScript
sapphi-red
james-od
import './dep2.js' // TODO: currently we need one more `import` in this module // to trigger prune for depending module `dep2.js` since // the prune event logic is skipped when `es-module-lexer` // detects `imports.length === 0` import './dep2-other.js'
Let's add a link to the issue you are going to create here.
import './dep2.js' // TODO: https://github.com/vitejs/vite/issues/20781 // currently we need one more `import` in this module // to trigger prune for depending module `dep2.js` since // the prune event logic is skipped when `es-module-lexer` // detects `imports.length === 0` import './dep2-other.js'
@@ -0,0 +1,7 @@ +import './dep2.js' + +// TODO: currently we need one more `import` in this module
playground/hmr/prune/dep1.js
3
JavaScript
0.143
suggestion
59
8
9
false
fix(hmr): trigger prune event when import is removed from non hmr module
20,768
vitejs/vite
78,557
TypeScript
sapphi-red
hi-ogawa
await Promise.all( resolved .getSortedPluginHooks('configResolved') .map((hook) => hook.call(resolvedConfigContext, resolved)), ) // Resolve environment plugins after configResolved because there are // downstream projects modifying the plugins in it. This may change // once the ecosystem is ...
This backward compat only makes sense with `builder.sharedConfigBuild: false` because only in that case `build.*` and `environments.ssr.build.*` should be synced. So I think, instead, we can skip this code when `sharedConfigBuild` is enabled: ```ts if (!sharedConfigBuild && resolved.environments.ssr) { resolved.e...
await Promise.all( resolved .getSortedPluginHooks('configResolved') .map((hook) => hook.call(resolvedConfigContext, resolved)), ) // Resolve environment plugins after configResolved because there are // downstream projects modifying the plugins in it. This may change // once the ecosystem is ...
@@ -1659,7 +1659,7 @@ export async function resolveConfig( // For backward compat, set ssr environment build.emitAssets with the same value as build.ssrEmitAssets that might be changed in configResolved hook // https://github.com/vikejs/vike/blob/953614cea7b418fcc0309b5c918491889fdec90a/vike/node/plugin/plugins/b...
packages/vite/src/node/config.ts
26
TypeScript
1
suggestion
420
51
51
false
fix(build): fix ssr environment `emitAssets: true` when `sharedConfigBuild: true`
20,787
vitejs/vite
78,557
TypeScript
sapphi-red
hi-ogawa
greenBright, magenta, red, redBright, reset, yellow, } = colors const argv = mri<{ template?: string help?: boolean overwrite?: boolean interactive?: boolean }>(process.argv.slice(2), { alias: { h: 'help', t: 'template' }, boolean: ['help', 'overwrite', 'interactive'], string: ['template'], }...
I think it should be "running" here: ```suggestion If it is running in TTY, the CLI will start in interactive mode. ``` Or maybe it can be shorter like ```suggestion When running in TTY, the CLI will start in interactive mode. ```
greenBright, magenta, red, redBright, reset, yellow, } = colors const argv = mri<{ template?: string help?: boolean overwrite?: boolean interactive?: boolean }>(process.argv.slice(2), { alias: { h: 'help', t: 'template' }, boolean: ['help', 'overwrite', 'interactive'], string: ['template'], }...
@@ -35,10 +36,11 @@ const helpMessage = `\ Usage: create-vite [OPTION]... [DIRECTORY] Create a new Vite project in JavaScript or TypeScript. -With no arguments, start the CLI in interactive mode. +If it is run in TTY, the CLI will start in interactive mode.
packages/create-vite/src/index.ts
26
TypeScript
1
suggestion
233
51
51
false
feat(create-vite): add `--interactive` / `--no-interactive`
20,797
vitejs/vite
78,557
TypeScript
bluwy
sapphi-red
const staticImports: string[] = [] const resolvePaths = (file: string) => { if (!dir) { if (!options.base && isRelative) throw new Error( "In virtual modules, all globs must start with '/'", ) const importPath...
@copilot there's other places that `filePath[0] !== '.'` is used. fix them and add a test case for each one.
const staticImports: string[] = [] const resolvePaths = (file: string) => { if (!dir) { if (!options.base && isRelative) throw new Error( "In virtual modules, all globs must start with '/'", ) const importPath...
@@ -465,7 +465,9 @@ export async function transformGlobImport( } let importPath = relative(dir, file) - if (importPath[0] !== '.') importPath = `./${importPath}` + if (!importPath.startsWith('./') && !importPath.startsWith('../')) { + importPath = `./${impo...
packages/vite/src/node/plugins/importMetaGlob.ts
26
TypeScript
0.714
suggestion
108
51
51
false
fix(glob): handle glob imports from folders starting with dot
20,800
vitejs/vite
78,557
TypeScript
sapphi-red
Copilot
debugPluginResolve?.( timeFrom(pluginResolveStart), plugin.name, prettifyUrl(id, this.environment.config.root), ) // resolveId() is hookFirst - first non-null result is returned. break } if (debugResolve && rawId !== id && !rawId.startsWith(FS_PREFIX)) { c...
```suggestion isExternalUrl(id) || id[0] === '\0' ? id : normalizePath(id) ``` Keep the code style consistent with other places.
debugPluginResolve?.( timeFrom(pluginResolveStart), plugin.name, prettifyUrl(id, this.environment.config.root), ) // resolveId() is hookFirst - first non-null result is returned. break } if (debugResolve && rawId !== id && !rawId.startsWith(FS_PREFIX)) { c...
@@ -462,7 +462,8 @@ class EnvironmentPluginContainer<Env extends Environment = Environment> { } if (id) { - partial.id = isExternalUrl(id) ? id : normalizePath(id) + partial.id = + isExternalUrl(id) || id.startsWith('\0') ? id : normalizePath(id)
packages/vite/src/node/server/pluginContainer.ts
26
TypeScript
1
suggestion
136
51
51
false
fix: keep ids for virtual modules as-is
20,808
vitejs/vite
78,557
TypeScript
btea
sapphi-red
import fs from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import type { SpawnOptions } from 'node:child_process'; import spawn from 'cross-spawn' import mri from 'mri' import * as prompts from '@clack/prompts' import colors from 'picocolors' const { blue, blueBright, cyan, ...
```suggestion import type { SpawnOptions } from 'node:child_process' ```
import fs from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import type { SpawnOptions } from 'node:child_process' import spawn from 'cross-spawn' import mri from 'mri' import * as prompts from '@clack/prompts' import colors from 'picocolors' const { blue, blueBright, cyan, g...
@@ -1,6 +1,7 @@ import fs from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' +import type { SpawnOptions } from 'node:child_process';
packages/create-vite/src/index.ts
4
TypeScript
1
suggestion
74
29
29
false
fix(create-vite): fix installing dependencies
20,826
vitejs/vite
78,557
TypeScript
sapphi-red
nicolo-ribaudo
isExternalUrl(unquotedUrl) || isDataUrl(unquotedUrl) || unquotedUrl[0] === '#' || functionCallRE.test(unquotedUrl) || // skip if it is already a placeholder unquotedUrl.startsWith('__VITE_ASSET__') || unquotedUrl.startsWith('__VITE_PUBLIC_ASSET__') ) } async function doUrlReplace( rawUrl...
```suggestion // The URL may contain escaped characters, which the regex can capture. Before resolving the file path, // the escapes are removed to get the actual file name. ``` Comment is a little long
isExternalUrl(unquotedUrl) || isDataUrl(unquotedUrl) || unquotedUrl[0] === '#' || functionCallRE.test(unquotedUrl) || // skip if it is already a placeholder unquotedUrl.startsWith('__VITE_ASSET__') || unquotedUrl.startsWith('__VITE_PUBLIC_ASSET__') ) } async function doUrlReplace( rawUrl...
@@ -2049,14 +2049,17 @@ async function doUrlReplace( if (skipUrlReplacer(unquotedUrl)) { return matched } + // The URL may contain escaped characters, which the regex can capture. Before resolving the file path, the escapes are removed to get the actual file name.
packages/vite/src/node/plugins/css.ts
26
TypeScript
1
security
207
51
51
false
fix(css): improve url escape characters handling
20,847
vitejs/vite
78,557
TypeScript
bluwy
ia319
isDataUrl(unquotedUrl) || unquotedUrl[0] === '#' || functionCallRE.test(unquotedUrl) || // skip if it is already a placeholder unquotedUrl.startsWith('__VITE_ASSET__') || unquotedUrl.startsWith('__VITE_PUBLIC_ASSET__') ) } async function doUrlReplace( rawUrl: string, matched: string, rep...
Is there a specific set of characters to skip here? Could it be simplified as `/\\([^\w])/`?
isDataUrl(unquotedUrl) || unquotedUrl[0] === '#' || functionCallRE.test(unquotedUrl) || // skip if it is already a placeholder unquotedUrl.startsWith('__VITE_ASSET__') || unquotedUrl.startsWith('__VITE_PUBLIC_ASSET__') ) } async function doUrlReplace( rawUrl: string, matched: string, rep...
@@ -2049,14 +2049,17 @@ async function doUrlReplace( if (skipUrlReplacer(unquotedUrl)) { return matched } + // The URL may contain escaped characters, which the regex can capture. Before resolving the file path, the escapes are removed to get the actual file name. + unquotedUrl = unquotedUrl.replace(/\\([ ...
packages/vite/src/node/plugins/css.ts
26
TypeScript
0.571
question
92
51
51
false
fix(css): improve url escape characters handling
20,847
vitejs/vite
78,557
TypeScript
bluwy
ia319
async function doUrlReplace( rawUrl: string, matched: string, replacer: CssUrlReplacer, funcName: string = 'url', ) { let wrap = '' const first = rawUrl[0] let unquotedUrl = rawUrl if (first === `"` || first === `'`) { wrap = first unquotedUrl = rawUrl.slice(1, -1) } if (skipUrlReplacer(unqu...
```suggestion // The new url might need wrapping even if the original did not have it, e.g. // if a space was added during replacement or the URL contains ")" ``` I think the comment can be combined here
async function doUrlReplace( rawUrl: string, matched: string, replacer: CssUrlReplacer, funcName: string = 'url', ) { let wrap = '' const first = rawUrl[0] let unquotedUrl = rawUrl if (first === `"` || first === `'`) { wrap = first unquotedUrl = rawUrl.slice(1, -1) } if (skipUrlReplacer(unqu...
@@ -2049,14 +2049,17 @@ async function doUrlReplace( if (skipUrlReplacer(unquotedUrl)) { return matched } + // The URL may contain escaped characters, which the regex can capture. Before resolving the file path, the escapes are removed to get the actual file name. + unquotedUrl = unquotedUrl.replace(/\\([ ...
packages/vite/src/node/plugins/css.ts
26
TypeScript
1
suggestion
211
51
51
false
fix(css): improve url escape characters handling
20,847
vitejs/vite
78,557
TypeScript
bluwy
ia319
cssUrlRE.test( 'mask-image: image(skyblue,url(mask.png), linear-gradient(rgba(0, 0, 0, 1.0), transparent));', ), ).toBe(true) }) test('should capture the full url with escaped parentheses', () => { const css = 'background-image: url(public/awkward-name\\)2.png);' const match = cssUrl...
I think we can simplify this as ```suggestion expect(match?.[1].trim()).toBe('public/awkward-name\\)2.png') ```
cssUrlRE.test( 'mask-image: image(skyblue,url(mask.png), linear-gradient(rgba(0, 0, 0, 1.0), transparent));', ), ).toBe(true) }) test('should capture the full url with escaped parentheses', () => { const css = 'background-image: url(public/awkward-name\\)2.png);' const match = cssUr...
@@ -56,6 +56,28 @@ describe('search css url function', () => { ), ).toBe(true) }) + test('should capture the full url with escaped parentheses', () => { + const css = 'background-image: url(public/awkward-name\\)2.png);' + const match = cssUrlRE.exec(css) + + if (match) { + const capturedU...
packages/vite/src/node/__tests__/plugins/css.spec.ts
26
TypeScript
1
refactor
115
51
51
false
fix(css): improve url escape characters handling
20,847
vitejs/vite
78,557
TypeScript
bluwy
ia319
import type { Plugin } from '../plugin' /** * ensure amd bundles request `require` to be injected */ export function completeAmdWrapPlugin(): Plugin { const AmdWrapRE = /\bdefine\((?:\s*\[([^\]]*)\],)?\s*(?:\(\s*)?function\s*\(([^)]*)\)\s*\{/g return { name: 'vite:force-amd-wrap-require', renderChun...
```suggestion if (deps?.includes('"require"')) { ```
import type { Plugin } from '../plugin' /** * ensure amd bundles request `require` to be injected */ export function completeAmdWrapPlugin(): Plugin { const AmdWrapRE = /\bdefine\((?:\s*\[([^\]]*)\],)?\s*(?:\(\s*)?function\s*\(([^)]*)\)\s*\{/g return { name: 'vite:force-amd-wrap-require', renderChun...
@@ -0,0 +1,30 @@ +import type { Plugin } from '../plugin' + +/** + * ensure amd bundles request `require` to be injected + */ +export function completeAmdWrapPlugin(): Plugin { + const AmdWrapRE = + /\bdefine\((?:\s*\[([^\]]*)\],)?\s*(?:\(\s*)?function\s*\(([^)]*)\)\s*\{/g + + return { + name: 'vite:force-amd-w...
packages/vite/src/node/plugins/completeAmdWrap.ts
17
TypeScript
0.857
suggestion
64
31
31
false
fix(build): ensure amd bundles request `require` to be injected
20,861
vitejs/vite
78,557
TypeScript
sapphi-red
dschmidt
import type { Plugin } from '../plugin' /** * ensure amd bundles request `require` to be injected */ export function completeAmdWrapPlugin(): Plugin { const AmdWrapRE = /\bdefine\((?:\s*\[([^\]]*)\],)?\s*(?:\(\s*)?function\s*\(([^)]*)\)\s*\{/g return { name: 'vite:force-amd-wrap-require', renderChun...
```suggestion map: null, // no need to generate sourcemap as no mapping exists for the wrapper ``` The `completeSystemWrapPlugin` does not have this comment, but I thought it would be nice to clarify this.
import type { Plugin } from '../plugin' /** * ensure amd bundles request `require` to be injected */ export function completeAmdWrapPlugin(): Plugin { const AmdWrapRE = /\bdefine\((?:\s*\[([^\]]*)\],)?\s*(?:\(\s*)?function\s*\(([^)]*)\)\s*\{/g return { name: 'vite:force-amd-wrap-require', renderChun...
@@ -0,0 +1,30 @@ +import type { Plugin } from '../plugin' + +/** + * ensure amd bundles request `require` to be injected + */ +export function completeAmdWrapPlugin(): Plugin { + const AmdWrapRE = + /\bdefine\((?:\s*\[([^\]]*)\],)?\s*(?:\(\s*)?function\s*\(([^)]*)\)\s*\{/g + + return { + name: 'vite:force-amd-w...
packages/vite/src/node/plugins/completeAmdWrap.ts
26
TypeScript
1
suggestion
218
31
31
false
fix(build): ensure amd bundles request `require` to be injected
20,861
vitejs/vite
78,557
TypeScript
sapphi-red
dschmidt
} from '../../utils' import { send } from '../send' import { ERR_DENIED_ID, ERR_LOAD_URL } from '../transformRequest' import { applySourcemapIgnoreList } from '../sourcemap' import { isHTMLProxy } from '../../plugins/html' import { DEP_VERSION_RE, ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR, ERR_OPTIMIZE_DEPS_PROCESS...
Can the `string | undefined` be removed? Looks like the elements are all strings only. I suppose this affects the types for `documentFetchDests.has` below.
} from '../../utils' import { send } from '../send' import { ERR_DENIED_ID, ERR_LOAD_URL } from '../transformRequest' import { applySourcemapIgnoreList } from '../sourcemap' import { isHTMLProxy } from '../../plugins/html' import { DEP_VERSION_RE, ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR, ERR_OPTIMIZE_DEPS_PROCESS...
@@ -40,6 +40,16 @@ const debugCache = createDebugger('vite:cache') const knownIgnoreList = new Set(['/', '/favicon.ico']) +const documentFetchDests = new Set<string | undefined>([
packages/vite/src/node/server/middlewares/transform.ts
26
TypeScript
1
suggestion
156
51
51
false
fix(dev): skip JS responses for document requests
20,866
vitejs/vite
78,557
TypeScript
bluwy
sapphi-red
// This module may get invalidated while we are processing it. For example // when a full page reload is needed after the re-processing of pre-bundled // dependencies when a missing dep is discovered. We save the current time // to compare it to the last invalidation performed to know if we should // cache th...
The diff is a bit big than the actual change. I only removed `removeTimestampQuery` here.
// This module may get invalidated while we are processing it. For example // when a full page reload is needed after the re-processing of pre-bundled // dependencies when a missing dep is discovered. We save the current time // to compare it to the last invalidation performed to know if we should // cache th...
@@ -99,25 +99,25 @@ export function transformRequest( // last time this module is invalidated const timestamp = monotonicDateNow() + url = removeTimestampQuery(url) + const pending = environment._pendingRequests.get(url) if (pending) { - return environment.moduleGraph - .getModuleByUrl(removeTime...
packages/vite/src/node/server/transformRequest.ts
26
TypeScript
0.571
suggestion
89
51
51
false
fix(dev): remove timestamp query consistently
20,887
vitejs/vite
78,557
TypeScript
sapphi-red
sapphi-red
map?: ExistingRawSourceMap | undefined additionalMap?: ExistingRawSourceMap | undefined error?: RollupError deps: string[] } const loadedPreprocessorPath: Partial< Record< PreprocessLang | PostCssDialectLang | 'sass-embedded', string | Promise<string> > > = {} let nodeResolveWithVite: NodeResolveWi...
This only tries to resolve from `root`, but `requireResolveFromRootWithFallback` resolves from `__dirname` if failed. IIRC we need to keep the fallback for some cases covered by ecosystem-ci.
additionalMap?: ExistingRawSourceMap | undefined error?: RollupError deps: string[] } const loadedPreprocessorPath: Partial< Record<PreprocessLang | PostCssDialectLang | 'sass-embedded', string> > = {} function loadPreprocessorPath( lang: PreprocessLang | PostCssDialectLang | 'sass-embedded', root: string...
@@ -2312,60 +2314,68 @@ export interface StylePreprocessorResults { } const loadedPreprocessorPath: Partial< - Record<PreprocessLang | PostCssDialectLang | 'sass-embedded', string> + Record< + PreprocessLang | PostCssDialectLang | 'sass-embedded', + string | Promise<string> + > > = {} +let nodeResolveWith...
packages/vite/src/node/plugins/css.ts
26
TypeScript
0.5
bug
191
51
51
false
fix: use esm entrypoint for css preprocessors and terser
20,918
vitejs/vite
78,557
TypeScript
sapphi-red
bluwy
) aliasOnlyPluginContainerMap.set(environment, pluginContainer) } return await pluginContainer.resolveId(id, importer, { scan }) } return async (environment, id, importer, aliasOnly) => { const resolveFn = aliasOnly ? resolveAlias : resolve // aliasPlugin and resolvePlugin are implement...
Maybe we can import this statically? I don't remember why I made this dynamic, but I guess converting this to static would make the code simpler.
import type { PartialResolvedId } from 'rollup' import aliasPlugin from '@rollup/plugin-alias' import type { ResolvedConfig } from './config' import type { EnvironmentPluginContainer } from './server/pluginContainer' import { createEnvironmentPluginContainer } from './server/pluginContainer' import { resolvePlugin } fr...
@@ -110,3 +111,41 @@ export function createIdResolver( return resolved?.id } } + +export type NodeResolveWithViteFn = ( + id: string, + importer?: string, + isRequire?: boolean, +) => string | undefined + +export async function createNodeResolverWithVite( + root: string, +): Promise<NodeResolveWithViteFn> ...
packages/vite/src/node/idResolver.ts
26
TypeScript
0.286
suggestion
145
51
113
false
fix: use esm entrypoint for css preprocessors and terser
20,918
vitejs/vite
78,557
TypeScript
sapphi-red
bluwy
isNodeBuiltin(id) ) { return } // With the `isNodeBuiltin` check above, this check captures if the builtin is a // non-node built-in, which esbuild doesn't know how to handle. In that case, we // externalize it so the...
```suggestion isRequire: false, ``` This was `false` before.
isNodeBuiltin(id) ) { return } // With the `isNodeBuiltin` check above, this check captures if the builtin is a // non-node built-in, which esbuild doesn't know how to handle. In that case, we // externalize it so the...
@@ -2003,16 +1973,18 @@ async function bundleConfigFile( const isImport = isESM || kind === 'dynamic-import' let idFsPath: string | undefined try { - idFsPath = resolveByViteResolver(id, importer, !isImport) + idFsPath = nodeResolveWithVite(id, ...
packages/vite/src/node/config.ts
26
TypeScript
0.857
suggestion
85
51
51
false
fix: use esm entrypoint for css preprocessors and terser
20,918
vitejs/vite
78,557
TypeScript
sapphi-red
bluwy
// NOTE: Cannot use subpath imports for some reason import '../../../../../../types/importMeta' export interface ModuleType { name: string } export const basic = import.meta.glob<ModuleType>('./modules/*.ts') // prettier-ignore export const basicWithObjectKeys = Object.keys(import.meta.glob<ModuleType>('./modules/*...
I think it's because the closest `package.json` is this one. https://github.com/vitejs/vite/blob/2bdd262388a1eaee7853b7f8349dc9f60f2cc2f0/packages/vite/src/node/__tests__/package.json
// NOTE: `#types/importMeta` does not work as `src/node/__tests__/package.json` shadows the root // `package.json` and does not declare the subpath import. import '../../../../../../types/importMeta' export interface ModuleType { name: string } export const basic = import.meta.glob<ModuleType>('./modules/*.ts') // ...
@@ -1,4 +1,5 @@ -import 'types/importMeta' +// NOTE: Cannot use subpath imports for some reason
packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/index.ts
1
TypeScript
0.714
suggestion
184
26
26
false
refactor: use subpath imports for types module reference
20,921
vitejs/vite
78,557
TypeScript
sapphi-red
bluwy
} export class ModuleRunner { public evaluatedModules: EvaluatedModules public hmrClient?: HMRClient private readonly transport: NormalizedModuleRunnerTransport private readonly resetSourceMapSupport?: () => void private readonly concurrentModuleNodePromises = new Map< string, Promise<EvaluatedModul...
Instead of receiving the options here, I think we should ask the server side by `this.transport.invoke` so that users won't have to set the option.
public hmrClient?: HMRClient private readonly transport: NormalizedModuleRunnerTransport private readonly resetSourceMapSupport?: () => void private readonly concurrentModuleNodePromises = new Map< string, Promise<EvaluatedModuleNode> >() private isBuiltin?: (id: string) => boolean private builti...
@@ -54,6 +60,9 @@ export class ModuleRunner { ) { this.evaluatedModules = options.evaluatedModules ?? new EvaluatedModules() this.transport = normalizeModuleRunnerTransport(options.transport) + if (options.builtins) { + this.isBuiltin = createIsBuiltin(options.builtins) + }
packages/vite/src/module-runner/runner.ts
26
TypeScript
0.714
suggestion
147
51
51
false
perf(module-runner): add client-side builtin module check
20,924
vitejs/vite
78,557
TypeScript
sapphi-red
jiji-hoon96
| 'prepareStackTrace' | InterceptorOptions /** * Disable HMR or configure HMR options. * * @default true */ hmr?: boolean | ModuleRunnerHmr /** * Create import.meta object for the module. * * @default createDefaultImportMeta */ createImportMeta?: ( modulePath: string, ) => ...
Do we still need this option? (I guess no?)
| 'prepareStackTrace' | InterceptorOptions /** * Disable HMR or configure HMR options. * * @default true */ hmr?: boolean | ModuleRunnerHmr /** * Create import.meta object for the module. * * @default createDefaultImportMeta */ createImportMeta?: ( modulePath: string, ) => ...
@@ -117,6 +117,12 @@ export interface ModuleRunnerOptions { * Custom module cache. If not provided, creates a separate module cache for each ModuleRunner instance. */ evaluatedModules?: EvaluatedModules + /** + * List of builtin modules to check on the client side. + * If not provided, will be automatic...
packages/vite/src/module-runner/types.ts
26
TypeScript
0.071
question
43
37
31
false
perf(module-runner): add client-side builtin module check
20,924
vitejs/vite
78,557
TypeScript
sapphi-red
jiji-hoon96
", ], "version": 3, }, visualization: "https://evanw.github.io/source-map-visualization/#MTQ2NgBjb25zdCBfX3ZpdGVfX21hcERlcHM9KGksbT1fX3ZpdGVfX21hcERlcHMsZD0obS5mfHwobS5mPVsiYXNzZXRzL2R5bmFtaWMtZm9vLUZfYXJUX3E1LmpzIiwiYXNzZXRzL2R5bmFtaWMtZm9vLURzcUtSckV5LmNzcyJdKSkpPT5...
```suggestion ``` This assertion is covered by the assertion below.
", ], "version": 3, }, visualization: "https://evanw.github.io/source-map-visualization/#MTQ2NgBjb25zdCBfX3ZpdGVfX21hcERlcHM9KGksbT1fX3ZpdGVfX21hcERlcHMsZD0obS5mfHwobS5mPVsiYXNzZXRzL2R5bmFtaWMtZm9vLUZfYXJUX3E1LmpzIiwiYXNzZXRzL2R5bmFtaWMtZm9vLURzcUtSckV5LmNzcyJdKSkpPT5...
@@ -182,6 +182,27 @@ describe.runIf(isBuild)('build tests', () => { ) }) + test('sourcemap file field is consistent (#20853)', async () => { + const assets = listAssets() + const mapAssets = assets.filter((asset) => asset.endsWith('.js.map')) + + for (const mapAsset of mapAssets) { + const mapC...
playground/js-sourcemap/__tests__/js-sourcemap.spec.ts
26
TypeScript
1
suggestion
69
51
51
false
fix: preserve original sourcemap file field when combining sourcemaps
20,926
vitejs/vite
78,557
TypeScript
sapphi-red
jiji-hoon96
], 'n/no-extraneous-import': [ 'error', { allowModules: [ 'vite', 'less', 'sass', 'sass-embedded', 'terser', 'lightningcss', 'vitest', 'unbuild', ], }, ], '...
How about this setting? ```js '@typescript-eslint/consistent-generic-constructors': [ 'error', 'type-annotation', ], ```
}, ], 'n/no-extraneous-import': [ 'error', { allowModules: [ 'vite', 'less', 'sass', 'sass-embedded', 'terser', 'lightningcss', 'vitest', 'unbuild', ], }, ...
@@ -117,6 +117,7 @@ export default defineConfig( 'n/prefer-node-protocol': 'error', '@typescript-eslint/ban-ts-comment': 'error', + '@typescript-eslint/consistent-generic-constructors': 'off',
eslint.config.js
26
JavaScript
1
question
156
51
51
false
build: use isolated declarations
20,928
vitejs/vite
78,557
TypeScript
sapphi-red
bluwy
it('should not crash when sourceMappingURL pattern appears in string literals', async ({ runner, server, }) => { const mod = await runner.import('/fixtures/string-literal-sourcemap.ts') expect(mod.getMessage()).toBe( '//# sourceMappingURL=data:application/json;base64,invalidbase64', ) ...
```suggestion // the file is mentioned in the source maps, but doesn't exist because we removed it. // Vite still prefers it because it is specified in inlined base64 map under "sources" field. // if something breaks, the stack trace will use "transpiled-inline.js" file instead. ``` Would you clarify w...
it('should not crash when sourceMappingURL pattern appears in string literals', async ({ runner, server, }) => { const mod = await runner.import('/fixtures/string-literal-sourcemap.ts') expect(mod.getMessage()).toBe( '//# sourceMappingURL=data:application/json;base64,invalidbase64', ) ...
@@ -109,4 +109,23 @@ describe('module runner initialization', async () => { ' at Module.throwError (<root>/fixtures/string-literal-sourcemap.ts:11:9)', ]) }) + + it('should correctly pickup the url from sources', async ({ + server, + runner, + }) => { + const mod = await runner.import('/fix...
packages/vite/src/node/ssr/runtime/__tests__/server-source-maps.spec.ts
26
TypeScript
1
question
369
37
37
false
fix(module-runner): resolve `resolvedSources` correctly
20,959
vitejs/vite
78,557
TypeScript
sapphi-red
sheremet-va
export type ImportMetaResolver = (specifier: string, importer: string) => string const customizationHookNamespace = 'vite-module-runner:import-meta-resolve/v1/' const customizationHooksModule = /* js */ ` export async function resolve(specifier, context, nextResolve) { if (specifier.startsWith(${JSON.stringify(cust...
The exported string contains leading and trailing blank lines that serve no functional purpose. These should be removed to improve code clarity and reduce unnecessary whitespace in the injected code. ```suggestion (() => { const resolve = 'resolve' return (specifier, importer) => import.meta[resolve]( \`$...
module.register(hookModuleContent) } catch (e) { // For `--experimental-network-imports` flag that exists in Node before v22 if ('code' in e && e.code === 'ERR_NETWORK_IMPORT_DISALLOWED') { return } throw e } return (specifier: string, importer: string) => import.meta.resolve( ...
@@ -46,3 +46,16 @@ export async function createImportMetaResolver(): Promise< `${customizationHookNamespace}${JSON.stringify([specifier, importer])}`, ) } + +// NOTE: use computed string to avoid `define` replacing `import.meta.resolve` when bundled +export const importMetaResolveWithCustomHookString: stri...
packages/vite/src/module-runner/importMetaResolver.ts
26
TypeScript
1
suggestion
407
49
28
false
feat: add `import.meta.resolve` support for ESM config (bundle config loader)
20,962
vitejs/vite
78,557
TypeScript
Copilot
sapphi-red
build.onLoad({ filter: /\.[cm]?[jt]s$/ }, async (args) => { const contents = await fsp.readFile(args.path, 'utf-8') const injectValues = `const ${dirnameVarName} = ${JSON.stringify( path.dirname(args.path), )};` + `const ${filen...
The injected code wraps `importMetaResolveWithCustomHookString` in an immediately invoked function call, but the string already contains an IIFE. This creates nested IIFEs: `(() => {...})()` becomes `((() => {...})())(specifier, importer)`. The outer wrapping is unnecessary and should be removed. Change to: `const ${im...
external: true, } }, ) }, }, { name: 'inject-file-scope-variables', setup(build) { build.onLoad({ filter: /\.[cm]?[jt]s$/ }, async (args) => { const contents = await fsp.readFile(args.path, 'utf-8') ...
@@ -2015,14 +2024,25 @@ async function bundleConfigFile( setup(build) { build.onLoad({ filter: /\.[cm]?[jt]s$/ }, async (args) => { const contents = await fsp.readFile(args.path, 'utf-8') - const injectValues = + let injectValues = `const ${dirnameVa...
packages/vite/src/node/config.ts
26
TypeScript
1
suggestion
517
51
51
false
feat: add `import.meta.resolve` support for ESM config (bundle config loader)
20,962
vitejs/vite
78,557
TypeScript
Copilot
sapphi-red
`WebSocket server error: Port ${e.port} is already in use`, ), { error: e }, ) } else { config.logger.error( colors.red(`WebSocket server error:\n${e.stack || e.message}`), { error: e }, ) } }) } const emitCustomEvent = <T ...
Unrelated, but this `parsed.invoke` (or anywhere `invoke` related) seems unused.
), { error: e }, ) } else { config.logger.error( colors.red(`WebSocket server error:\n${e.stack || e.message}`), { error: e }, ) } }) } const emitCustomEvent = <T extends string>( event: T, data: InferCustomEventPayload<T>, ...
@@ -289,19 +304,20 @@ export function createWebSocketServer( parsed = JSON.parse(String(raw)) } catch {} if (!parsed || parsed.type !== 'custom' || !parsed.event) return - const listeners = customListeners.get(parsed.event) - if (!listeners?.size) return - const client = getSocketC...
packages/vite/src/node/server/ws.ts
26
TypeScript
0.571
suggestion
80
51
51
false
feat: add vite client connect events
20,978
vitejs/vite
78,557
TypeScript
bluwy
sapphi-red
import type { ErrorPayload, FullReloadPayload, PrunePayload, UpdatePayload, } from './hmrPayload' export interface CustomEventMap { // client events 'vite:beforeUpdate': UpdatePayload 'vite:afterUpdate': UpdatePayload 'vite:beforePrune': PrunePayload 'vite:beforeFullReload': FullReloadPayload 'vite...
Should we rename it as `vite:client:connect` so it's similar to `vite:ws:connect`? --- Btw I found it initially weird that we're mixing client/server events here, but it's not too terrible at the end if it makes configuring events easier. It's unlikely that client <-> server with the same event name will need dif...
import type { ErrorPayload, FullReloadPayload, PrunePayload, UpdatePayload, } from './hmrPayload' export interface CustomEventMap { // client events 'vite:beforeUpdate': UpdatePayload 'vite:afterUpdate': UpdatePayload 'vite:beforePrune': PrunePayload 'vite:beforeFullReload': FullReloadPayload 'vite...
@@ -14,6 +15,10 @@ export interface CustomEventMap { 'vite:invalidate': InvalidatePayload 'vite:ws:connect': WebSocketConnectionPayload 'vite:ws:disconnect': WebSocketConnectionPayload + + // server events + 'vite:client-connect': undefined + 'vite:client-disconnect': undefined
packages/vite/types/customEvent.d.ts
21
TypeScript
0.857
question
341
46
46
false
feat: add vite client connect events
20,978
vitejs/vite
78,557
TypeScript
bluwy
sapphi-red
preTransformRequests?: boolean /** * Whether or not to ignore-list source files in the dev server sourcemap, used to populate * the [`x_google_ignoreList` source map extension](https://developer.chrome.com/blog/devtools-better-angular-debugging/#the-x_google_ignorelist-source-map-extension). * * By defa...
Are the comments here inaccurate that: > called only once for all environments Should be this instead? > called only for the client environment
preTransformRequests?: boolean /** * Whether or not to ignore-list source files in the dev server sourcemap, used to populate * the [`x_google_ignoreList` source map extension](https://developer.chrome.com/blog/devtools-better-angular-debugging/#the-x_google_ignorelist-source-map-extension). * * By defa...
@@ -180,6 +180,13 @@ export interface ServerOptions extends CommonServerOptions { * @experimental */ perEnvironmentStartEndDuringDev?: boolean + /** + * Backward compatibility. The watchChange hook was called only once for all environments. + * This option enables per-environment watchChange hooks. + ...
packages/vite/src/node/server/index.ts
26
TypeScript
0.5
suggestion
146
51
51
false
feat: add `perEnvironmentWatchChangeDuringDev`
20,996
vitejs/vite
78,557
TypeScript
bluwy
sapphi-red
await compiler?.dispose() compilerPromise = undefined }, } return worker } type ScssWorkerResult = { css: string map?: string | undefined stats: { includedFiles: string[] } } const scssProcessor = ( maxWorkers: number | undefined, ): StylePreprocessor<SassStylePreprocessorInternalOptions>...
```suggestion let sassPackage = loadSassPackage(root, failedSassEmbedded ?? false) if (failedSassEmbedded === undefined) { // failedSassEmbedded is undefined for the first time try { await import(sassPackage.path) } catch (e) { if (/sass-embedded-[a-z0-9]+-[a-z0-9]+/i.test(e.message)) ...
await compiler?.dispose() compilerPromise = undefined }, } return worker } type ScssWorkerResult = { css: string map?: string | undefined stats: { includedFiles: string[] } } const scssProcessor = ( maxWorkers: number | undefined, ): StylePreprocessor<SassStylePreprocessorInternalOptions>...
@@ -2511,13 +2520,14 @@ const scssProcessor = ( maxWorkers: number | undefined, ): StylePreprocessor<SassStylePreprocessorInternalOptions> => { let worker: ReturnType<typeof makeScssWorker> | undefined + let failedSassEmbedded = false return { close() { worker?.stop() }, async process...
packages/vite/src/node/plugins/css.ts
26
TypeScript
1
bug
545
51
51
false
fix(css): fallback to sass when sass-embedded platform binary is missing
21,002
vitejs/vite
78,557
TypeScript
sapphi-red
taearls
} return worker } type ScssWorkerResult = { css: string map?: string | undefined stats: { includedFiles: string[] } } const scssProcessor = ( maxWorkers: number | undefined, ): StylePreprocessor<SassStylePreprocessorInternalOptions> => { let worker: ReturnType<typeof makeScssWorker> | undefined retu...
```suggestion let sassPackage = loadSassPackage(root, failedSassEmbedded ?? false) // failedSassEmbedded is undefined for the first time if (failedSassEmbedded === undefined) { failedSassEmbedded = false ``` I think we need to set `failedSassEmbedded` here and hoist `let failedSassEmbedd...
} return worker } type ScssWorkerResult = { css: string map?: string | undefined stats: { includedFiles: string[] } } const scssProcessor = ( maxWorkers: number | undefined, ): StylePreprocessor<SassStylePreprocessorInternalOptions> => { let worker: ReturnType<typeof makeScssWorker> | undefined let f...
@@ -2517,7 +2526,21 @@ const scssProcessor = ( worker?.stop() }, async process(environment, source, root, options, resolvers) { - const sassPackage = loadSassPackage(root) + let failedSassEmbedded: boolean | undefined + let sassPackage = loadSassPackage(root, failedSassEmbedded ?? false)...
packages/vite/src/node/plugins/css.ts
26
TypeScript
1
bug
451
51
51
false
fix(css): fallback to sass when sass-embedded platform binary is missing
21,002
vitejs/vite
78,557
TypeScript
sapphi-red
taearls
return worker } type ScssWorkerResult = { css: string map?: string | undefined stats: { includedFiles: string[] } } const scssProcessor = ( maxWorkers: number | undefined, ): StylePreprocessor<SassStylePreprocessorInternalOptions> => { let worker: ReturnType<typeof makeScssWorker> | undefined let faile...
```suggestion if (failedSassEmbedded === undefined) { failedSassEmbedded = false ```
return worker } type ScssWorkerResult = { css: string map?: string | undefined stats: { includedFiles: string[] } } const scssProcessor = ( maxWorkers: number | undefined, ): StylePreprocessor<SassStylePreprocessorInternalOptions> => { let worker: ReturnType<typeof makeScssWorker> | undefined let faile...
@@ -2511,13 +2520,28 @@ const scssProcessor = ( maxWorkers: number | undefined, ): StylePreprocessor<SassStylePreprocessorInternalOptions> => { let worker: ReturnType<typeof makeScssWorker> | undefined + let failedSassEmbedded: boolean | undefined return { close() { worker?.stop() }, ...
packages/vite/src/node/plugins/css.ts
26
TypeScript
1
bug
101
51
51
false
fix(css): fallback to sass when sass-embedded platform binary is missing
21,002
vitejs/vite
78,557
TypeScript
sapphi-red
taearls
link: '/config/worker-options', }, ], }, ], '/changes/': [ { text: 'Breaking Changes', link: '/changes/', }, { text: 'Current', items: [], }, { text: 'Future', item...
`transformPageData` was previously use for reasons mentioned at https://github.com/vitejs/vite/pull/15984. However, I can't seem to replicate the issue now. We're only generating one `.html` file which servers would use for both `/path` and `/path.html`. There's no way that canonical links were only added to `/path.htm...
{ text: 'Move to Per-environment APIs', link: '/changes/per-environment-apis', }, { text: 'SSR Using ModuleRunner API', link: '/changes/ssr-using-modulerunner', }, { text: 'Shared Plugins Du...
@@ -468,16 +443,34 @@ export default defineConfig({ level: [2, 3], }, }, - transformPageData(pageData) { - const canonicalUrl = `${ogUrl}/${pageData.relativePath}` - .replace(/\/index\.md$/, '/') - .replace(/\.md$/, '') - pageData.frontmatter.head ??= [] - pageData.frontmatter.head.un...
docs/.vitepress/config.ts
26
TypeScript
0.857
suggestion
452
51
51
false
docs(landing): optimize fonts loading
21,075
vitejs/vite
78,557
TypeScript
bluwy
bluwy
source, ) this.error(message, showCodeFrame ? e.idx : undefined) } const depsOptimizer = environment.depsOptimizer // since we are already in the transform phase of the importer, it must // have been loaded so its entry is guaranteed in the module graph. const i...
I guess we need to keep this line. What was the reason to remove this line?
const e = _e as EsModuleLexerParseError const { message, showCodeFrame } = createParseErrorInfo( importer, source, ) this.error(message, showCodeFrame ? e.idx : undefined) } const depsOptimizer = environment.depsOptimizer // since we are already in...
@@ -296,7 +296,17 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin { !imports.length && !(this as unknown as TransformPluginContext)._addedImports ) { - importerModule.isSelfAccepting = false
packages/vite/src/node/plugins/importAnalysis.ts
26
TypeScript
0.357
refactor
75
51
51
false
fix(hmr): trigger prune event when last import is removed (#20781)
21,093
vitejs/vite
78,557
TypeScript
sapphi-red
almadoro
import './dep2.js'
Would you add a separate test for the previous one so that we have a test that covers the non-early-return path?
import './dep2.js' import './dep3.js'
playground/hmr/prune/dep1.js
1
JavaScript
0.286
question
112
2
3
false
fix(hmr): trigger prune event when last import is removed (#20781)
21,093
vitejs/vite
78,557
TypeScript
sapphi-red
almadoro
if ( Object.values(builder.environments).every( (environment) => !environment.isBuilt, ) ) { for (const environment of Object.values(builder.environments)) { await builder.build(environment) } } }, async build( environment: BuildEnviron...
I have to admit I have no idea why this condition was written this way before. I can see it was initially added in https://github.com/vitejs/vite/pull/8762 but couldn't figure out why it was there. Changing this also doesn't seem to fail any test, so I suppose it isn't very critical. I think it makes more sense for ...
hostType: string, ) => string | { runtime: string }, ): string | { runtime: string } { const { experimental, base, decodedBase } = environment.config const ssr = environment.config.consumer === 'server' // was !!environment.config.build.ssr const { renderBuiltUrl } = experimental let relative = base === '...
@@ -1404,7 +1404,7 @@ export function toOutputFilePathInJS( return result } } - if (relative && !ssr) {
packages/vite/src/node/build.ts
26
TypeScript
0.643
bug
653
51
51
false
feat(wasm): add SSR support for `.wasm?init`
21,102
vitejs/vite
78,557
TypeScript
upsuper
upsuper
const { default: light } = await import('../light.wasm?init') let result const instance = await light({ imports: { imported_func: (res) => (result = res), }, }) expect(instance instanceof WebAssembly.Instance).toBe(true) // @ts-ignore instance.exports.exported_func() ...
We can remove these tests as it's covered by the new `ssr-wasm` playground.
import { expect, test } from 'vitest' import { isBuild, page } from '~utils' test('should work when inlined', async () => { await page.click('.inline-wasm .run') await expect .poll(() => page.textContent('.inline-wasm .result')) .toMatch('42') }) test('should work when output', async () => { await page....
@@ -1,33 +1,67 @@ -import { expect, test } from 'vitest' +import { describe, expect, test } from 'vitest' import { isBuild, page } from '~utils' -test('should work when inlined', async () => { - await page.click('.inline-wasm .run') - await expect - .poll(() => page.textContent('.inline-wasm .result')) - .to...
playground/wasm/__tests__/wasm.spec.ts
26
TypeScript
0.571
suggestion
75
28
34
false
feat(wasm): add SSR support for `.wasm?init`
21,102
vitejs/vite
78,557
TypeScript
sapphi-red
upsuper
} return } const shortcut = shortcuts.find((shortcut) => shortcut.key === input) if (!shortcut || shortcut.action == null) return actionRunning = true await shortcut.action(server) actionRunning = false } const rl = readline.createInterface({ input: process.stdin }) server...
```suggestion server._rl ??= readline.createInterface({ input: process.stdin }) const rl = server._rl rl.removeAllListeners('line') ``` I wonder if this is better as this way we can avoid the destruction / initialization cost.
server.config.logger.info( colors.dim(' press ') + colors.bold(`${shortcut.key} + enter`) + colors.dim(` to ${shortcut.description}`), ) } return } const shortcut = shortcuts.find((shortcut) => shortcut.key === input) if (!shortcut || shortcut...
@@ -88,6 +96,10 @@ export function bindCLIShortcuts<Server extends ViteDevServer | PreviewServer>( } const rl = readline.createInterface({ input: process.stdin }) + + server._rl?.close() + server._rl = rl +
packages/vite/src/node/shortcuts.ts
26
TypeScript
1
suggestion
239
51
51
false
fix: allow multiple `bindCLIShortcuts` calls with shortcut merging
21,103
vitejs/vite
78,557
TypeScript
sapphi-red
edmundhung
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { createServer } from '../server' import { preview } from '../preview' import { bindCLIShortcuts } from '../shortcuts' describe('bindCLIShortcuts', () => { const originalIsTTY = process.stdin.isTTY beforeEach(() => { process.std...
To avoid these stubs, would you add a third parameter to `bindCLIShortcuts` that can bypass the `isTTY` & `CI` check?
import { describe, expect, test, vi } from 'vitest' import { createServer } from '../server' import { preview } from '../preview' import { bindCLIShortcuts } from '../shortcuts' describe('bindCLIShortcuts', () => { test.each([ ['dev server', () => createServer()], ['preview server', () => preview()], ])('b...
@@ -0,0 +1,74 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { createServer } from '../server' +import { preview } from '../preview' +import { bindCLIShortcuts } from '../shortcuts' + +describe('bindCLIShortcuts', () => { + const originalIsTTY = process.stdin.isTTY + + beforeEa...
packages/vite/src/node/__tests__/shortcuts.spec.ts
17
TypeScript
0.714
question
117
42
42
false
fix: allow multiple `bindCLIShortcuts` calls with shortcut merging
21,103
vitejs/vite
78,557
TypeScript
sapphi-red
edmundhung
} export type CLIShortcut<Server = ViteDevServer | PreviewServer> = { key: string description: string action?(server: Server): void | Promise<void> } export function bindCLIShortcuts<Server extends ViteDevServer | PreviewServer>( server: Server, opts?: BindCLIShortcutsOptions<Server>, enabled: boolean = p...
```suggestion if (!customShortcuts.some((s) => s.key === shortcut.key)) { ```
} export type CLIShortcut<Server = ViteDevServer | PreviewServer> = { key: string description: string action?(server: Server): void | Promise<void> } export function bindCLIShortcuts<Server extends ViteDevServer | PreviewServer>( server: Server, opts?: BindCLIShortcutsOptions<Server>, enabled: boolean = p...
@@ -28,15 +28,28 @@ export type CLIShortcut<Server = ViteDevServer | PreviewServer> = { export function bindCLIShortcuts<Server extends ViteDevServer | PreviewServer>( server: Server, opts?: BindCLIShortcutsOptions<Server>, + enabled: boolean = process.stdin.isTTY && !process.env.CI, ): void { - if (!server.h...
packages/vite/src/node/shortcuts.ts
26
TypeScript
0.857
suggestion
83
51
51
false
fix: allow multiple `bindCLIShortcuts` calls with shortcut merging
21,103
vitejs/vite
78,557
TypeScript
sapphi-red
edmundhung
build.onLoad({ filter: /\.[cm]?[jt]s$/ }, async (args) => { const contents = await fsp.readFile(args.path, 'utf-8') let injectValues = `const ${dirnameVarName} = ${JSON.stringify( path.dirname(args.path), )};` + `const ${filenam...
```suggestion let firstLineEndIndex = contents.indexOf('\n') if (firstLineEndIndex < 0) firstLineEndIndex = contents.length ```
build.onLoad({ filter: /\.[cm]?[jt]s$/ }, async (args) => { const contents = await fsp.readFile(args.path, 'utf-8') let injectValues = `const ${dirnameVarName} = ${JSON.stringify( path.dirname(args.path), )};` + `const ${filenam...
@@ -2044,9 +2044,21 @@ async function bundleConfigFile( } } + let injectedContents: string + if (contents.startsWith('#!')) { + // hashbang + const firstLineEndIndex = contents.indexOf('\n')
packages/vite/src/node/config.ts
26
TypeScript
1
suggestion
158
51
51
false
fix(config): handle shebang properly
21,158
vitejs/vite
78,557
TypeScript
sapphi-red
sapphi-red
// Keep the same connect instance so app.use(vite.middlewares) works // after a restart in middlewareMode (.route is always '/') middlewares.stack = newServer.middlewares.stack server.middlewares = middlewares // Rebind internal server variable so functions reference the user server newServer._...
```suggestion bindCLIShortcuts( server, shortcutsOptions, // Skip environment checks since shortcuts were bound before restart true, ) ``` Just to make it clear which parameter this comment is referring to.
// Keep the same connect instance so app.use(vite.middlewares) works // after a restart in middlewareMode (.route is always '/') middlewares.stack = newServer.middlewares.stack server.middlewares = middlewares // Rebind internal server variable so functions reference the user server newServer._...
@@ -1278,7 +1280,8 @@ async function restartServer(server: ViteDevServer) { if (shortcutsOptions) { shortcutsOptions.print = false - bindCLIShortcuts(server, shortcutsOptions) + // Skip environment checks since shortcuts were bound before restart + bindCLIShortcuts(server, shortcutsOptions, true)
packages/vite/src/node/server/index.ts
26
TypeScript
1
suggestion
248
51
51
false
fix: shortcuts not rebound after server restart
21,166
vitejs/vite
78,557
TypeScript
sapphi-red
edmundhung
moduleGraph: EnvironmentModuleGraph, ): string { calculateOffsetOnce() return stack .split('\n') .map((line) => { return line.replace( /^ {4}at (?:(\S.*?)\s\()?(.+?):(\d+)(?::(\d+))?\)?/, (input, varName, id, line, column) => { if (!id) return input const mod = m...
Maybe `alreadyRewritten = line` while showing the problematic line in the warning. (Also maybe one sentence explaining what `line` is expected to be instead.) Just an idea, the warning alone is already quite a neat improvement. This PR LGTM as-is.
moduleGraph: EnvironmentModuleGraph, ): { result: string; alreadyRewritten: boolean } { calculateOffsetOnce() let alreadyRewritten = false const rewritten = stack .split('\n') .map((line) => { return line.replace( /^ {4}at (?:(\S.*?)\s\()?(.+?):(\d+)(?::(\d+))?\)?/, (input, varNam...
@@ -41,13 +43,15 @@ export function ssrRewriteStacktrace( } const traced = new TraceMap(rawSourceMap as any) + const line = Number(originalLine) - offset + // stacktrace's column is 1-indexed, but sourcemap's one is 0-indexed + const column = Number(originalColumn) - 1...
packages/vite/src/node/ssr/ssrStacktrace.ts
26
TypeScript
0.786
suggestion
250
51
51
false
feat(ssr): avoid errors when rewriting already rewritten stacktrace
21,269
vitejs/vite
78,557
TypeScript
brillout
sapphi-red
} // check if there are actual env variables starting with VITE_* // these are typically provided inline and should be prioritized for (const key in process.env) { if (prefixes.some((prefix) => key.startsWith(prefix))) { env[key] = process.env[key] as string } } debug?.(`using resolved env: ...
```suggestion if (envPrefix.some((prefix) => prefix.includes(' '))) { ``` I think we can avoid a regex here
} } // check if there are actual env variables starting with VITE_* // these are typically provided inline and should be prioritized for (const key in process.env) { if (prefixes.some((prefix) => key.startsWith(prefix))) { env[key] = process.env[key] as string } } debug?.(`using resolved...
@@ -99,5 +99,10 @@ export function resolveEnvPrefix({ `envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`, ) } + if (envPrefix.some((prefix) => /\s/.test(prefix))) {
packages/vite/src/node/env.ts
26
TypeScript
1
suggestion
110
32
36
false
feat: warn if `envPrefix` contains spaces
21,292
vitejs/vite
78,557
TypeScript
bluwy
btea
// these are typically provided inline and should be prioritized for (const key in process.env) { if (prefixes.some((prefix) => key.startsWith(prefix))) { env[key] = process.env[key] as string } } debug?.(`using resolved env: %O`, env) return env } export function resolveEnvPrefix({ envPref...
```suggestion `[vite] Warning: envPrefix option contains values with whitespace, which does not work in practice.`, ``` Maybe we can be a bit more accurate as we know it wont work in practice as env vars cant have whitespaces.
// these are typically provided inline and should be prioritized for (const key in process.env) { if (prefixes.some((prefix) => key.startsWith(prefix))) { env[key] = process.env[key] as string } } debug?.(`using resolved env: %O`, env) return env } export function resolveEnvPrefix({ envPref...
@@ -99,5 +100,13 @@ export function resolveEnvPrefix({ `envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`, ) } + if (envPrefix.some((prefix) => /\s/.test(prefix))) { + // eslint-disable-next-line no-console + console.warn( + colors.yellow( + ...
packages/vite/src/node/env.ts
26
TypeScript
1
suggestion
235
32
32
false
feat: warn if `envPrefix` contains spaces
21,292
vitejs/vite
78,557
TypeScript
bluwy
btea
}, 'serve', ) expect( testRolldownOptions.environments.ssr.build.rolldownOptions.platform, ).toBe('neutral') expect( testRolldownOptions.environments.client.build.rolldownOptions.platform, ).toBe('browser') }) }) describe('resolveEnvPrefix', () => { test(`use 'VITE_' as ...
```suggestion test(`show a warning message if envPrefix contains a whitespace`, () => { ```
}, 'serve', ) expect( testRolldownOptions.environments.ssr.build.rolldownOptions.platform, ).toBe('neutral') expect( testRolldownOptions.environments.client.build.rolldownOptions.platform, ).toBe('browser') }) }) describe('resolveEnvPrefix', () => { test(`use 'VITE_' as ...
@@ -632,9 +632,22 @@ describe('resolveEnvPrefix', () => { expect(() => resolveEnvPrefix(config)).toThrow() }) + test(`throw a warning message if envPrefix contains whitespace`, () => {
packages/vite/src/node/__tests__/config.spec.ts
26
TypeScript
0.857
suggestion
95
51
51
false
feat: warn if `envPrefix` contains spaces
21,292
vitejs/vite
78,557
TypeScript
sapphi-red
btea
), ).toMatchInlineSnapshot( `"repro(new Worker(new URL(/* @vite-ignore */ "/worker?worker_file&type=classic", '' + import.meta.url)), { type: "module" })"`, ) }) test('with multi-line new URL and trailing comma', async () => { expect( await transform(`new Worker( new URL( "./wor...
@copilot ```suggestion "./worker.js", ```
), ).toMatchInlineSnapshot( `"repro(new Worker(new URL(/* @vite-ignore */ "/worker?worker_file&type=classic", '' + import.meta.url)), { type: "module" })"`, ) }) test('with multi-line new URL and trailing comma', async () => { expect( await transform(`new Worker( new URL( "./wor...
@@ -221,4 +221,36 @@ new Worker( `"repro(new Worker(new URL(/* @vite-ignore */ "/worker?worker_file&type=classic", '' + import.meta.url)), { type: "module" })"`, ) }) + + test('with multi-line new URL and trailing comma', async () => { + expect( + await transform(`new Worker( + new URL( + "....
packages/vite/src/node/__tests__/plugins/workerImportMetaUrl.spec.ts
26
TypeScript
0.786
suggestion
49
39
39
false
fix(worker): handle `new Worker(..., new URL(import.meta.url))` with trailing comma
21,325
vitejs/vite
78,557
TypeScript
sapphi-red
Copilot
> = { chrome: 'chrome', edge: 'edge', firefox: 'firefox', hermes: false, ie: 'ie', ios: 'ios_saf', node: false, opera: 'opera', rhino: false, safari: 'safari', } const esMap: Record<number, string[]> = { // https://caniuse.com/?search=es2015 2015: ['chrome49', 'edge13', 'safari10', 'ios10', 'fi...
```suggestion 2020: ['chrome80', 'edge80', 'safari14.1', 'ios14.5', 'firefox80', 'opera67'], ```
> = { chrome: 'chrome', edge: 'edge', firefox: 'firefox', hermes: false, ie: 'ie', ios: 'ios_saf', node: false, opera: 'opera', rhino: false, safari: 'safari', } const esMap: Record<number, string[]> = { // https://caniuse.com/?search=es2015 2015: ['chrome49', 'edge13', 'safari10', 'ios10', 'fi...
@@ -3387,25 +3387,39 @@ const map: Record< const esMap: Record<number, string[]> = { // https://caniuse.com/?search=es2015 - 2015: ['chrome49', 'edge13', 'safari10', 'firefox44', 'opera36'], + 2015: ['chrome49', 'edge13', 'safari10', 'ios10', 'firefox44', 'opera36'], // https://caniuse.com/?search=es2016 - ...
packages/vite/src/node/plugins/css.ts
26
TypeScript
1
suggestion
100
51
51
false
feat: add ios to default esbuild targets
21,342
vitejs/vite
78,557
TypeScript
sapphi-red
illusionaries
edge: 'edge', firefox: 'firefox', hermes: false, ie: 'ie', ios: 'ios_saf', node: false, opera: 'opera', rhino: false, safari: 'safari', } const esMap: Record<number, string[]> = { // https://caniuse.com/?search=es2015 2015: ['chrome49', 'edge13', 'safari10', 'ios10', 'firefox44', 'opera36'], //...
```suggestion 2021: ['chrome85', 'edge85', 'safari14.1', 'ios14.5', 'firefox80', 'opera71'], ```
edge: 'edge', firefox: 'firefox', hermes: false, ie: 'ie', ios: 'ios_saf', node: false, opera: 'opera', rhino: false, safari: 'safari', } const esMap: Record<number, string[]> = { // https://caniuse.com/?search=es2015 2015: ['chrome49', 'edge13', 'safari10', 'ios10', 'firefox44', 'opera36'], //...
@@ -3387,25 +3387,39 @@ const map: Record< const esMap: Record<number, string[]> = { // https://caniuse.com/?search=es2015 - 2015: ['chrome49', 'edge13', 'safari10', 'firefox44', 'opera36'], + 2015: ['chrome49', 'edge13', 'safari10', 'ios10', 'firefox44', 'opera36'], // https://caniuse.com/?search=es2016 - ...
packages/vite/src/node/plugins/css.ts
26
TypeScript
1
suggestion
100
51
51
false
feat: add ios to default esbuild targets
21,342
vitejs/vite
78,557
TypeScript
sapphi-red
illusionaries
*/ disabled?: boolean | 'build' | 'dev' /** * Automatic dependency discovery. When `noDiscovery` is true, only dependencies * listed in `include` will be optimized. The scanner isn't run for cold start * in this case. CJS-only dependencies must be present in `include` during dev. * @default false ...
```suggestion * When enabled, Vite will not throw an error when an outdated optimized * dependency is requested. Enabling this option may cause a single module * to have a multiple reference. * @default false * @experimental ```
*/ disabled?: boolean | 'build' | 'dev' /** * Automatic dependency discovery. When `noDiscovery` is true, only dependencies * listed in `include` will be optimized. The scanner isn't run for cold start * in this case. CJS-only dependencies must be present in `include` during dev. * @default false ...
@@ -163,6 +163,13 @@ export interface DepOptimizationConfig { * @experimental */ holdUntilCrawlEnd?: boolean + /** + * When enabled, Vite will not throw an error when an outdated optimized + * dependency is requested. + * @default false + * @experimental
packages/vite/src/node/optimizer/index.ts
26
TypeScript
1
performance
249
51
51
false
feat: add `ignoreOutdatedRequests` option to `optimizeDeps`
21,364
vitejs/vite
78,557
TypeScript
sapphi-red
jamesopstad
/* eslint-disable n/no-unsupported-features/node-builtins */ import type { ResolveFnOutput, ResolveHookContext } from 'node:module' export type ImportMetaResolver = (specifier: string, importer: string) => string const customizationHookNamespace = 'vite-module-runner:import-meta-resolve/v1/' const customizationHooks...
Can we use `// eslint-disable-next-line n/no-unsupported-features/node-builtins -- reason` instead?
import type { ResolveFnOutput, ResolveHookContext } from 'node:module' export type ImportMetaResolver = (specifier: string, importer: string) => string const customizationHookNamespace = 'vite-module-runner:import-meta-resolve/v1/' const customizationHooksModule = /* js */ ` export async function resolve(specifier, ...
@@ -1,3 +1,5 @@ +/* eslint-disable n/no-unsupported-features/node-builtins */
packages/vite/src/module-runner/importMetaResolver.ts
1
TypeScript
0.571
question
99
26
26
false
fix(module-runner): use `process.getBuiltinModule` instead of `import('node:module')`
21,402
vitejs/vite
78,557
TypeScript
sapphi-red
sheremet-va
--interactive / --no-interactive force interactive / non-interactive mode Available templates: ${yellow ('vanilla-ts vanilla' )} ${green ('vue-ts vue' )} ${cyan ('react-ts react' )} ${cyan ('react-compiler-ts react-compiler')} ${cyan ...
We think that the description doesn't help users much as the user won't be able to choose the templates only with that description and would need to open the website anyway. We also prefer to avoid maintaining the description. As a conclusion, we think we should not add the description, but have the links.
Available templates: ${yellow ('vanilla-ts vanilla' )} ${green ('vue-ts vue' )} ${cyan ('react-ts react' )} ${cyan ('react-compiler-ts react-compiler')} ${cyan ('react-swc-ts react-swc' )} ${magenta ('preact-ts preac...
@@ -68,6 +71,8 @@ type Framework = { type FrameworkVariant = { name: string display: string + description?: string + link?: `https://${string}`
packages/create-vite/src/index.ts
26
TypeScript
0.643
suggestion
308
51
51
false
feat(create-vite): show links for meta-framework variants
21,403
vitejs/vite
78,557
TypeScript
sapphi-red
brillout
let template = argTemplate let hasInvalidArgTemplate = false if (argTemplate && !TEMPLATES.includes(argTemplate)) { template = undefined hasInvalidArgTemplate = true } if (!template) { if (interactive) { const framework = await prompts.select({ message: hasInvalidArgTemplate ...
We think we should keep this as-is as "(listed first)" and "(listed last)" won't clearly tell which one is the template and which one is the framework.
} }), }) if (prompts.isCancel(variant)) return cancel() template = variant } else { template = 'vanilla-ts' } } const pkgManager = pkgInfo ? pkgInfo.name : 'npm' const root = path.join(cwd, targetDir) // determine template let isReactSwc = false if (templ...
@@ -572,19 +617,13 @@ async function init() { if (prompts.isCancel(framework)) return cancel() const variant = await prompts.select({ - message: 'Select a variant:', + message: !['react', 'vue', 'solid'].includes(framework.name) + ? 'Select a variant:' + : `Select ${bold(...
packages/create-vite/src/index.ts
26
TypeScript
0.5
suggestion
151
51
51
false
feat(create-vite): show links for meta-framework variants
21,403
vitejs/vite
78,557
TypeScript
sapphi-red
brillout
if (id.startsWith(optionalPeerDepNamespace)) { const path = id.slice(optionalPeerDepNamespace.length) const [, peerDep, parentDep] = path.split(':') return { code: 'module.exports = {};' + `throw new Error(\`Could not resolve "$...
We shouldn't use absolute paths here so that the optimized cache doesn't rely on the project path. I think we should generate a resolved relative path to the file from the output file path.
}))`, } } } if (id.startsWith(optionalPeerDepNamespace)) { const path = id.slice(optionalPeerDepNamespace.length) const [, peerDep, parentDep] = path.split(':') return { code: 'module.exports = {};' + ...
@@ -298,6 +300,45 @@ export function rolldownDepPlugin( } }, }, + transform: { + filter: { code: /new\s+URL/ }, + async handler(code, id) { + if (!id.includes('node_modules')) return null + + const s = new MagicString(code) + + const workerRE = + ...
packages/vite/src/node/optimizer/rolldownDepPlugin.ts
26
TypeScript
0.5
performance
189
51
51
false
fix(optimizer): map relative `new URL` paths to correct relative file location
21,434
vitejs/vite
78,557
TypeScript
sapphi-red
guyco3
let hasReplacements = false let match while ((match = workerRE.exec(code))) { hasReplacements = true const [fullMatch, prefix, _, url] = match const absolutePath = path.resolve(path.dirname(id), url) const relativePath = path.relative(bundleD...
I guess this part is not needed because it'll be handled by the other internal plugins.
let match: RegExpExecArray | null while ((match = assetImportMetaUrlRE.exec(cleanString))) { const [[startIndex, endIndex], [urlStart, urlEnd]] = match.indices! if (hasViteIgnoreRE.test(code.slice(startIndex, urlStart))) continue const rawUrl = code.slice(urlSta...
@@ -298,6 +300,53 @@ export function rolldownDepPlugin( } }, }, + transform: { + filter: { code: /new\s+URL/ }, + async handler(code, id) { + if (!id.includes('node_modules')) return null + + const s = new MagicString(code) + + const workerRE = + ...
packages/vite/src/node/optimizer/rolldownDepPlugin.ts
26
TypeScript
0.643
suggestion
87
51
51
false
fix(optimizer): map relative `new URL` paths to correct relative file location
21,434
vitejs/vite
78,557
TypeScript
sapphi-red
guyco3
} }))`, } } } if (id.startsWith(optionalPeerDepNamespace)) { const path = id.slice(optionalPeerDepNamespace.length) const [, peerDep, parentDep] = path.split(':') return { code: 'module.exports =...
> Improved Regex: Refined the transformation logic to target new Worker(new URL(...)) and new SharedWorker(...) constructors specifically. This prevents accidental transformation of standard assets (images, data files) that use new URL but are not workers. We have the same issue with non-worker assets. Was there a s...
key !== 'constructor' && key !== 'splice' ) { console.warn(\`Module "${path}" has been externalized for browser compatibility. Cannot access "${path}.\${key}" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for mor...
@@ -298,6 +300,53 @@ export function rolldownDepPlugin( } }, }, + transform: { + filter: { code: /new\s+URL/ }, + async handler(code, id) { + if (!id.includes('node_modules')) return null + + const s = new MagicString(code) + + const workerRE = + ...
packages/vite/src/node/optimizer/rolldownDepPlugin.ts
26
TypeScript
0.643
question
443
51
51
false
fix(optimizer): map relative `new URL` paths to correct relative file location
21,434
vitejs/vite
78,557
TypeScript
sapphi-red
guyco3
key !== 'splice' ) { console.warn(\`Module "${path}" has been externalized for browser compatibility. Cannot access "${path}.\${key}" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`) } } ...
```suggestion ``` If the file is bundled by the optimizer, I think we need to resolve the path in `new URL`.
get(_, key) { if ( key !== '__esModule' && key !== '__proto__' && key !== 'constructor' && key !== 'splice' ) { console.warn(\`Module "${path}" has been externalized for browser compatibility. Cannot access "${path}.\${key}" in client c...
@@ -298,6 +300,53 @@ export function rolldownDepPlugin( } }, }, + transform: { + filter: { code: /new\s+URL/ }, + async handler(code, id) { + if (!id.includes('node_modules')) return null +
packages/vite/src/node/optimizer/rolldownDepPlugin.ts
26
TypeScript
1
performance
110
51
51
false
fix(optimizer): map relative `new URL` paths to correct relative file location
21,434
vitejs/vite
78,557
TypeScript
sapphi-red
guyco3
code: 'module.exports = {};' + `throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)`, } } }, }, transform: { filter: { code: /new\s+URL/ }, async handler(code, id) { ...
Let's skip URLs that starts with protocols: ```js if (isDataUrl(url)) { continue } ``` and `new URL` with `/* @vite-ignore */`. I think you can copy some code from https://github.com/vitejs/vite/blob/ebda8fd3c14f60e63d13d22102cb3d79a12f47a9/packages/vite/src/node/plugins/assetImportMetaUrl.ts#L62-L75
if (id.startsWith(optionalPeerDepNamespace)) { const path = id.slice(optionalPeerDepNamespace.length) const [, peerDep, parentDep] = path.split(':') return { code: 'module.exports = {};' + `throw new Error(\`Could not resolve "...
@@ -298,6 +300,53 @@ export function rolldownDepPlugin( } }, }, + transform: { + filter: { code: /new\s+URL/ }, + async handler(code, id) { + if (!id.includes('node_modules')) return null + + const s = new MagicString(code) + + const workerRE = + ...
packages/vite/src/node/optimizer/rolldownDepPlugin.ts
26
TypeScript
0.929
suggestion
314
51
51
false
fix(optimizer): map relative `new URL` paths to correct relative file location
21,434
vitejs/vite
78,557
TypeScript
sapphi-red
guyco3
<script setup lang="ts"> defineProps<{ href: string title: string }>() </script> <template> <div class="scrimba"> <span class="play-button"> <span class="play-icon"></span> </span> <a :href="href" target="_blank" rel="sponsored noopener" :title="title"> <slot>Watch an interactive lesson o...
```suggestion margin: 16px 0; color: var(--vp-custom-block-info-text); background-color: var(--vp-custom-block-info-bg); border: 1px solid var(--vp-custom-block-info-border); padding: 16px 20px; ``` I'd like to tweak the style a bit to match the `::: info` block.
<script setup lang="ts"> defineProps<{ href: string title: string }>() </script> <template> <div class="scrimba"> <span class="play-button"> <span class="play-icon"></span> </span> <a :href="href" target="_blank" rel="sponsored noopener" :title="title"> <slot>Watch an interactive lesson o...
@@ -0,0 +1,54 @@ +<script setup lang="ts"> +defineProps<{ + href: string + title: string +}>() +</script> + +<template> + <div class="scrimba"> + <span class="play-button"> + <span class="play-icon"></span> + </span> + <a :href="href" target="_blank" rel="sponsored noopener" :title="title"> + <slo...
docs/.vitepress/theme/components/ScrimbaLink.vue
23
Vue
1
suggestion
280
48
48
false
docs: add Scrimba tutorial links across documentation
21,467
vitejs/vite
78,557
TypeScript
sapphi-red
perborgen
function resolveResolveOptions( resolve: AllResolveOptions | undefined, logger: Logger, ): ResolvedAllResolveOptions { // resolve alias with internal client alias const alias = normalizeAlias( mergeAlias(clientAlias, resolve?.alias || configDefaults.resolve.alias), ) const preserveSymlinks = resolv...
```suggestion `Please use a custom plugin with a resolveId hook instead.`, ```
function resolveResolveOptions( resolve: AllResolveOptions | undefined, logger: Logger, ): ResolvedAllResolveOptions { // resolve alias with internal client alias const alias = normalizeAlias( mergeAlias(clientAlias, resolve?.alias || configDefaults.resolve.alias), ) const preserveSymlinks = resolve...
@@ -1100,6 +1100,15 @@ function resolveResolveOptions( ), ) } + if (alias.some((a) => a.customResolver)) { + logger.warn( + colors.yellow( + `\`resolve.alias\` contains an alias with \`customResolver\` option. ` + + `This is deprecated and will be removed in Vite 9. ` + + ...
packages/vite/src/node/config.ts
26
TypeScript
0.857
suggestion
88
51
51
false
refactor: deprecate `customResolver` in `resolve.alias`
21,476
vitejs/vite
78,557
TypeScript
sapphi-red
sapphi-red
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the S...
```suggestion * @deprecated Use a custom plugin with resolveId hook instead ```
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the S...
@@ -36,6 +36,7 @@ export interface Alias { * Instructs the plugin to use an alternative resolving algorithm, * rather than the Rollup's resolver. * @default null + * @deprecated Use a custom plugin instead
packages/vite/src/types/alias.d.ts
26
TypeScript
0.857
suggestion
82
50
50
false
refactor: deprecate `customResolver` in `resolve.alias`
21,476
vitejs/vite
78,557
TypeScript
sapphi-red
sapphi-red
'use strict' module.exports = function xhrAdapter(config) { return new Promise(function (resolve) { var request = new XMLHttpRequest() request.open(config.method, config.url, true) request.onload = function () { resolve({ data: request.responseText }) } request.send() }) }
@copilot let's simplify further more ```suggestion return 'pong' ``` we can also remove https://github.com/vitejs/vite/blob/ca79ccb0d855d40725d446775ec6a8949f8bb89f/playground/optimize-deps/vite.config.js#L60-L75
'use strict' module.exports = function xhrAdapter(config) { return Promise.resolve({ data: 'pong' }) }
@@ -0,0 +1,12 @@ +'use strict' + +module.exports = function xhrAdapter(config) { + return new Promise(function (resolve) { + var request = new XMLHttpRequest() + request.open(config.method, config.url, true) + request.onload = function () { + resolve({ data: request.responseText }) + } + request.se...
playground/optimize-deps/dep-cjs-browser-field/lib/adapters/xhr.js
11
JavaScript
1
performance
222
13
6
false
test(optimize-deps): replace `axios` dependency with local package
21,490
vitejs/vite
78,557
TypeScript
sapphi-red
Copilot
// legacy build if (code.startsWith('#!')) { let secondLinePos = code.indexOf('\n') if (secondLinePos === -1) { secondLinePos = 0 } injectionPoint = secondLinePos ...
@copilot extract this as a variable together with https://github.com/vitejs/vite/blob/870d512b5d354b07e920cd6c5fcf1cdd7a4e3d53/packages/vite/src/node/plugins/css.ts#L1067-L1069
// legacy build if (code.startsWith('#!')) { let secondLinePos = code.indexOf('\n') if (secondLinePos === -1) { secondLinePos = 0 } injectionPoint = secondLinePos ...
@@ -957,7 +969,13 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { } } else { // resolve public URL from CSS paths, we need to use absolute paths - chunkCSS = resolveAssetUrlsInCss(chunkCSS, getCssBundleName()) + // Use 'st...
packages/vite/src/node/plugins/css.ts
26
TypeScript
0.5
refactor
176
51
51
false
fix: populate originalFileNames when resolving CSS asset paths
21,542
vitejs/vite
78,557
TypeScript
sapphi-red
Copilot
object[key] = /^(?:is|get)/.test(name) ? function () { return frame[key].call(frame) } : frame[key] }) object.toString = CallSiteToString return object } function wrapCallSite(frame: CallSite, state: State) { // provides interface backward compatibility if (state === undefin...
```suggestion const column = (frame.getColumnNumber() as number) - 1 ```
object[key] = /^(?:is|get)/.test(name) ? function () { return frame[key].call(frame) } : frame[key] }) object.toString = CallSiteToString return object } function wrapCallSite(frame: CallSite, state: State) { // provides interface backward compatibility if (state === undefin...
@@ -361,15 +361,6 @@ function wrapCallSite(frame: CallSite, state: State) { const line = frame.getLineNumber() as number let column = (frame.getColumnNumber() as number) - 1
packages/vite/src/module-runner/sourcemap/interceptor.ts
26
TypeScript
0.857
suggestion
76
51
51
false
fix(module-runner): incorrect column with `sourcemapInterceptor: "prepareStackTrace"`
21,562
vitejs/vite
78,557
TypeScript
sapphi-red
sapphi-red
{}, { sourcemapInterceptor: 'prepareStackTrace', evaluator: new Evaluator(), }, ) it('should not crash when error stacktrace contains negative column', async ({ runner, }) => { const hook = createHook({ init(_, type) { if (type === 'PROMISE') { new Error(''...
<img width="809" height="810" alt="Image" src="https://github.com/user-attachments/assets/759d61dd-2029-4e16-a143-3161394b7b95" />
import { runInThisContext } from 'node:vm' import { resolve } from 'node:path' import { describe, expect } from 'vitest' import type { ViteDevServer } from '../../..' import type { ModuleRunnerContext } from '../../../../module-runner' import { ESModulesEvaluator } from '../../../../module-runner' import { createFixt...
@@ -135,3 +141,53 @@ describe('module runner initialization', async () => { `) }) }) + +describe('module runner with node:vm executor', async () => { + class Evaluator extends ESModulesEvaluator { + async runInlinedModule(_: ModuleRunnerContext, __: string) { + const code = `\ + await new Promise...
packages/vite/src/node/ssr/runtime/__tests__/server-source-maps.spec.ts
26
TypeScript
0.5
suggestion
130
29
178
false
fix(module-runner): prevent crash on negative column in stacktrace
21,585
vitejs/vite
78,557
TypeScript
AriPerkkio
AriPerkkio
import fs from 'node:fs' import path from 'node:path' import fsp from 'node:fs/promises' import { pathToFileURL } from 'node:url' import { inspect, promisify } from 'node:util' import { performance } from 'node:perf_hooks' import { createRequire } from 'node:module' import crypto from 'node:crypto' import colors from '...
`@vitejs/devtools` is declared as an optional peer dependency, but this file now has a top-level *runtime* import of `normalizeDevToolsConfig` from `@vitejs/devtools/config`. In consumer installs where `@vitejs/devtools` is not installed, importing Vite will throw `ERR_MODULE_NOT_FOUND` before any devtools checks can r...
import fs from 'node:fs' import path from 'node:path' import fsp from 'node:fs/promises' import { pathToFileURL } from 'node:url' import { inspect, promisify } from 'node:util' import { performance } from 'node:perf_hooks' import { createRequire } from 'node:module' import crypto from 'node:crypto' import colors from '...
@@ -15,7 +15,11 @@ import { type RolldownOptions, rolldown, } from 'rolldown' -import type { StartOptions } from '@vitejs/devtools/cli-commands' +import type { + DevToolsConfig, + ResolvedDevToolsConfig, +} from '@vitejs/devtools/config' +import { normalizeDevToolsConfig } from '@vitejs/devtools/config'
packages/vite/src/node/config.ts
22
TypeScript
0.857
suggestion
599
47
47
false
refactor: use internal devtools config
21,609
vitejs/vite
78,557
TypeScript
Copilot
webfansplz
* We recommend using `import.meta.hot` rather than connecting * to the WebSocket server directly. * If you have a usecase that requires connecting to the WebSocket * server, please create an issue so that we can discuss. * * @deprecated */ webSocketToken: string /** @internal ...
`resolveDevToolsConfig` is called during config resolution regardless of whether devtools are enabled, so it should be safe when `@vitejs/devtools` isn't installed. With the current implementation, the required normalizer will already have been imported at module load time. If you move to a dynamic import, also conside...
* to the WebSocket server directly. * If you have a usecase that requires connecting to the WebSocket * server, please create an issue so that we can discuss. * * @deprecated */ webSocketToken: string /** @internal */ fsDenyGlob: AnymatchFn /** @internal */ safeModulePa...
@@ -751,16 +746,7 @@ export async function resolveDevToolsConfig( ): Promise<ResolvedDevToolsConfig> { const resolvedHostname = await resolveHostname(host) const fallbackHostname = resolvedHostname.host ?? 'localhost' - - return { - enabled: config === true || !!(config && config.enabled), - config: { - ...
packages/vite/src/node/config.ts
26
TypeScript
0.857
suggestion
466
51
51
false
refactor: use internal devtools config
21,609
vitejs/vite
78,557
TypeScript
Copilot
webfansplz
* We recommend using `import.meta.hot` rather than connecting * to the WebSocket server directly. * If you have a usecase that requires connecting to the WebSocket * server, please create an issue so that we can discuss. * * @deprecated */ webSocketToken: string /** @internal ...
There are currently no unit tests covering the `devtools` config option, and this change delegates normalization to `@vitejs/devtools/config`. Please add a focused test in `packages/vite/src/node/__tests__/config.spec.ts` (or a new spec) that asserts `resolveConfig` produces the expected `resolved.devtools.enabled` and...
* to the WebSocket server directly. * If you have a usecase that requires connecting to the WebSocket * server, please create an issue so that we can discuss. * * @deprecated */ webSocketToken: string /** @internal */ fsDenyGlob: AnymatchFn /** @internal */ safeModulePa...
@@ -751,16 +746,7 @@ export async function resolveDevToolsConfig( ): Promise<ResolvedDevToolsConfig> { const resolvedHostname = await resolveHostname(host) const fallbackHostname = resolvedHostname.host ?? 'localhost' - - return { - enabled: config === true || !!(config && config.enabled), - config: { - ...
packages/vite/src/node/config.ts
26
TypeScript
0.857
bug
502
51
51
false
refactor: use internal devtools config
21,609
vitejs/vite
78,557
TypeScript
Copilot
webfansplz
import fs from 'node:fs' import path from 'node:path' import fsp from 'node:fs/promises' import { pathToFileURL } from 'node:url' import { inspect, promisify } from 'node:util' import { performance } from 'node:perf_hooks' import { createRequire } from 'node:module' import crypto from 'node:crypto' import colors from '...
Not caused by this PR, but I noticed that we need to do something similar to https://github.com/vitejs/vite/blob/f1a47b36456298029f2a30cfef4e7318d780bad3/packages/vite/types/internal/lightningcssOptions.d.ts#L3-L4 otherwise an error would happen in the typecheck when skipLibCheck is disabled.
import fs from 'node:fs' import path from 'node:path' import fsp from 'node:fs/promises' import { pathToFileURL } from 'node:url' import { inspect, promisify } from 'node:util' import { performance } from 'node:perf_hooks' import { createRequire } from 'node:module' import crypto from 'node:crypto' import colors from '...
@@ -15,7 +15,11 @@ import { type RolldownOptions, rolldown, } from 'rolldown' -import type { StartOptions } from '@vitejs/devtools/cli-commands' +import type { + DevToolsConfig, + ResolvedDevToolsConfig,
packages/vite/src/node/config.ts
20
TypeScript
0.857
suggestion
294
45
45
false
refactor: use internal devtools config
21,609
vitejs/vite
78,557
TypeScript
sapphi-red
webfansplz