Skip to content

Commit e17d2d5

Browse files
jamesopstadbluwy
andauthored
feat: add closeServer and closePreviewServer hooks (#23110)
Co-authored-by: Bjorn Lu <[email protected]>
1 parent 924997a commit e17d2d5

5 files changed

Lines changed: 293 additions & 8 deletions

File tree

‎docs/guide/api-plugin.md‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,58 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo
337337
})
338338
```
339339

340+
### `closeServer`
341+
342+
- **Type:** `(context: { reason: 'restart' | 'close' }) => void | Promise<void>`
343+
- **Kind:** `async`, `parallel`
344+
- **Scope:** [Global](/guide/api-environment-plugins#per-environment-hooks-and-global-hooks)
345+
346+
Called when the dev server is restarted or closed, after the server has been torn down. Typically used to dispose resources created in [`configureServer`](/guide/api-plugin.html#configureserver).
347+
348+
The `context.reason` distinguishes the two cases:
349+
- `'restart'`: the server is restarting (e.g. a config file change or a call to `server.restart()`).
350+
- `'close'`: the server is shutting down (e.g. the `q` shortcut, or a call to `server.close()`).
351+
352+
```js
353+
const myPlugin = () => {
354+
let resource
355+
return {
356+
name: 'close-server',
357+
configureServer(server) {
358+
resource = createResource()
359+
},
360+
async closeServer({ reason }) {
361+
if (reason === 'close') {
362+
await resource.dispose()
363+
}
364+
},
365+
}
366+
}
367+
```
368+
369+
### `closePreviewServer`
370+
371+
- **Type:** `() => void | Promise<void>`
372+
- **Kind:** `async`, `parallel`
373+
- **Scope:** [Global](/guide/api-environment-plugins#per-environment-hooks-and-global-hooks)
374+
375+
Same as [`closeServer`](/guide/api-plugin.html#closeserver) but for the preview server. The preview server never restarts, so there is no `reason`.
376+
377+
```js
378+
const myPlugin = () => {
379+
let resource
380+
return {
381+
name: 'close-preview-server',
382+
configurePreviewServer(server) {
383+
resource = createResource()
384+
},
385+
async closePreviewServer() {
386+
await resource.dispose()
387+
},
388+
}
389+
}
390+
```
391+
340392
### `transformIndexHtml`
341393

342394
- **Type:** `IndexHtmlTransformHook | { order?: 'pre' | 'post', handler: IndexHtmlTransformHook }`

‎packages/vite/src/node/__tests__/plugins/hooks.spec.ts‎

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,3 +446,169 @@ describe('watcher add/unlink error handling', () => {
446446
expect(logError).toHaveBeenCalledWith(error)
447447
})
448448
})
449+
450+
describe('closeServer hook', () => {
451+
test('is called with reason "close" on server.close()', async () => {
452+
const closeServer = vi.fn()
453+
const server = await createServerWithPlugin({
454+
name: 'test',
455+
closeServer,
456+
})
457+
458+
await server.close()
459+
460+
expect(closeServer).toHaveBeenCalledTimes(1)
461+
expect(closeServer).toHaveBeenCalledWith({ reason: 'close' })
462+
})
463+
464+
test('receives a minimal plugin context as `this`', async () => {
465+
expect.assertions(2)
466+
467+
const server = await createServerWithPlugin({
468+
name: 'test',
469+
closeServer() {
470+
expect(this).toMatchObject({
471+
debug: expect.any(Function),
472+
info: expect.any(Function),
473+
warn: expect.any(Function),
474+
error: expect.any(Function),
475+
meta: expect.any(Object),
476+
})
477+
// Global hooks don't have an environment.
478+
expect(this).not.toHaveProperty('environment')
479+
},
480+
})
481+
482+
await server.close()
483+
})
484+
485+
test('is awaited before server.close() resolves', async () => {
486+
let hookDone = false
487+
const server = await createServerWithPlugin({
488+
name: 'test',
489+
async closeServer() {
490+
await new Promise((r) => setTimeout(r, 10))
491+
hookDone = true
492+
},
493+
})
494+
495+
await server.close()
496+
497+
// `server.close()` does not resolve until the async hook has completed.
498+
expect(hookDone).toBe(true)
499+
})
500+
501+
test('runs after the server is torn down (after closeBundle)', async () => {
502+
const order: string[] = []
503+
const server = await createServerWithPlugin({
504+
name: 'test',
505+
closeBundle() {
506+
order.push('closeBundle')
507+
},
508+
closeServer() {
509+
order.push('closeServer')
510+
},
511+
})
512+
513+
await server.close()
514+
515+
// `closeBundle` runs as part of teardown (once per environment); the
516+
// `closeServer` hook runs afterwards, so it is the last event.
517+
expect(order.at(-1)).toBe('closeServer')
518+
expect(order.indexOf('closeBundle')).toBeLessThan(
519+
order.indexOf('closeServer'),
520+
)
521+
})
522+
523+
test('runs hooks in parallel', async () => {
524+
const events: string[] = []
525+
const server = await createServer({
526+
configFile: false,
527+
root: import.meta.dirname,
528+
plugins: [
529+
{
530+
name: 'a',
531+
async closeServer() {
532+
events.push('a:start')
533+
await new Promise((r) => setTimeout(r, 20))
534+
events.push('a:end')
535+
},
536+
},
537+
{
538+
name: 'b',
539+
async closeServer() {
540+
events.push('b:start')
541+
await new Promise((r) => setTimeout(r, 20))
542+
events.push('b:end')
543+
},
544+
},
545+
resolveEntryPlugin,
546+
],
547+
logLevel: 'error',
548+
server: { middlewareMode: true, ws: false },
549+
})
550+
551+
await server.close()
552+
553+
// Both hooks start before either finishes.
554+
expect(events.slice(0, 2)).toStrictEqual(['a:start', 'b:start'])
555+
})
556+
557+
test('is called only once even if close() is called multiple times', async () => {
558+
const closeServer = vi.fn()
559+
const server = await createServerWithPlugin({
560+
name: 'test',
561+
closeServer,
562+
})
563+
564+
await Promise.all([server.close(), server.close()])
565+
await server.close()
566+
567+
expect(closeServer).toHaveBeenCalledTimes(1)
568+
})
569+
570+
test('is called with reason "restart" on server.restart()', async () => {
571+
const closeServer = vi.fn()
572+
const server = await createServerWithPlugin({
573+
name: 'test',
574+
closeServer,
575+
})
576+
577+
await server.restart()
578+
579+
expect(closeServer).toHaveBeenCalledTimes(1)
580+
expect(closeServer).toHaveBeenCalledWith({ reason: 'restart' })
581+
582+
await server.close()
583+
})
584+
})
585+
586+
describe('closePreviewServer hook', () => {
587+
test('is called on preview server.close()', async () => {
588+
const closePreviewServer = vi.fn()
589+
const server = await createPreviewServerWithPlugin({
590+
name: 'test',
591+
closePreviewServer,
592+
})
593+
594+
await server.close()
595+
596+
expect(closePreviewServer).toHaveBeenCalledTimes(1)
597+
})
598+
599+
test('is awaited before server.close() resolves', async () => {
600+
let hookDone = false
601+
const server = await createPreviewServerWithPlugin({
602+
name: 'test',
603+
async closePreviewServer() {
604+
await new Promise((r) => setTimeout(r, 10))
605+
hookDone = true
606+
},
607+
})
608+
609+
await server.close()
610+
611+
// `server.close()` does not resolve until the async hook has completed.
612+
expect(hookDone).toBe(true)
613+
})
614+
})

‎packages/vite/src/node/plugin.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import type {
1919
ResolvedConfig,
2020
UserConfig,
2121
} from './config'
22-
import type { ServerHook } from './server'
22+
import type { CloseServerHook, ServerHook } from './server'
2323
import type { BuildAppHook } from './build'
2424
import type { IndexHtmlTransform } from './plugins/html'
2525
import type { EnvironmentModuleNode } from './server/moduleGraph'
@@ -28,7 +28,7 @@ import type { HmrContext, HotUpdateOptions } from './server/hmr'
2828
import type { DevEnvironment } from './server/environment'
2929
import type { Environment } from './environment'
3030
import type { PartialEnvironment } from './baseEnvironment'
31-
import type { PreviewServerHook } from './preview'
31+
import type { ClosePreviewServerHook, PreviewServerHook } from './preview'
3232
import { arraify, asyncFlatten } from './utils'
3333
import type { StringFilter } from './plugins/pluginFilter'
3434

@@ -303,6 +303,20 @@ export interface Plugin<A = any> extends RolldownPlugin<A> {
303303
* applied. Hooks can be async functions and will be called in series.
304304
*/
305305
configurePreviewServer?: ObjectHook<PreviewServerHook>
306+
/**
307+
* Run logic when the server is restarted or closed. The hook receives a
308+
* `reason` that is `'restart'` when the server is restarting and `'close'`
309+
* when it is closing.
310+
*
311+
* The hooks are called after the server is torn down. Hooks can be async
312+
* functions and will be called in parallel.
313+
*/
314+
closeServer?: ObjectHook<CloseServerHook>
315+
/**
316+
* Same as `closeServer` but for the preview server. The preview server never
317+
* restarts, so no `reason` is provided.
318+
*/
319+
closePreviewServer?: ObjectHook<ClosePreviewServerHook>
306320
/**
307321
* Transform index.html.
308322
* The hook receives the following arguments:

‎packages/vite/src/node/preview.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,10 @@ export type PreviewServerHook = (
121121
server: PreviewServer,
122122
) => (() => void) | void | Promise<(() => void) | void>
123123

124+
export type ClosePreviewServerHook = (
125+
this: MinimalPluginContextWithoutEnvironment,
126+
) => void | Promise<void>
127+
124128
/**
125129
* Starts the Vite server in preview mode, to simulate a production deployment
126130
*/
@@ -169,8 +173,20 @@ export async function preview(
169173
let closeServerPromise: Promise<void> | undefined
170174
const closeServer = async () => {
171175
teardownSIGTERMListener(closeServerAndExit)
176+
172177
await closeHttpServer()
173178
server.resolvedUrls = null
179+
180+
// Run `closePreviewServer` plugin hooks after the server has been torn down.
181+
const closePreviewServerContext = new BasicMinimalPluginContext(
182+
{ ...basePluginContextMeta, watchMode: false },
183+
config.logger,
184+
)
185+
await Promise.all(
186+
config
187+
.getSortedPluginHooks('closePreviewServer')
188+
.map((hook) => hook.call(closePreviewServerContext)),
189+
)
174190
}
175191

176192
const server: PreviewServer = {

‎packages/vite/src/node/server/index.ts‎

Lines changed: 43 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,20 @@ export type ServerHook = (
266266
server: ViteDevServer,
267267
) => (() => void) | void | Promise<(() => void) | void>
268268

269+
export interface CloseServerHookContext {
270+
/**
271+
* Whether the server is being restarted (e.g. a config change or
272+
* `server.restart()`) or closed (e.g. the `q` shortcut, SIGTERM, stdin
273+
* ending, or `server.close()`).
274+
*/
275+
reason: 'restart' | 'close'
276+
}
277+
278+
export type CloseServerHook = (
279+
this: MinimalPluginContextWithoutEnvironment,
280+
context: CloseServerHookContext,
281+
) => void | Promise<void>
282+
269283
export type HttpServer = http.Server | Http2SecureServer
270284

271285
export async function resolveForwardConsoleOptions(
@@ -439,6 +453,13 @@ export interface ViteDevServer {
439453
* @internal
440454
*/
441455
_setInternalServer(server: ViteDevServer): void
456+
/**
457+
* Internal close implementation shared by `close()` and `restart()`. The
458+
* `reason` is forwarded to `closeServer` plugin hooks so they can distinguish
459+
* a restart from a real close.
460+
* @internal
461+
*/
462+
_closeServer(reason: 'restart' | 'close'): Promise<void>
442463
/**
443464
* @internal
444465
*/
@@ -606,7 +627,7 @@ export async function _createServer(
606627

607628
// Promise used by `server.close()` to ensure `closeServer()` is only called once
608629
let closeServerPromise: Promise<void> | undefined
609-
const closeServer = async () => {
630+
const closeServer = async (reason: 'restart' | 'close') => {
610631
if (!middlewareMode) {
611632
teardownSIGTERMListener(closeServerAndExit)
612633
}
@@ -624,6 +645,17 @@ export async function _createServer(
624645
])
625646
server.resolvedUrls = null
626647
server._ssrCompatModuleRunner = undefined
648+
649+
// Run `closeServer` plugin hooks after the server has been torn down.
650+
const closeServerContext = new BasicMinimalPluginContext(
651+
{ ...basePluginContextMeta, watchMode: true },
652+
config.logger,
653+
)
654+
await Promise.all(
655+
config
656+
.getSortedPluginHooks('closeServer')
657+
.map((hook) => hook.call(closeServerContext, { reason })),
658+
)
627659
}
628660

629661
let hot = ws
@@ -782,10 +814,7 @@ export async function _createServer(
782814
}
783815
},
784816
async close() {
785-
if (!closeServerPromise) {
786-
closeServerPromise = closeServer()
787-
}
788-
return closeServerPromise
817+
return server._closeServer('close')
789818
},
790819
printUrls() {
791820
if (server.resolvedUrls) {
@@ -825,6 +854,12 @@ export async function _createServer(
825854
// server instance after a restart
826855
server = _server
827856
},
857+
_closeServer(reason: 'restart' | 'close') {
858+
if (!closeServerPromise) {
859+
closeServerPromise = closeServer(reason)
860+
}
861+
return closeServerPromise
862+
},
828863
_restartPromise: options.previousRestartPromise ?? null,
829864
_forceOptimizeOnRestart: options.previousForceOptimizeOnRestart ?? false,
830865
_shortcutsState: options.previousShortcutsState,
@@ -1380,7 +1415,9 @@ async function restartServer(server: ViteDevServer) {
13801415
// Detach readline so close handler skips it. Reused to avoid stdin issues
13811416
server._shortcutsState = undefined
13821417

1383-
await server.close()
1418+
// Close with reason 'restart' so `closeServer` hooks can distinguish a
1419+
// restart from a real close.
1420+
await server._closeServer('restart')
13841421

13851422
// Assign new server props to existing server instance
13861423
const middlewares = server.middlewares

0 commit comments

Comments
 (0)