wip: use fs watch

This commit is contained in:
bluwy 2023-07-02 16:42:53 +08:00
parent 2d9008e81d
commit 1eb2e065dd
13 changed files with 97 additions and 222 deletions

View File

@ -128,7 +128,6 @@
},
"patchedDependencies": {
"dotenv-expand@9.0.0": "patches/dotenv-expand@9.0.0.patch",
"chokidar@3.5.3": "patches/chokidar@3.5.3.patch",
"sirv@2.0.3": "patches/sirv@2.0.3.patch"
}
},

View File

@ -612,29 +612,6 @@ Repository: chalk/ansi-regex
---------------------------------------
## anymatch
License: ISC
By: Elan Shanker
Repository: https://github.com/micromatch/anymatch
> The ISC License
>
> Copyright (c) 2019 Elan Shanker, Paul Miller (https://paulmillr.com)
>
> Permission to use, copy, modify, and/or distribute this software for any
> purpose with or without fee is hereby granted, provided that the above
> copyright notice and this permission notice appear in all copies.
>
> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
> IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------
## balanced-match
License: MIT
By: Julian Gruber
@ -664,23 +641,6 @@ Repository: git://github.com/juliangruber/balanced-match.git
---------------------------------------
## binary-extensions
License: MIT
By: Sindre Sorhus
Repository: sindresorhus/binary-extensions
> MIT License
>
> Copyright (c) 2019 Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com), Paul Miller (https://paulmillr.com)
>
> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights 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 Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---------------------------------------
## brace-expansion
License: MIT
By: Julian Gruber
@ -768,35 +728,6 @@ Repository: egoist/cac
---------------------------------------
## chokidar
License: MIT
By: Paul Miller, Elan Shanker
Repository: git+https://github.com/paulmillr/chokidar.git
> The MIT License (MIT)
>
> Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com), Elan Shanker
>
> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the “Software”), to deal
> in the Software without restriction, including without limitation the rights
> 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 Software.
>
> THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
> THE SOFTWARE.
---------------------------------------
## commondir
License: MIT
By: James Halliday
@ -1665,23 +1596,6 @@ Repository: git://github.com/isaacs/inherits
---------------------------------------
## is-binary-path
License: MIT
By: Sindre Sorhus
Repository: sindresorhus/is-binary-path
> MIT License
>
> Copyright (c) 2019 Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com), Paul Miller (https://paulmillr.com)
>
> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights 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 Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---------------------------------------
## is-docker
License: MIT
By: Sindre Sorhus
@ -2143,35 +2057,6 @@ Repository: zeit/ms
---------------------------------------
## normalize-path
License: MIT
By: Jon Schlinkert, Blaine Bublitz
Repository: jonschlinkert/normalize-path
> The MIT License (MIT)
>
> Copyright (c) 2014-2018, Jon Schlinkert.
>
> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
> in the Software without restriction, including without limitation the rights
> 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 Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
> THE SOFTWARE.
---------------------------------------
## object-assign
License: MIT
By: Sindre Sorhus
@ -2742,35 +2627,6 @@ Repository: git+https://github.com/TrySound/read-cache.git
---------------------------------------
## readdirp
License: MIT
By: Thorsten Lorenz, Paul Miller
Repository: git://github.com/paulmillr/readdirp.git
> MIT License
>
> Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (https://paulmillr.com)
>
> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
> in the Software without restriction, including without limitation the rights
> 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 Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
> SOFTWARE.
---------------------------------------
## requires-port
License: MIT
By: Arnout Kazemier

View File

@ -91,7 +91,6 @@
"acorn": "^8.9.0",
"acorn-walk": "^8.2.0",
"cac": "^6.7.14",
"chokidar": "^3.5.3",
"connect": "^3.7.0",
"connect-history-api-fallback": "^2.0.0",
"convert-source-map": "^2.0.0",

View File

@ -97,11 +97,6 @@ function createNodePlugins(
// Shim them with eval() so rollup can skip these calls.
isProduction &&
shimDepsPlugin({
// chokidar -> fsevents
'fsevents-handler.js': {
src: `require('fsevents')`,
replacement: `__require('fsevents')`,
},
// postcss-import -> sugarss
'process-content.js': {
src: 'require("sugarss")',

View File

@ -56,7 +56,7 @@ import { findNearestPackageData } from './packages'
import type { PackageCache } from './packages'
import { ensureWatchPlugin } from './plugins/ensureWatch'
import { ESBUILD_MODULES_TARGET, VERSION } from './constants'
import { resolveChokidarOptions } from './watch'
import { resolveWatchOptions } from './watch'
import { completeSystemWrapPlugin } from './plugins/completeSystemWrap'
import { mergeConfig } from './publicUtils'
import { webWorkerPostPlugin } from './plugins/worker'
@ -650,7 +650,7 @@ export async function build(
if (config.build.watch) {
config.logger.info(colors.cyan(`\nwatching for file changes...`))
const resolvedChokidarOptions = resolveChokidarOptions(
const resolvedChokidarOptions = resolveWatchOptions(
config,
config.build.watch.chokidar,
)

View File

@ -65,6 +65,7 @@ export type {
LogType,
LoggerOptions,
} from './logger'
export type { Watcher, WatchEventHandler, WatchOptions } from './watch'
export type {
IndexHtmlTransform,
IndexHtmlTransformHook,
@ -135,11 +136,6 @@ export type {
export type { Connect } from 'dep-types/connect'
export type { WebSocket, WebSocketAlias } from 'dep-types/ws'
export type { HttpProxy } from 'dep-types/http-proxy'
export type {
FSWatcher,
WatchOptions,
AwaitWriteFinishOptions,
} from 'dep-types/chokidar'
export type { Terser } from 'dep-types/terser'
export type { RollupCommonJSOptions } from 'dep-types/commonjs'
export type { RollupDynamicImportVarsOptions } from 'dep-types/dynamicImportVars'

View File

@ -232,10 +232,7 @@ export function esbuildPlugin(config: ResolvedConfig): Plugin {
name: 'vite:esbuild',
configureServer(_server) {
server = _server
server.watcher
.on('add', reloadOnTsconfigChange)
.on('change', reloadOnTsconfigChange)
.on('unlink', reloadOnTsconfigChange)
server.watcher.on((_, file) => reloadOnTsconfigChange(file))
},
buildEnd() {
// recycle serve to avoid preventing Node self-exit (#6815)

View File

@ -5,8 +5,6 @@ import { performance } from 'node:perf_hooks'
import connect from 'connect'
import corsMiddleware from 'cors'
import colors from 'picocolors'
import chokidar from 'chokidar'
import type { FSWatcher, WatchOptions } from 'dep-types/chokidar'
import type { Connect } from 'dep-types/connect'
import launchEditorMiddleware from 'launch-editor-middleware'
import type { SourceMap } from 'rollup'
@ -45,7 +43,8 @@ import type { BindShortcutsOptions } from '../shortcuts'
import { CLIENT_DIR, DEFAULT_DEV_PORT } from '../constants'
import type { Logger } from '../logger'
import { printServerUrls } from '../logger'
import { resolveChokidarOptions } from '../watch'
import type { WatchOptions } from '../watch'
import { Watcher, resolveWatchOptions } from '../watch'
import type { PluginContainer } from './pluginContainer'
import { createPluginContainer } from './pluginContainer'
import type { WebSocketServer } from './ws'
@ -85,8 +84,7 @@ export interface ServerOptions extends CommonServerOptions {
*/
hmr?: HmrOptions | boolean
/**
* chokidar watch options
* https://github.com/paulmillr/chokidar#api
* vite watch options
*/
watch?: WatchOptions
/**
@ -192,10 +190,9 @@ export interface ViteDevServer {
*/
httpServer: http.Server | null
/**
* chokidar watcher instance
* https://github.com/paulmillr/chokidar#api
* vite watcher instance
*/
watcher: FSWatcher
watcher: Watcher
/**
* web socket server with `send(payload)` method
*/
@ -344,11 +341,6 @@ export async function _createServer(
const httpsOptions = await resolveHttpsConfig(config.server.https)
const { middlewareMode } = serverConfig
const resolvedWatchOptions = resolveChokidarOptions(config, {
disableGlobbing: true,
...serverConfig.watch,
})
const middlewares = connect() as Connect.Server
const httpServer = middlewareMode
? null
@ -359,11 +351,10 @@ export async function _createServer(
setClientErrorHandler(httpServer, config.logger)
}
const watcher = chokidar.watch(
// config file dependencies and env file might be outside of root
[root, ...config.configFileDependencies, config.envDir],
resolvedWatchOptions,
) as FSWatcher
const resolvedWatchOptions = resolveWatchOptions(config, serverConfig.watch)
const watcher = new Watcher(resolvedWatchOptions)
// config file dependencies and env file might be outside of root
watcher.add([root, ...config.configFileDependencies, config.envDir])
const moduleGraph: ModuleGraph = new ModuleGraph((url, ssr) =>
container.resolveId(url, undefined, { ssr }),
@ -540,13 +531,9 @@ export async function _createServer(
}
}
const onFileAddUnlink = async (file: string) => {
file = normalizePath(file)
await handleFileAddUnlink(file, server)
await onHMRUpdate(file, true)
}
watcher.on(async (event, file) => {
if (event !== 'change') return
watcher.on('change', async (file) => {
file = normalizePath(file)
// invalidate module graph cache on file change
moduleGraph.onFileChange(file)
@ -554,8 +541,12 @@ export async function _createServer(
await onHMRUpdate(file, false)
})
watcher.on('add', onFileAddUnlink)
watcher.on('unlink', onFileAddUnlink)
watcher.on(async (event, file) => {
if (event !== 'rename') return
file = normalizePath(file)
await handleFileAddUnlink(file, server)
await onHMRUpdate(file, true)
})
ws.on('vite:invalidate', async ({ path, message }: InvalidatePayload) => {
const mod = moduleGraph.urlToModuleMap.get(path)

View File

@ -60,7 +60,6 @@ import * as acorn from 'acorn'
import type { RawSourceMap } from '@ampproject/remapping'
import { TraceMap, originalPositionFor } from '@jridgewell/trace-mapping'
import MagicString from 'magic-string'
import type { FSWatcher } from 'chokidar'
import colors from 'picocolors'
import type * as postcss from 'postcss'
import type { Plugin } from '../plugin'
@ -82,6 +81,7 @@ import {
import { FS_PREFIX } from '../constants'
import type { ResolvedConfig } from '../config'
import { createPluginHookUtils } from '../plugins'
import type { Watcher } from '../watch'
import { buildErrorMessage } from './middlewares/error'
import type { ModuleGraph } from './moduleGraph'
@ -155,7 +155,7 @@ export let parser = acorn.Parser
export async function createPluginContainer(
config: ResolvedConfig,
moduleGraph?: ModuleGraph,
watcher?: FSWatcher,
watcher?: Watcher,
): Promise<PluginContainer> {
const {
plugins,

View File

@ -8,7 +8,6 @@ import { builtinModules, createRequire } from 'node:module'
import { promises as dns } from 'node:dns'
import { performance } from 'node:perf_hooks'
import type { AddressInfo, Server } from 'node:net'
import type { FSWatcher } from 'chokidar'
import remapping from '@ampproject/remapping'
import type { DecodedSourceMap, RawSourceMap } from '@ampproject/remapping'
import colors from 'picocolors'
@ -33,6 +32,7 @@ import type { DepOptimizationConfig } from './optimizer'
import type { ResolvedConfig } from './config'
import type { ResolvedServerUrls, ViteDevServer } from './server'
import { resolvePackageData } from './packages'
import type { Watcher } from './watch'
import type { CommonServerOptions } from '.'
/**
@ -627,7 +627,7 @@ function optimizeSafeRealPathSync() {
}
export function ensureWatchedFile(
watcher: FSWatcher,
watcher: Watcher,
file: string | null,
root: string,
): void {
@ -640,7 +640,7 @@ export function ensureWatchedFile(
fs.existsSync(file)
) {
// resolve file to normalized system path
watcher.add(path.resolve(file))
watcher.add([path.resolve(file)])
}
}

View File

@ -1,8 +1,73 @@
import fs from 'node:fs'
import path from 'node:path'
import type { FSWatcher, WatchEventType } from 'node:fs'
import glob from 'fast-glob'
import type { WatchOptions } from 'dep-types/chokidar'
import picomatch from 'picomatch'
import type { ResolvedConfig } from '.'
export function resolveChokidarOptions(
export type WatchEventHandler = (event: WatchEventType, file: string) => void
export interface WatchOptions {
ignored?: string[]
}
export class Watcher {
private watchers: FSWatcher[] = []
private eventHandlers = new Set<WatchEventHandler>()
private matcher: ReturnType<typeof picomatch> | undefined
constructor(opts: WatchOptions) {
if (opts.ignored) {
this.matcher = picomatch(opts.ignored, {})
}
}
on(eventHandler: WatchEventHandler): void {
this.eventHandlers.add(eventHandler)
}
off(eventHandler: WatchEventHandler): void {
this.eventHandlers.delete(eventHandler)
}
close(): void {
this.watchers.forEach((w) => w.close())
}
/**
* Watch additional paths
*/
add(paths: string[]): void {
for (const p of paths) {
fs.watch(p, (event, file) => {
if (!file) return
if (file !== p) file = path.join(p, file)
if (this.isPathIgnored(file)) return
this.throttleEvent(event, file)
})
}
}
private isPathIgnored(file: string): boolean {
return !this.matcher || this.matcher(file)
}
// Throttle events as Node.js sometimes over-triggers events
private throttledKeys = new Set<string>()
private throttleEvent(event: WatchEventType, file: string) {
const key = `${event}:${file}`
if (this.throttledKeys.has(key)) return
this.throttledKeys.add(key)
setTimeout(() => {
for (const eventHandler of this.eventHandlers) {
eventHandler(event, file)
}
this.throttledKeys.delete(key)
}, 10)
}
}
export function resolveWatchOptions(
config: ResolvedConfig,
options: WatchOptions | undefined,
): WatchOptions {
@ -16,8 +81,6 @@ export function resolveChokidarOptions(
glob.escapePath(config.cacheDir) + '/**',
...(Array.isArray(ignored) ? ignored : [ignored]),
],
ignoreInitial: true,
ignorePermissionErrors: true,
...otherOptions,
}

View File

@ -1,14 +0,0 @@
diff --git a/lib/fsevents-handler.js b/lib/fsevents-handler.js
index 0f7f2cba857e0dbe001a5597061b11a9268d1e0e..5e99d97b917f8e2616cd3deb48b7a19d8b038928 100644
--- a/lib/fsevents-handler.js
+++ b/lib/fsevents-handler.js
@@ -303,7 +303,8 @@ _watchWithFsEvents(watchPath, realPath, transform, globFilter) {
if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
const opts = this.fsw.options;
const watchCallback = async (fullPath, flags, info) => {
- if (this.fsw.closed) return;
+ // PATCH: bypass the callback for better perf when fullPath hit the ignored file list
+ if (this.fsw.closed || this.fsw._isIgnored(fullPath)) return;
if (
opts.depth !== undefined &&
calcDepth(fullPath, realPath) > opts.depth

View File

@ -10,9 +10,6 @@ overrides:
packageExtensionsChecksum: 2a87e01b470616d3b7def19cc0830231
patchedDependencies:
chokidar@3.5.3:
hash: dzxbf3kgof5pdmbsyih2x43sq4
path: patches/chokidar@3.5.3.patch
dotenv-expand@9.0.0:
hash: dccccn23nvejzy75sgiosdt2au
path: patches/dotenv-expand@9.0.0.patch
@ -294,9 +291,6 @@ importers:
cac:
specifier: ^6.7.14
version: 6.7.14
chokidar:
specifier: ^3.5.3
version: 3.5.3(patch_hash=dzxbf3kgof5pdmbsyih2x43sq4)
connect:
specifier: ^3.7.0
version: 3.7.0
@ -4764,7 +4758,7 @@ packages:
resolution: {integrity: sha512-BrgHpW9NURQgzoNyjfq0Wu6VFO6D7IZEmJNdtgNqpzGG8RuNFHt2jQxWlAs4HMe119chBnv+34syEZtc6IhLtA==}
dev: true
/chokidar@3.5.3(patch_hash=dzxbf3kgof5pdmbsyih2x43sq4):
/chokidar@3.5.3:
resolution: {integrity: sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==}
engines: {node: '>= 8.10.0'}
dependencies:
@ -4777,7 +4771,6 @@ packages:
readdirp: 3.6.0
optionalDependencies:
fsevents: 2.3.2
patched: true
/chownr@2.0.0:
resolution: {integrity: sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==}
@ -7760,7 +7753,7 @@ packages:
'@iarna/toml': 2.2.5
'@mrbbot/node-fetch': 4.6.0
'@peculiar/webcrypto': 1.3.3
chokidar: 3.5.3(patch_hash=dzxbf3kgof5pdmbsyih2x43sq4)
chokidar: 3.5.3
cjstoesm: 1.1.4(typescript@4.6.4)
dotenv: 8.6.0
env-paths: 2.2.1
@ -9157,7 +9150,7 @@ packages:
engines: {node: '>=14.0.0'}
hasBin: true
dependencies:
chokidar: 3.5.3(patch_hash=dzxbf3kgof5pdmbsyih2x43sq4)
chokidar: 3.5.3
immutable: 4.0.0
source-map-js: 1.0.2
dev: true
@ -9668,7 +9661,7 @@ packages:
dependencies:
'@alloc/quick-lru': 5.2.0
arg: 5.0.2
chokidar: 3.5.3(patch_hash=dzxbf3kgof5pdmbsyih2x43sq4)
chokidar: 3.5.3
didyoumean: 1.2.2
dlv: 1.1.3
fast-glob: 3.2.12