source: imaps-frontend/node_modules/vite/dist/node/index.d.ts@ d565449

main
Last change on this file since d565449 was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

  • Property mode set to 100644
File size: 121.0 KB
Line 
1/// <reference types="node" />
2import { PluginHooks, RollupError, SourceMap, ModuleInfo, PartialResolvedId, MinimalPluginContext, InputOptions, CustomPluginOptions, LoadResult, SourceDescription, RollupOptions, WatcherOptions, InputOption, ModuleFormat, RollupOutput, RollupWatcher, SourceMapInput, ExistingRawSourceMap, OutputBundle, OutputChunk, ObjectHook, PluginContext, ResolveIdResult, TransformPluginContext, GetManualChunk } from 'rollup';
3import * as rollup from 'rollup';
4export { rollup as Rollup };
5export { parseAst, parseAstAsync } from 'rollup/parseAst';
6import * as http from 'node:http';
7import { OutgoingHttpHeaders, ClientRequestArgs, IncomingMessage, ClientRequest, Agent, Server, ServerResponse } from 'node:http';
8import { Http2SecureServer } from 'node:http2';
9import * as fs from 'node:fs';
10import * as events from 'node:events';
11import { EventEmitter } from 'node:events';
12import { ServerOptions as HttpsServerOptions, Server as HttpsServer } from 'node:https';
13import * as net from 'node:net';
14import * as url from 'node:url';
15import { URL } from 'node:url';
16import * as stream from 'node:stream';
17import { Duplex, DuplexOptions } from 'node:stream';
18import { F as FetchResult, H as HMRLogger } from './types.d-aGj9QkWt.js';
19export { a as FetchFunction } from './types.d-aGj9QkWt.js';
20import { SecureContextOptions } from 'node:tls';
21import { ZlibOptions } from 'node:zlib';
22import { HMRPayload, CustomPayload } from '../../types/hmrPayload.js';
23export { ConnectedPayload, CustomPayload, ErrorPayload, FullReloadPayload, HMRPayload, PrunePayload, Update, UpdatePayload } from '../../types/hmrPayload.js';
24import { InferCustomEventPayload } from '../../types/customEvent.js';
25export { CustomEventMap, InferCustomEventPayload, InvalidatePayload } from '../../types/customEvent.js';
26import { TransformOptions as esbuild_TransformOptions, TransformResult as esbuild_TransformResult, BuildOptions as esbuild_BuildOptions } from 'esbuild';
27export { TransformOptions as EsbuildTransformOptions, version as esbuildVersion } from 'esbuild';
28import * as PostCSS from 'postcss';
29import { ViteRuntimeOptions, ViteModuleRunner, ViteRuntime, HMRRuntimeConnection } from 'vite/runtime';
30export { GeneralImportGlobOptions, ImportGlobFunction, ImportGlobOptions, KnownAsTypeMap } from '../../types/importGlob.js';
31export { ChunkMetadata } from '../../types/metadata.js';
32import '../../types/hot.js';
33
34interface Alias {
35 find: string | RegExp
36 replacement: string
37 /**
38 * Instructs the plugin to use an alternative resolving algorithm,
39 * rather than the Rollup's resolver.
40 * @default null
41 */
42 customResolver?: ResolverFunction | ResolverObject | null
43}
44
45type MapToFunction<T> = T extends Function ? T : never
46
47type ResolverFunction = MapToFunction<PluginHooks['resolveId']>
48
49interface ResolverObject {
50 buildStart?: PluginHooks['buildStart']
51 resolveId: ResolverFunction
52}
53
54/**
55 * Specifies an `Object`, or an `Array` of `Object`,
56 * which defines aliases used to replace values in `import` or `require` statements.
57 * With either format, the order of the entries is important,
58 * in that the first defined rules are applied first.
59 *
60 * This is passed to \@rollup/plugin-alias as the "entries" field
61 * https://github.com/rollup/plugins/tree/master/packages/alias#entries
62 */
63type AliasOptions = readonly Alias[] | { [find: string]: string }
64
65type AnymatchFn = (testString: string) => boolean
66type AnymatchPattern = string | RegExp | AnymatchFn
67type AnymatchMatcher = AnymatchPattern | AnymatchPattern[]
68
69// Inlined to avoid extra dependency (chokidar is bundled in the published build)
70
71declare class FSWatcher extends EventEmitter implements fs.FSWatcher {
72 options: WatchOptions
73
74 /**
75 * Constructs a new FSWatcher instance with optional WatchOptions parameter.
76 */
77 constructor(options?: WatchOptions)
78
79 /**
80 * When called, requests that the Node.js event loop not exit so long as the fs.FSWatcher is active.
81 * Calling watcher.ref() multiple times will have no effect.
82 */
83 ref(): this
84
85 /**
86 * When called, the active fs.FSWatcher object will not require the Node.js event loop to remain active.
87 * If there is no other activity keeping the event loop running, the process may exit before the fs.FSWatcher object's callback is invoked.
88 * Calling watcher.unref() multiple times will have no effect.
89 */
90 unref(): this
91
92 /**
93 * Add files, directories, or glob patterns for tracking. Takes an array of strings or just one
94 * string.
95 */
96 add(paths: string | ReadonlyArray<string>): this
97
98 /**
99 * Stop watching files, directories, or glob patterns. Takes an array of strings or just one
100 * string.
101 */
102 unwatch(paths: string | ReadonlyArray<string>): this
103
104 /**
105 * Returns an object representing all the paths on the file system being watched by this
106 * `FSWatcher` instance. The object's keys are all the directories (using absolute paths unless
107 * the `cwd` option was used), and the values are arrays of the names of the items contained in
108 * each directory.
109 */
110 getWatched(): {
111 [directory: string]: string[]
112 }
113
114 /**
115 * Removes all listeners from watched files.
116 */
117 close(): Promise<void>
118
119 on(
120 event: 'add' | 'addDir' | 'change',
121 listener: (path: string, stats?: fs.Stats) => void,
122 ): this
123
124 on(
125 event: 'all',
126 listener: (
127 eventName: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir',
128 path: string,
129 stats?: fs.Stats,
130 ) => void,
131 ): this
132
133 /**
134 * Error occurred
135 */
136 on(event: 'error', listener: (error: Error) => void): this
137
138 /**
139 * Exposes the native Node `fs.FSWatcher events`
140 */
141 on(
142 event: 'raw',
143 listener: (eventName: string, path: string, details: any) => void,
144 ): this
145
146 /**
147 * Fires when the initial scan is complete
148 */
149 on(event: 'ready', listener: () => void): this
150
151 on(event: 'unlink' | 'unlinkDir', listener: (path: string) => void): this
152
153 on(event: string, listener: (...args: any[]) => void): this
154}
155
156interface WatchOptions {
157 /**
158 * Indicates whether the process should continue to run as long as files are being watched. If
159 * set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`,
160 * even if the process continues to run.
161 */
162 persistent?: boolean
163
164 /**
165 * ([anymatch](https://github.com/micromatch/anymatch)-compatible definition) Defines files/paths to
166 * be ignored. The whole relative or absolute path is tested, not just filename. If a function
167 * with two arguments is provided, it gets called twice per path - once with a single argument
168 * (the path), second time with two arguments (the path and the
169 * [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path).
170 */
171 ignored?: AnymatchMatcher
172
173 /**
174 * If set to `false` then `add`/`addDir` events are also emitted for matching paths while
175 * instantiating the watching as chokidar discovers these file paths (before the `ready` event).
176 */
177 ignoreInitial?: boolean
178
179 /**
180 * When `false`, only the symlinks themselves will be watched for changes instead of following
181 * the link references and bubbling events through the link's path.
182 */
183 followSymlinks?: boolean
184
185 /**
186 * The base directory from which watch `paths` are to be derived. Paths emitted with events will
187 * be relative to this.
188 */
189 cwd?: string
190
191 /**
192 * If set to true then the strings passed to .watch() and .add() are treated as literal path
193 * names, even if they look like globs.
194 *
195 * @default false
196 */
197 disableGlobbing?: boolean
198
199 /**
200 * Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU
201 * utilization, consider setting this to `false`. It is typically necessary to **set this to
202 * `true` to successfully watch files over a network**, and it may be necessary to successfully
203 * watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides
204 * the `useFsEvents` default.
205 */
206 usePolling?: boolean
207
208 /**
209 * Whether to use the `fsevents` watching interface if available. When set to `true` explicitly
210 * and `fsevents` is available this supersedes the `usePolling` setting. When set to `false` on
211 * OS X, `usePolling: true` becomes the default.
212 */
213 useFsEvents?: boolean
214
215 /**
216 * If relying upon the [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object that
217 * may get passed with `add`, `addDir`, and `change` events, set this to `true` to ensure it is
218 * provided even in cases where it wasn't already available from the underlying watch events.
219 */
220 alwaysStat?: boolean
221
222 /**
223 * If set, limits how many levels of subdirectories will be traversed.
224 */
225 depth?: number
226
227 /**
228 * Interval of file system polling.
229 */
230 interval?: number
231
232 /**
233 * Interval of file system polling for binary files. ([see list of binary extensions](https://gi
234 * thub.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))
235 */
236 binaryInterval?: number
237
238 /**
239 * Indicates whether to watch files that don't have read permissions if possible. If watching
240 * fails due to `EPERM` or `EACCES` with this set to `true`, the errors will be suppressed
241 * silently.
242 */
243 ignorePermissionErrors?: boolean
244
245 /**
246 * `true` if `useFsEvents` and `usePolling` are `false`. Automatically filters out artifacts
247 * that occur when using editors that use "atomic writes" instead of writing directly to the
248 * source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a `change`
249 * event rather than `unlink` then `add`. If the default of 100 ms does not work well for you,
250 * you can override it by setting `atomic` to a custom value, in milliseconds.
251 */
252 atomic?: boolean | number
253
254 /**
255 * can be set to an object in order to adjust timing params:
256 */
257 awaitWriteFinish?: AwaitWriteFinishOptions | boolean
258}
259
260interface AwaitWriteFinishOptions {
261 /**
262 * Amount of time in milliseconds for a file size to remain constant before emitting its event.
263 */
264 stabilityThreshold?: number
265
266 /**
267 * File size polling interval.
268 */
269 pollInterval?: number
270}
271
272// Inlined to avoid extra dependency
273// MIT Licensed https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/LICENSE
274
275declare namespace Connect {
276 export type ServerHandle = HandleFunction | http.Server
277
278 export class IncomingMessage extends http.IncomingMessage {
279 originalUrl?: http.IncomingMessage['url'] | undefined
280 }
281
282 export type NextFunction = (err?: any) => void
283
284 export type SimpleHandleFunction = (
285 req: IncomingMessage,
286 res: http.ServerResponse,
287 ) => void
288 export type NextHandleFunction = (
289 req: IncomingMessage,
290 res: http.ServerResponse,
291 next: NextFunction,
292 ) => void
293 export type ErrorHandleFunction = (
294 err: any,
295 req: IncomingMessage,
296 res: http.ServerResponse,
297 next: NextFunction,
298 ) => void
299 export type HandleFunction =
300 | SimpleHandleFunction
301 | NextHandleFunction
302 | ErrorHandleFunction
303
304 export interface ServerStackItem {
305 route: string
306 handle: ServerHandle
307 }
308
309 export interface Server extends NodeJS.EventEmitter {
310 (req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void
311
312 route: string
313 stack: ServerStackItem[]
314
315 /**
316 * Utilize the given middleware `handle` to the given `route`,
317 * defaulting to _/_. This "route" is the mount-point for the
318 * middleware, when given a value other than _/_ the middleware
319 * is only effective when that segment is present in the request's
320 * pathname.
321 *
322 * For example if we were to mount a function at _/admin_, it would
323 * be invoked on _/admin_, and _/admin/settings_, however it would
324 * not be invoked for _/_, or _/posts_.
325 */
326 use(fn: NextHandleFunction): Server
327 use(fn: HandleFunction): Server
328 use(route: string, fn: NextHandleFunction): Server
329 use(route: string, fn: HandleFunction): Server
330
331 /**
332 * Handle server requests, punting them down
333 * the middleware stack.
334 */
335 handle(
336 req: http.IncomingMessage,
337 res: http.ServerResponse,
338 next: Function,
339 ): void
340
341 /**
342 * Listen for connections.
343 *
344 * This method takes the same arguments
345 * as node's `http.Server#listen()`.
346 *
347 * HTTP and HTTPS:
348 *
349 * If you run your application both as HTTP
350 * and HTTPS you may wrap them individually,
351 * since your Connect "server" is really just
352 * a JavaScript `Function`.
353 *
354 * var connect = require('connect')
355 * , http = require('http')
356 * , https = require('https');
357 *
358 * var app = connect();
359 *
360 * http.createServer(app).listen(80);
361 * https.createServer(options, app).listen(443);
362 */
363 listen(
364 port: number,
365 hostname?: string,
366 backlog?: number,
367 callback?: Function,
368 ): http.Server
369 listen(port: number, hostname?: string, callback?: Function): http.Server
370 listen(path: string, callback?: Function): http.Server
371 listen(handle: any, listeningListener?: Function): http.Server
372 }
373}
374
375// Inlined to avoid extra dependency
376// MIT Licensed https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/LICENSE
377
378declare namespace HttpProxy {
379 export type ProxyTarget = ProxyTargetUrl | ProxyTargetDetailed
380
381 export type ProxyTargetUrl = string | Partial<url.Url>
382
383 export interface ProxyTargetDetailed {
384 host: string
385 port: number
386 protocol?: string | undefined
387 hostname?: string | undefined
388 socketPath?: string | undefined
389 key?: string | undefined
390 passphrase?: string | undefined
391 pfx?: Buffer | string | undefined
392 cert?: string | undefined
393 ca?: string | undefined
394 ciphers?: string | undefined
395 secureProtocol?: string | undefined
396 }
397
398 export type ErrorCallback = (
399 err: Error,
400 req: http.IncomingMessage,
401 res: http.ServerResponse,
402 target?: ProxyTargetUrl,
403 ) => void
404
405 export class Server extends events.EventEmitter {
406 /**
407 * Creates the proxy server with specified options.
408 * @param options - Config object passed to the proxy
409 */
410 constructor(options?: ServerOptions)
411
412 /**
413 * Used for proxying regular HTTP(S) requests
414 * @param req - Client request.
415 * @param res - Client response.
416 * @param options - Additional options.
417 * @param callback - Error callback.
418 */
419 web(
420 req: http.IncomingMessage,
421 res: http.ServerResponse,
422 options?: ServerOptions,
423 callback?: ErrorCallback,
424 ): void
425
426 /**
427 * Used for proxying regular HTTP(S) requests
428 * @param req - Client request.
429 * @param socket - Client socket.
430 * @param head - Client head.
431 * @param options - Additional options.
432 * @param callback - Error callback.
433 */
434 ws(
435 req: http.IncomingMessage,
436 socket: unknown,
437 head: unknown,
438 options?: ServerOptions,
439 callback?: ErrorCallback,
440 ): void
441
442 /**
443 * A function that wraps the object in a webserver, for your convenience
444 * @param port - Port to listen on
445 */
446 listen(port: number): Server
447
448 /**
449 * A function that closes the inner webserver and stops listening on given port
450 */
451 close(callback?: () => void): void
452
453 /**
454 * Creates the proxy server with specified options.
455 * @param options - Config object passed to the proxy
456 * @returns Proxy object with handlers for `ws` and `web` requests
457 */
458 static createProxyServer(options?: ServerOptions): Server
459
460 /**
461 * Creates the proxy server with specified options.
462 * @param options - Config object passed to the proxy
463 * @returns Proxy object with handlers for `ws` and `web` requests
464 */
465 static createServer(options?: ServerOptions): Server
466
467 /**
468 * Creates the proxy server with specified options.
469 * @param options - Config object passed to the proxy
470 * @returns Proxy object with handlers for `ws` and `web` requests
471 */
472 static createProxy(options?: ServerOptions): Server
473
474 addListener(event: string, listener: () => void): this
475 on(event: string, listener: () => void): this
476 on(event: 'error', listener: ErrorCallback): this
477 on(
478 event: 'start',
479 listener: (
480 req: http.IncomingMessage,
481 res: http.ServerResponse,
482 target: ProxyTargetUrl,
483 ) => void,
484 ): this
485 on(
486 event: 'proxyReq',
487 listener: (
488 proxyReq: http.ClientRequest,
489 req: http.IncomingMessage,
490 res: http.ServerResponse,
491 options: ServerOptions,
492 ) => void,
493 ): this
494 on(
495 event: 'proxyRes',
496 listener: (
497 proxyRes: http.IncomingMessage,
498 req: http.IncomingMessage,
499 res: http.ServerResponse,
500 ) => void,
501 ): this
502 on(
503 event: 'proxyReqWs',
504 listener: (
505 proxyReq: http.ClientRequest,
506 req: http.IncomingMessage,
507 socket: net.Socket,
508 options: ServerOptions,
509 head: any,
510 ) => void,
511 ): this
512 on(
513 event: 'econnreset',
514 listener: (
515 err: Error,
516 req: http.IncomingMessage,
517 res: http.ServerResponse,
518 target: ProxyTargetUrl,
519 ) => void,
520 ): this
521 on(
522 event: 'end',
523 listener: (
524 req: http.IncomingMessage,
525 res: http.ServerResponse,
526 proxyRes: http.IncomingMessage,
527 ) => void,
528 ): this
529 on(
530 event: 'close',
531 listener: (
532 proxyRes: http.IncomingMessage,
533 proxySocket: net.Socket,
534 proxyHead: any,
535 ) => void,
536 ): this
537
538 once(event: string, listener: () => void): this
539 removeListener(event: string, listener: () => void): this
540 removeAllListeners(event?: string): this
541 getMaxListeners(): number
542 setMaxListeners(n: number): this
543 listeners(event: string): Array<() => void>
544 emit(event: string, ...args: any[]): boolean
545 listenerCount(type: string): number
546 }
547
548 export interface ServerOptions {
549 /** URL string to be parsed with the url module. */
550 target?: ProxyTarget | undefined
551 /** URL string to be parsed with the url module. */
552 forward?: ProxyTargetUrl | undefined
553 /** Object to be passed to http(s).request. */
554 agent?: any
555 /** Object to be passed to https.createServer(). */
556 ssl?: any
557 /** If you want to proxy websockets. */
558 ws?: boolean | undefined
559 /** Adds x- forward headers. */
560 xfwd?: boolean | undefined
561 /** Verify SSL certificate. */
562 secure?: boolean | undefined
563 /** Explicitly specify if we are proxying to another proxy. */
564 toProxy?: boolean | undefined
565 /** Specify whether you want to prepend the target's path to the proxy path. */
566 prependPath?: boolean | undefined
567 /** Specify whether you want to ignore the proxy path of the incoming request. */
568 ignorePath?: boolean | undefined
569 /** Local interface string to bind for outgoing connections. */
570 localAddress?: string | undefined
571 /** Changes the origin of the host header to the target URL. */
572 changeOrigin?: boolean | undefined
573 /** specify whether you want to keep letter case of response header key */
574 preserveHeaderKeyCase?: boolean | undefined
575 /** Basic authentication i.e. 'user:password' to compute an Authorization header. */
576 auth?: string | undefined
577 /** Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null. */
578 hostRewrite?: string | undefined
579 /** Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false. */
580 autoRewrite?: boolean | undefined
581 /** Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null. */
582 protocolRewrite?: string | undefined
583 /** rewrites domain of set-cookie headers. */
584 cookieDomainRewrite?:
585 | false
586 | string
587 | { [oldDomain: string]: string }
588 | undefined
589 /** rewrites path of set-cookie headers. Default: false */
590 cookiePathRewrite?:
591 | false
592 | string
593 | { [oldPath: string]: string }
594 | undefined
595 /** object with extra headers to be added to target requests. */
596 headers?: { [header: string]: string } | undefined
597 /** Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes) */
598 proxyTimeout?: number | undefined
599 /** Timeout (in milliseconds) for incoming requests */
600 timeout?: number | undefined
601 /** Specify whether you want to follow redirects. Default: false */
602 followRedirects?: boolean | undefined
603 /** If set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the proxyRes event */
604 selfHandleResponse?: boolean | undefined
605 /** Buffer */
606 buffer?: stream.Stream | undefined
607 }
608}
609
610interface ProxyOptions extends HttpProxy.ServerOptions {
611 /**
612 * rewrite path
613 */
614 rewrite?: (path: string) => string;
615 /**
616 * configure the proxy server (e.g. listen to events)
617 */
618 configure?: (proxy: HttpProxy.Server, options: ProxyOptions) => void;
619 /**
620 * webpack-dev-server style bypass function
621 */
622 bypass?: (req: http.IncomingMessage, res: http.ServerResponse, options: ProxyOptions) => void | null | undefined | false | string;
623 /**
624 * rewrite the Origin header of a WebSocket request to match the the target
625 *
626 * **Exercise caution as rewriting the Origin can leave the proxying open to [CSRF attacks](https://owasp.org/www-community/attacks/csrf).**
627 */
628 rewriteWsOrigin?: boolean | undefined;
629}
630
631type LogType = 'error' | 'warn' | 'info';
632type LogLevel = LogType | 'silent';
633interface Logger {
634 info(msg: string, options?: LogOptions): void;
635 warn(msg: string, options?: LogOptions): void;
636 warnOnce(msg: string, options?: LogOptions): void;
637 error(msg: string, options?: LogErrorOptions): void;
638 clearScreen(type: LogType): void;
639 hasErrorLogged(error: Error | RollupError): boolean;
640 hasWarned: boolean;
641}
642interface LogOptions {
643 clear?: boolean;
644 timestamp?: boolean;
645}
646interface LogErrorOptions extends LogOptions {
647 error?: Error | RollupError | null;
648}
649interface LoggerOptions {
650 prefix?: string;
651 allowClearScreen?: boolean;
652 customLogger?: Logger;
653}
654declare function createLogger(level?: LogLevel, options?: LoggerOptions): Logger;
655
656interface CommonServerOptions {
657 /**
658 * Specify server port. Note if the port is already being used, Vite will
659 * automatically try the next available port so this may not be the actual
660 * port the server ends up listening on.
661 */
662 port?: number;
663 /**
664 * If enabled, vite will exit if specified port is already in use
665 */
666 strictPort?: boolean;
667 /**
668 * Specify which IP addresses the server should listen on.
669 * Set to 0.0.0.0 to listen on all addresses, including LAN and public addresses.
670 */
671 host?: string | boolean;
672 /**
673 * Enable TLS + HTTP/2.
674 * Note: this downgrades to TLS only when the proxy option is also used.
675 */
676 https?: HttpsServerOptions;
677 /**
678 * Open browser window on startup
679 */
680 open?: boolean | string;
681 /**
682 * Configure custom proxy rules for the dev server. Expects an object
683 * of `{ key: options }` pairs.
684 * Uses [`http-proxy`](https://github.com/http-party/node-http-proxy).
685 * Full options [here](https://github.com/http-party/node-http-proxy#options).
686 *
687 * Example `vite.config.js`:
688 * ``` js
689 * module.exports = {
690 * proxy: {
691 * // string shorthand: /foo -> http://localhost:4567/foo
692 * '/foo': 'http://localhost:4567',
693 * // with options
694 * '/api': {
695 * target: 'http://jsonplaceholder.typicode.com',
696 * changeOrigin: true,
697 * rewrite: path => path.replace(/^\/api/, '')
698 * }
699 * }
700 * }
701 * ```
702 */
703 proxy?: Record<string, string | ProxyOptions>;
704 /**
705 * Configure CORS for the dev server.
706 * Uses https://github.com/expressjs/cors.
707 * Set to `true` to allow all methods from any origin, or configure separately
708 * using an object.
709 */
710 cors?: CorsOptions | boolean;
711 /**
712 * Specify server response headers.
713 */
714 headers?: OutgoingHttpHeaders;
715}
716/**
717 * https://github.com/expressjs/cors#configuration-options
718 */
719interface CorsOptions {
720 origin?: CorsOrigin | ((origin: string, cb: (err: Error, origins: CorsOrigin) => void) => void);
721 methods?: string | string[];
722 allowedHeaders?: string | string[];
723 exposedHeaders?: string | string[];
724 credentials?: boolean;
725 maxAge?: number;
726 preflightContinue?: boolean;
727 optionsSuccessStatus?: number;
728}
729type CorsOrigin = boolean | string | RegExp | (string | RegExp)[];
730
731interface PreviewOptions extends CommonServerOptions {
732}
733interface ResolvedPreviewOptions extends PreviewOptions {
734}
735interface PreviewServer {
736 /**
737 * The resolved vite config object
738 */
739 config: ResolvedConfig;
740 /**
741 * Stop the server.
742 */
743 close(): Promise<void>;
744 /**
745 * A connect app instance.
746 * - Can be used to attach custom middlewares to the preview server.
747 * - Can also be used as the handler function of a custom http server
748 * or as a middleware in any connect-style Node.js frameworks
749 *
750 * https://github.com/senchalabs/connect#use-middleware
751 */
752 middlewares: Connect.Server;
753 /**
754 * native Node http server instance
755 */
756 httpServer: HttpServer;
757 /**
758 * The resolved urls Vite prints on the CLI.
759 * null before server is listening.
760 */
761 resolvedUrls: ResolvedServerUrls | null;
762 /**
763 * Print server urls
764 */
765 printUrls(): void;
766 /**
767 * Bind CLI shortcuts
768 */
769 bindCLIShortcuts(options?: BindCLIShortcutsOptions<PreviewServer>): void;
770}
771type PreviewServerHook = (this: void, server: PreviewServer) => (() => void) | void | Promise<(() => void) | void>;
772/**
773 * Starts the Vite server in preview mode, to simulate a production deployment
774 */
775declare function preview(inlineConfig?: InlineConfig): Promise<PreviewServer>;
776
777type BindCLIShortcutsOptions<Server = ViteDevServer | PreviewServer> = {
778 /**
779 * Print a one-line shortcuts "help" hint to the terminal
780 */
781 print?: boolean;
782 /**
783 * Custom shortcuts to run when a key is pressed. These shortcuts take priority
784 * over the default shortcuts if they have the same keys (except the `h` key).
785 * To disable a default shortcut, define the same key but with `action: undefined`.
786 */
787 customShortcuts?: CLIShortcut<Server>[];
788};
789type CLIShortcut<Server = ViteDevServer | PreviewServer> = {
790 key: string;
791 description: string;
792 action?(server: Server): void | Promise<void>;
793};
794
795interface TransformResult {
796 code: string;
797 map: SourceMap | {
798 mappings: '';
799 } | null;
800 etag?: string;
801 deps?: string[];
802 dynamicDeps?: string[];
803}
804interface TransformOptions {
805 ssr?: boolean;
806 html?: boolean;
807}
808
809declare class ModuleNode {
810 /**
811 * Public served url path, starts with /
812 */
813 url: string;
814 /**
815 * Resolved file system path + query
816 */
817 id: string | null;
818 file: string | null;
819 type: 'js' | 'css';
820 info?: ModuleInfo;
821 meta?: Record<string, any>;
822 importers: Set<ModuleNode>;
823 clientImportedModules: Set<ModuleNode>;
824 ssrImportedModules: Set<ModuleNode>;
825 acceptedHmrDeps: Set<ModuleNode>;
826 acceptedHmrExports: Set<string> | null;
827 importedBindings: Map<string, Set<string>> | null;
828 isSelfAccepting?: boolean;
829 transformResult: TransformResult | null;
830 ssrTransformResult: TransformResult | null;
831 ssrModule: Record<string, any> | null;
832 ssrError: Error | null;
833 lastHMRTimestamp: number;
834 lastInvalidationTimestamp: number;
835 /**
836 * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870
837 */
838 constructor(url: string, setIsSelfAccepting?: boolean);
839 get importedModules(): Set<ModuleNode>;
840}
841type ResolvedUrl = [
842 url: string,
843 resolvedId: string,
844 meta: object | null | undefined
845];
846declare class ModuleGraph {
847 private resolveId;
848 urlToModuleMap: Map<string, ModuleNode>;
849 idToModuleMap: Map<string, ModuleNode>;
850 etagToModuleMap: Map<string, ModuleNode>;
851 fileToModulesMap: Map<string, Set<ModuleNode>>;
852 safeModulesPath: Set<string>;
853 constructor(resolveId: (url: string, ssr: boolean) => Promise<PartialResolvedId | null>);
854 getModuleByUrl(rawUrl: string, ssr?: boolean): Promise<ModuleNode | undefined>;
855 getModuleById(id: string): ModuleNode | undefined;
856 getModulesByFile(file: string): Set<ModuleNode> | undefined;
857 onFileChange(file: string): void;
858 onFileDelete(file: string): void;
859 invalidateModule(mod: ModuleNode, seen?: Set<ModuleNode>, timestamp?: number, isHmr?: boolean,
860 ): void;
861 invalidateAll(): void;
862 /**
863 * Update the module graph based on a module's updated imports information
864 * If there are dependencies that no longer have any importers, they are
865 * returned as a Set.
866 *
867 * @param staticImportedUrls Subset of `importedModules` where they're statically imported in code.
868 * This is only used for soft invalidations so `undefined` is fine but may cause more runtime processing.
869 */
870 updateModuleInfo(mod: ModuleNode, importedModules: Set<string | ModuleNode>, importedBindings: Map<string, Set<string>> | null, acceptedModules: Set<string | ModuleNode>, acceptedExports: Set<string> | null, isSelfAccepting: boolean, ssr?: boolean,
871 ): Promise<Set<ModuleNode> | undefined>;
872 ensureEntryFromUrl(rawUrl: string, ssr?: boolean, setIsSelfAccepting?: boolean): Promise<ModuleNode>;
873 createFileOnlyEntry(file: string): ModuleNode;
874 resolveUrl(url: string, ssr?: boolean): Promise<ResolvedUrl>;
875 updateModuleTransformResult(mod: ModuleNode, result: TransformResult | null, ssr: boolean): void;
876 getModuleByEtag(etag: string): ModuleNode | undefined;
877}
878
879/**
880 * This file is refactored into TypeScript based on
881 * https://github.com/preactjs/wmr/blob/main/packages/wmr/src/lib/rollup-plugin-container.js
882 */
883
884declare class PluginContainer {
885 config: ResolvedConfig;
886 moduleGraph?: ModuleGraph | undefined;
887 watcher?: FSWatcher | undefined;
888 plugins: readonly Plugin<any>[];
889 private _pluginContextMap;
890 private _pluginContextMapSsr;
891 private _resolvedRollupOptions?;
892 private _processesing;
893 private _seenResolves;
894 private _closed;
895 private _moduleNodeToLoadAddedImports;
896 getSortedPluginHooks: PluginHookUtils['getSortedPluginHooks'];
897 getSortedPlugins: PluginHookUtils['getSortedPlugins'];
898 watchFiles: Set<string>;
899 minimalContext: MinimalPluginContext;
900 private _updateModuleLoadAddedImports;
901 private _getAddedImports;
902 getModuleInfo(id: string): ModuleInfo | null;
903 private handleHookPromise;
904 get options(): InputOptions;
905 resolveRollupOptions(): Promise<InputOptions>;
906 private _getPluginContext;
907 private hookParallel;
908 buildStart(_options?: InputOptions): Promise<void>;
909 resolveId(rawId: string, importer?: string | undefined, options?: {
910 attributes?: Record<string, string>;
911 custom?: CustomPluginOptions;
912 skip?: Set<Plugin>;
913 ssr?: boolean;
914 isEntry?: boolean;
915 }): Promise<PartialResolvedId | null>;
916 load(id: string, options?: {
917 ssr?: boolean;
918 }): Promise<LoadResult | null>;
919 transform(code: string, id: string, options?: {
920 ssr?: boolean;
921 inMap?: SourceDescription['map'];
922 }): Promise<{
923 code: string;
924 map: SourceMap | {
925 mappings: '';
926 } | null;
927 }>;
928 watchChange(id: string, change: {
929 event: 'create' | 'update' | 'delete';
930 }): Promise<void>;
931 close(): Promise<void>;
932}
933
934// Modified and inlined to avoid extra dependency
935// Source: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/ws/index.d.ts
936
937declare const WebSocketAlias: typeof WebSocket
938interface WebSocketAlias extends WebSocket {}
939// WebSocket socket.
940declare class WebSocket extends EventEmitter {
941 /** The connection is not yet open. */
942 static readonly CONNECTING: 0
943 /** The connection is open and ready to communicate. */
944 static readonly OPEN: 1
945 /** The connection is in the process of closing. */
946 static readonly CLOSING: 2
947 /** The connection is closed. */
948 static readonly CLOSED: 3
949
950 binaryType: 'nodebuffer' | 'arraybuffer' | 'fragments'
951 readonly bufferedAmount: number
952 readonly extensions: string
953 /** Indicates whether the websocket is paused */
954 readonly isPaused: boolean
955 readonly protocol: string
956 /** The current state of the connection */
957 readonly readyState:
958 | typeof WebSocket.CONNECTING
959 | typeof WebSocket.OPEN
960 | typeof WebSocket.CLOSING
961 | typeof WebSocket.CLOSED
962 readonly url: string
963
964 /** The connection is not yet open. */
965 readonly CONNECTING: 0
966 /** The connection is open and ready to communicate. */
967 readonly OPEN: 1
968 /** The connection is in the process of closing. */
969 readonly CLOSING: 2
970 /** The connection is closed. */
971 readonly CLOSED: 3
972
973 onopen: ((event: WebSocket.Event) => void) | null
974 onerror: ((event: WebSocket.ErrorEvent) => void) | null
975 onclose: ((event: WebSocket.CloseEvent) => void) | null
976 onmessage: ((event: WebSocket.MessageEvent) => void) | null
977
978 constructor(address: null)
979 constructor(
980 address: string | URL,
981 options?: WebSocket.ClientOptions | ClientRequestArgs,
982 )
983 constructor(
984 address: string | URL,
985 protocols?: string | string[],
986 options?: WebSocket.ClientOptions | ClientRequestArgs,
987 )
988
989 close(code?: number, data?: string | Buffer): void
990 ping(data?: any, mask?: boolean, cb?: (err: Error) => void): void
991 pong(data?: any, mask?: boolean, cb?: (err: Error) => void): void
992 send(data: any, cb?: (err?: Error) => void): void
993 send(
994 data: any,
995 options: {
996 mask?: boolean | undefined
997 binary?: boolean | undefined
998 compress?: boolean | undefined
999 fin?: boolean | undefined
1000 },
1001 cb?: (err?: Error) => void,
1002 ): void
1003 terminate(): void
1004
1005 /**
1006 * Pause the websocket causing it to stop emitting events. Some events can still be
1007 * emitted after this is called, until all buffered data is consumed. This method
1008 * is a noop if the ready state is `CONNECTING` or `CLOSED`.
1009 */
1010 pause(): void
1011 /**
1012 * Make a paused socket resume emitting events. This method is a noop if the ready
1013 * state is `CONNECTING` or `CLOSED`.
1014 */
1015 resume(): void
1016
1017 // HTML5 WebSocket events
1018 addEventListener(
1019 method: 'message',
1020 cb: (event: WebSocket.MessageEvent) => void,
1021 options?: WebSocket.EventListenerOptions,
1022 ): void
1023 addEventListener(
1024 method: 'close',
1025 cb: (event: WebSocket.CloseEvent) => void,
1026 options?: WebSocket.EventListenerOptions,
1027 ): void
1028 addEventListener(
1029 method: 'error',
1030 cb: (event: WebSocket.ErrorEvent) => void,
1031 options?: WebSocket.EventListenerOptions,
1032 ): void
1033 addEventListener(
1034 method: 'open',
1035 cb: (event: WebSocket.Event) => void,
1036 options?: WebSocket.EventListenerOptions,
1037 ): void
1038
1039 removeEventListener(
1040 method: 'message',
1041 cb: (event: WebSocket.MessageEvent) => void,
1042 ): void
1043 removeEventListener(
1044 method: 'close',
1045 cb: (event: WebSocket.CloseEvent) => void,
1046 ): void
1047 removeEventListener(
1048 method: 'error',
1049 cb: (event: WebSocket.ErrorEvent) => void,
1050 ): void
1051 removeEventListener(
1052 method: 'open',
1053 cb: (event: WebSocket.Event) => void,
1054 ): void
1055
1056 // Events
1057 on(
1058 event: 'close',
1059 listener: (this: WebSocket, code: number, reason: Buffer) => void,
1060 ): this
1061 on(event: 'error', listener: (this: WebSocket, err: Error) => void): this
1062 on(
1063 event: 'upgrade',
1064 listener: (this: WebSocket, request: IncomingMessage) => void,
1065 ): this
1066 on(
1067 event: 'message',
1068 listener: (
1069 this: WebSocket,
1070 data: WebSocket.RawData,
1071 isBinary: boolean,
1072 ) => void,
1073 ): this
1074 on(event: 'open', listener: (this: WebSocket) => void): this
1075 on(
1076 event: 'ping' | 'pong',
1077 listener: (this: WebSocket, data: Buffer) => void,
1078 ): this
1079 on(
1080 event: 'unexpected-response',
1081 listener: (
1082 this: WebSocket,
1083 request: ClientRequest,
1084 response: IncomingMessage,
1085 ) => void,
1086 ): this
1087 on(
1088 event: string | symbol,
1089 listener: (this: WebSocket, ...args: any[]) => void,
1090 ): this
1091
1092 once(
1093 event: 'close',
1094 listener: (this: WebSocket, code: number, reason: Buffer) => void,
1095 ): this
1096 once(event: 'error', listener: (this: WebSocket, err: Error) => void): this
1097 once(
1098 event: 'upgrade',
1099 listener: (this: WebSocket, request: IncomingMessage) => void,
1100 ): this
1101 once(
1102 event: 'message',
1103 listener: (
1104 this: WebSocket,
1105 data: WebSocket.RawData,
1106 isBinary: boolean,
1107 ) => void,
1108 ): this
1109 once(event: 'open', listener: (this: WebSocket) => void): this
1110 once(
1111 event: 'ping' | 'pong',
1112 listener: (this: WebSocket, data: Buffer) => void,
1113 ): this
1114 once(
1115 event: 'unexpected-response',
1116 listener: (
1117 this: WebSocket,
1118 request: ClientRequest,
1119 response: IncomingMessage,
1120 ) => void,
1121 ): this
1122 once(
1123 event: string | symbol,
1124 listener: (this: WebSocket, ...args: any[]) => void,
1125 ): this
1126
1127 off(
1128 event: 'close',
1129 listener: (this: WebSocket, code: number, reason: Buffer) => void,
1130 ): this
1131 off(event: 'error', listener: (this: WebSocket, err: Error) => void): this
1132 off(
1133 event: 'upgrade',
1134 listener: (this: WebSocket, request: IncomingMessage) => void,
1135 ): this
1136 off(
1137 event: 'message',
1138 listener: (
1139 this: WebSocket,
1140 data: WebSocket.RawData,
1141 isBinary: boolean,
1142 ) => void,
1143 ): this
1144 off(event: 'open', listener: (this: WebSocket) => void): this
1145 off(
1146 event: 'ping' | 'pong',
1147 listener: (this: WebSocket, data: Buffer) => void,
1148 ): this
1149 off(
1150 event: 'unexpected-response',
1151 listener: (
1152 this: WebSocket,
1153 request: ClientRequest,
1154 response: IncomingMessage,
1155 ) => void,
1156 ): this
1157 off(
1158 event: string | symbol,
1159 listener: (this: WebSocket, ...args: any[]) => void,
1160 ): this
1161
1162 addListener(
1163 event: 'close',
1164 listener: (code: number, reason: Buffer) => void,
1165 ): this
1166 addListener(event: 'error', listener: (err: Error) => void): this
1167 addListener(
1168 event: 'upgrade',
1169 listener: (request: IncomingMessage) => void,
1170 ): this
1171 addListener(
1172 event: 'message',
1173 listener: (data: WebSocket.RawData, isBinary: boolean) => void,
1174 ): this
1175 addListener(event: 'open', listener: () => void): this
1176 addListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
1177 addListener(
1178 event: 'unexpected-response',
1179 listener: (request: ClientRequest, response: IncomingMessage) => void,
1180 ): this
1181 addListener(event: string | symbol, listener: (...args: any[]) => void): this
1182
1183 removeListener(
1184 event: 'close',
1185 listener: (code: number, reason: Buffer) => void,
1186 ): this
1187 removeListener(event: 'error', listener: (err: Error) => void): this
1188 removeListener(
1189 event: 'upgrade',
1190 listener: (request: IncomingMessage) => void,
1191 ): this
1192 removeListener(
1193 event: 'message',
1194 listener: (data: WebSocket.RawData, isBinary: boolean) => void,
1195 ): this
1196 removeListener(event: 'open', listener: () => void): this
1197 removeListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
1198 removeListener(
1199 event: 'unexpected-response',
1200 listener: (request: ClientRequest, response: IncomingMessage) => void,
1201 ): this
1202 removeListener(
1203 event: string | symbol,
1204 listener: (...args: any[]) => void,
1205 ): this
1206}
1207 // tslint:disable-line no-empty-interface
1208
1209declare namespace WebSocket {
1210 /**
1211 * Data represents the raw message payload received over the WebSocket.
1212 */
1213 type RawData = Buffer | ArrayBuffer | Buffer[]
1214
1215 /**
1216 * Data represents the message payload received over the WebSocket.
1217 */
1218 type Data = string | Buffer | ArrayBuffer | Buffer[]
1219
1220 /**
1221 * CertMeta represents the accepted types for certificate & key data.
1222 */
1223 type CertMeta = string | string[] | Buffer | Buffer[]
1224
1225 /**
1226 * VerifyClientCallbackSync is a synchronous callback used to inspect the
1227 * incoming message. The return value (boolean) of the function determines
1228 * whether or not to accept the handshake.
1229 */
1230 type VerifyClientCallbackSync = (info: {
1231 origin: string
1232 secure: boolean
1233 req: IncomingMessage
1234 }) => boolean
1235
1236 /**
1237 * VerifyClientCallbackAsync is an asynchronous callback used to inspect the
1238 * incoming message. The return value (boolean) of the function determines
1239 * whether or not to accept the handshake.
1240 */
1241 type VerifyClientCallbackAsync = (
1242 info: { origin: string; secure: boolean; req: IncomingMessage },
1243 callback: (
1244 res: boolean,
1245 code?: number,
1246 message?: string,
1247 headers?: OutgoingHttpHeaders,
1248 ) => void,
1249 ) => void
1250
1251 interface ClientOptions extends SecureContextOptions {
1252 protocol?: string | undefined
1253 followRedirects?: boolean | undefined
1254 generateMask?(mask: Buffer): void
1255 handshakeTimeout?: number | undefined
1256 maxRedirects?: number | undefined
1257 perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
1258 localAddress?: string | undefined
1259 protocolVersion?: number | undefined
1260 headers?: { [key: string]: string } | undefined
1261 origin?: string | undefined
1262 agent?: Agent | undefined
1263 host?: string | undefined
1264 family?: number | undefined
1265 checkServerIdentity?(servername: string, cert: CertMeta): boolean
1266 rejectUnauthorized?: boolean | undefined
1267 maxPayload?: number | undefined
1268 skipUTF8Validation?: boolean | undefined
1269 }
1270
1271 interface PerMessageDeflateOptions {
1272 serverNoContextTakeover?: boolean | undefined
1273 clientNoContextTakeover?: boolean | undefined
1274 serverMaxWindowBits?: number | undefined
1275 clientMaxWindowBits?: number | undefined
1276 zlibDeflateOptions?:
1277 | {
1278 flush?: number | undefined
1279 finishFlush?: number | undefined
1280 chunkSize?: number | undefined
1281 windowBits?: number | undefined
1282 level?: number | undefined
1283 memLevel?: number | undefined
1284 strategy?: number | undefined
1285 dictionary?: Buffer | Buffer[] | DataView | undefined
1286 info?: boolean | undefined
1287 }
1288 | undefined
1289 zlibInflateOptions?: ZlibOptions | undefined
1290 threshold?: number | undefined
1291 concurrencyLimit?: number | undefined
1292 }
1293
1294 interface Event {
1295 type: string
1296 target: WebSocket
1297 }
1298
1299 interface ErrorEvent {
1300 error: any
1301 message: string
1302 type: string
1303 target: WebSocket
1304 }
1305
1306 interface CloseEvent {
1307 wasClean: boolean
1308 code: number
1309 reason: string
1310 type: string
1311 target: WebSocket
1312 }
1313
1314 interface MessageEvent {
1315 data: Data
1316 type: string
1317 target: WebSocket
1318 }
1319
1320 interface EventListenerOptions {
1321 once?: boolean | undefined
1322 }
1323
1324 interface ServerOptions {
1325 host?: string | undefined
1326 port?: number | undefined
1327 backlog?: number | undefined
1328 server?: Server | HttpsServer | undefined
1329 verifyClient?:
1330 | VerifyClientCallbackAsync
1331 | VerifyClientCallbackSync
1332 | undefined
1333 handleProtocols?: (
1334 protocols: Set<string>,
1335 request: IncomingMessage,
1336 ) => string | false
1337 path?: string | undefined
1338 noServer?: boolean | undefined
1339 clientTracking?: boolean | undefined
1340 perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
1341 maxPayload?: number | undefined
1342 skipUTF8Validation?: boolean | undefined
1343 WebSocket?: typeof WebSocket.WebSocket | undefined
1344 }
1345
1346 interface AddressInfo {
1347 address: string
1348 family: string
1349 port: number
1350 }
1351
1352 // WebSocket Server
1353 class Server<T extends WebSocket = WebSocket> extends EventEmitter {
1354 options: ServerOptions
1355 path: string
1356 clients: Set<T>
1357
1358 constructor(options?: ServerOptions, callback?: () => void)
1359
1360 address(): AddressInfo | string
1361 close(cb?: (err?: Error) => void): void
1362 handleUpgrade(
1363 request: IncomingMessage,
1364 socket: Duplex,
1365 upgradeHead: Buffer,
1366 callback: (client: T, request: IncomingMessage) => void,
1367 ): void
1368 shouldHandle(request: IncomingMessage): boolean | Promise<boolean>
1369
1370 // Events
1371 on(
1372 event: 'connection',
1373 cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
1374 ): this
1375 on(event: 'error', cb: (this: Server<T>, error: Error) => void): this
1376 on(
1377 event: 'headers',
1378 cb: (
1379 this: Server<T>,
1380 headers: string[],
1381 request: IncomingMessage,
1382 ) => void,
1383 ): this
1384 on(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
1385 on(
1386 event: string | symbol,
1387 listener: (this: Server<T>, ...args: any[]) => void,
1388 ): this
1389
1390 once(
1391 event: 'connection',
1392 cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
1393 ): this
1394 once(event: 'error', cb: (this: Server<T>, error: Error) => void): this
1395 once(
1396 event: 'headers',
1397 cb: (
1398 this: Server<T>,
1399 headers: string[],
1400 request: IncomingMessage,
1401 ) => void,
1402 ): this
1403 once(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
1404 once(
1405 event: string | symbol,
1406 listener: (this: Server<T>, ...args: any[]) => void,
1407 ): this
1408
1409 off(
1410 event: 'connection',
1411 cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
1412 ): this
1413 off(event: 'error', cb: (this: Server<T>, error: Error) => void): this
1414 off(
1415 event: 'headers',
1416 cb: (
1417 this: Server<T>,
1418 headers: string[],
1419 request: IncomingMessage,
1420 ) => void,
1421 ): this
1422 off(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
1423 off(
1424 event: string | symbol,
1425 listener: (this: Server<T>, ...args: any[]) => void,
1426 ): this
1427
1428 addListener(
1429 event: 'connection',
1430 cb: (client: T, request: IncomingMessage) => void,
1431 ): this
1432 addListener(event: 'error', cb: (err: Error) => void): this
1433 addListener(
1434 event: 'headers',
1435 cb: (headers: string[], request: IncomingMessage) => void,
1436 ): this
1437 addListener(event: 'close' | 'listening', cb: () => void): this
1438 addListener(
1439 event: string | symbol,
1440 listener: (...args: any[]) => void,
1441 ): this
1442
1443 removeListener(event: 'connection', cb: (client: T) => void): this
1444 removeListener(event: 'error', cb: (err: Error) => void): this
1445 removeListener(
1446 event: 'headers',
1447 cb: (headers: string[], request: IncomingMessage) => void,
1448 ): this
1449 removeListener(event: 'close' | 'listening', cb: () => void): this
1450 removeListener(
1451 event: string | symbol,
1452 listener: (...args: any[]) => void,
1453 ): this
1454 }
1455
1456 const WebSocketServer: typeof Server
1457 interface WebSocketServer extends Server {} // tslint:disable-line no-empty-interface
1458 const WebSocket: typeof WebSocketAlias
1459 interface WebSocket extends WebSocketAlias {} // tslint:disable-line no-empty-interface
1460
1461 // WebSocket stream
1462 function createWebSocketStream(
1463 websocket: WebSocket,
1464 options?: DuplexOptions,
1465 ): Duplex
1466}
1467
1468interface HmrOptions {
1469 protocol?: string;
1470 host?: string;
1471 port?: number;
1472 clientPort?: number;
1473 path?: string;
1474 timeout?: number;
1475 overlay?: boolean;
1476 server?: HttpServer;
1477}
1478interface HmrContext {
1479 file: string;
1480 timestamp: number;
1481 modules: Array<ModuleNode>;
1482 read: () => string | Promise<string>;
1483 server: ViteDevServer;
1484}
1485interface HMRBroadcasterClient {
1486 /**
1487 * Send event to the client
1488 */
1489 send(payload: HMRPayload): void;
1490 /**
1491 * Send custom event
1492 */
1493 send(event: string, payload?: CustomPayload['data']): void;
1494}
1495interface HMRChannel {
1496 /**
1497 * Unique channel name
1498 */
1499 name: string;
1500 /**
1501 * Broadcast events to all clients
1502 */
1503 send(payload: HMRPayload): void;
1504 /**
1505 * Send custom event
1506 */
1507 send<T extends string>(event: T, payload?: InferCustomEventPayload<T>): void;
1508 /**
1509 * Handle custom event emitted by `import.meta.hot.send`
1510 */
1511 on<T extends string>(event: T, listener: (data: InferCustomEventPayload<T>, client: HMRBroadcasterClient, ...args: any[]) => void): void;
1512 on(event: 'connection', listener: () => void): void;
1513 /**
1514 * Unregister event listener
1515 */
1516 off(event: string, listener: Function): void;
1517 /**
1518 * Start listening for messages
1519 */
1520 listen(): void;
1521 /**
1522 * Disconnect all clients, called when server is closed or restarted.
1523 */
1524 close(): void;
1525}
1526interface HMRBroadcaster extends Omit<HMRChannel, 'close' | 'name'> {
1527 /**
1528 * All registered channels. Always has websocket channel.
1529 */
1530 readonly channels: HMRChannel[];
1531 /**
1532 * Add a new third-party channel.
1533 */
1534 addChannel(connection: HMRChannel): HMRBroadcaster;
1535 close(): Promise<unknown[]>;
1536}
1537interface ServerHMRChannel extends HMRChannel {
1538 api: {
1539 innerEmitter: EventEmitter;
1540 outsideEmitter: EventEmitter;
1541 };
1542}
1543
1544type WebSocketCustomListener<T> = (data: T, client: WebSocketClient) => void;
1545interface WebSocketServer extends HMRChannel {
1546 /**
1547 * Listen on port and host
1548 */
1549 listen(): void;
1550 /**
1551 * Get all connected clients.
1552 */
1553 clients: Set<WebSocketClient>;
1554 /**
1555 * Disconnect all clients and terminate the server.
1556 */
1557 close(): Promise<void>;
1558 /**
1559 * Handle custom event emitted by `import.meta.hot.send`
1560 */
1561 on: WebSocket.Server['on'] & {
1562 <T extends string>(event: T, listener: WebSocketCustomListener<InferCustomEventPayload<T>>): void;
1563 };
1564 /**
1565 * Unregister event listener.
1566 */
1567 off: WebSocket.Server['off'] & {
1568 (event: string, listener: Function): void;
1569 };
1570}
1571interface WebSocketClient {
1572 /**
1573 * Send event to the client
1574 */
1575 send(payload: HMRPayload): void;
1576 /**
1577 * Send custom event
1578 */
1579 send(event: string, payload?: CustomPayload['data']): void;
1580 /**
1581 * The raw WebSocket instance
1582 * @advanced
1583 */
1584 socket: WebSocket;
1585}
1586
1587interface ServerOptions extends CommonServerOptions {
1588 /**
1589 * Configure HMR-specific options (port, host, path & protocol)
1590 */
1591 hmr?: HmrOptions | boolean;
1592 /**
1593 * Do not start the websocket connection.
1594 * @experimental
1595 */
1596 ws?: false;
1597 /**
1598 * Warm-up files to transform and cache the results in advance. This improves the
1599 * initial page load during server starts and prevents transform waterfalls.
1600 */
1601 warmup?: {
1602 /**
1603 * The files to be transformed and used on the client-side. Supports glob patterns.
1604 */
1605 clientFiles?: string[];
1606 /**
1607 * The files to be transformed and used in SSR. Supports glob patterns.
1608 */
1609 ssrFiles?: string[];
1610 };
1611 /**
1612 * chokidar watch options or null to disable FS watching
1613 * https://github.com/paulmillr/chokidar#api
1614 */
1615 watch?: WatchOptions | null;
1616 /**
1617 * Create Vite dev server to be used as a middleware in an existing server
1618 * @default false
1619 */
1620 middlewareMode?: boolean | {
1621 /**
1622 * Parent server instance to attach to
1623 *
1624 * This is needed to proxy WebSocket connections to the parent server.
1625 */
1626 server: HttpServer;
1627 };
1628 /**
1629 * Options for files served via '/\@fs/'.
1630 */
1631 fs?: FileSystemServeOptions;
1632 /**
1633 * Origin for the generated asset URLs.
1634 *
1635 * @example `http://127.0.0.1:8080`
1636 */
1637 origin?: string;
1638 /**
1639 * Pre-transform known direct imports
1640 * @default true
1641 */
1642 preTransformRequests?: boolean;
1643 /**
1644 * Whether or not to ignore-list source files in the dev server sourcemap, used to populate
1645 * the [`x_google_ignoreList` source map extension](https://developer.chrome.com/blog/devtools-better-angular-debugging/#the-x_google_ignorelist-source-map-extension).
1646 *
1647 * By default, it excludes all paths containing `node_modules`. You can pass `false` to
1648 * disable this behavior, or, for full control, a function that takes the source path and
1649 * sourcemap path and returns whether to ignore the source path.
1650 */
1651 sourcemapIgnoreList?: false | ((sourcePath: string, sourcemapPath: string) => boolean);
1652}
1653interface ResolvedServerOptions extends Omit<ServerOptions, 'fs' | 'middlewareMode' | 'sourcemapIgnoreList'> {
1654 fs: Required<FileSystemServeOptions>;
1655 middlewareMode: NonNullable<ServerOptions['middlewareMode']>;
1656 sourcemapIgnoreList: Exclude<ServerOptions['sourcemapIgnoreList'], false | undefined>;
1657}
1658interface FileSystemServeOptions {
1659 /**
1660 * Strictly restrict file accessing outside of allowing paths.
1661 *
1662 * Set to `false` to disable the warning
1663 *
1664 * @default true
1665 */
1666 strict?: boolean;
1667 /**
1668 * Restrict accessing files outside the allowed directories.
1669 *
1670 * Accepts absolute path or a path relative to project root.
1671 * Will try to search up for workspace root by default.
1672 */
1673 allow?: string[];
1674 /**
1675 * Restrict accessing files that matches the patterns.
1676 *
1677 * This will have higher priority than `allow`.
1678 * picomatch patterns are supported.
1679 *
1680 * @default ['.env', '.env.*', '*.crt', '*.pem']
1681 */
1682 deny?: string[];
1683 /**
1684 * Enable caching of fs calls. It is enabled by default if no custom watch ignored patterns are provided.
1685 *
1686 * @experimental
1687 * @default undefined
1688 */
1689 cachedChecks?: boolean;
1690}
1691type ServerHook = (this: void, server: ViteDevServer) => (() => void) | void | Promise<(() => void) | void>;
1692type HttpServer = http.Server | Http2SecureServer;
1693interface ViteDevServer {
1694 /**
1695 * The resolved vite config object
1696 */
1697 config: ResolvedConfig;
1698 /**
1699 * A connect app instance.
1700 * - Can be used to attach custom middlewares to the dev server.
1701 * - Can also be used as the handler function of a custom http server
1702 * or as a middleware in any connect-style Node.js frameworks
1703 *
1704 * https://github.com/senchalabs/connect#use-middleware
1705 */
1706 middlewares: Connect.Server;
1707 /**
1708 * native Node http server instance
1709 * will be null in middleware mode
1710 */
1711 httpServer: HttpServer | null;
1712 /**
1713 * chokidar watcher instance
1714 * https://github.com/paulmillr/chokidar#api
1715 */
1716 watcher: FSWatcher;
1717 /**
1718 * web socket server with `send(payload)` method
1719 */
1720 ws: WebSocketServer;
1721 /**
1722 * HMR broadcaster that can be used to send custom HMR messages to the client
1723 *
1724 * Always sends a message to at least a WebSocket client. Any third party can
1725 * add a channel to the broadcaster to process messages
1726 * @deprecated will be replaced with the environment api in v6.
1727 */
1728 hot: HMRBroadcaster;
1729 /**
1730 * Rollup plugin container that can run plugin hooks on a given file
1731 */
1732 pluginContainer: PluginContainer;
1733 /**
1734 * Module graph that tracks the import relationships, url to file mapping
1735 * and hmr state.
1736 */
1737 moduleGraph: ModuleGraph;
1738 /**
1739 * The resolved urls Vite prints on the CLI. null in middleware mode or
1740 * before `server.listen` is called.
1741 */
1742 resolvedUrls: ResolvedServerUrls | null;
1743 /**
1744 * Programmatically resolve, load and transform a URL and get the result
1745 * without going through the http request pipeline.
1746 */
1747 transformRequest(url: string, options?: TransformOptions): Promise<TransformResult | null>;
1748 /**
1749 * Same as `transformRequest` but only warm up the URLs so the next request
1750 * will already be cached. The function will never throw as it handles and
1751 * reports errors internally.
1752 */
1753 warmupRequest(url: string, options?: TransformOptions): Promise<void>;
1754 /**
1755 * Apply vite built-in HTML transforms and any plugin HTML transforms.
1756 */
1757 transformIndexHtml(url: string, html: string, originalUrl?: string): Promise<string>;
1758 /**
1759 * Transform module code into SSR format.
1760 */
1761 ssrTransform(code: string, inMap: SourceMap | {
1762 mappings: '';
1763 } | null, url: string, originalCode?: string): Promise<TransformResult | null>;
1764 /**
1765 * Load a given URL as an instantiated module for SSR.
1766 */
1767 ssrLoadModule(url: string, opts?: {
1768 fixStacktrace?: boolean;
1769 }): Promise<Record<string, any>>;
1770 /**
1771 * Fetch information about the module for Vite SSR runtime.
1772 * @experimental
1773 */
1774 ssrFetchModule(id: string, importer?: string): Promise<FetchResult>;
1775 /**
1776 * Returns a fixed version of the given stack
1777 */
1778 ssrRewriteStacktrace(stack: string): string;
1779 /**
1780 * Mutates the given SSR error by rewriting the stacktrace
1781 */
1782 ssrFixStacktrace(e: Error): void;
1783 /**
1784 * Triggers HMR for a module in the module graph. You can use the `server.moduleGraph`
1785 * API to retrieve the module to be reloaded. If `hmr` is false, this is a no-op.
1786 */
1787 reloadModule(module: ModuleNode): Promise<void>;
1788 /**
1789 * Start the server.
1790 */
1791 listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>;
1792 /**
1793 * Stop the server.
1794 */
1795 close(): Promise<void>;
1796 /**
1797 * Print server urls
1798 */
1799 printUrls(): void;
1800 /**
1801 * Bind CLI shortcuts
1802 */
1803 bindCLIShortcuts(options?: BindCLIShortcutsOptions<ViteDevServer>): void;
1804 /**
1805 * Restart the server.
1806 *
1807 * @param forceOptimize - force the optimizer to re-bundle, same as --force cli flag
1808 */
1809 restart(forceOptimize?: boolean): Promise<void>;
1810 /**
1811 * Open browser
1812 */
1813 openBrowser(): void;
1814 /**
1815 * Calling `await server.waitForRequestsIdle(id)` will wait until all static imports
1816 * are processed. If called from a load or transform plugin hook, the id needs to be
1817 * passed as a parameter to avoid deadlocks. Calling this function after the first
1818 * static imports section of the module graph has been processed will resolve immediately.
1819 * @experimental
1820 */
1821 waitForRequestsIdle: (ignoredId?: string) => Promise<void>;
1822}
1823interface ResolvedServerUrls {
1824 local: string[];
1825 network: string[];
1826}
1827declare function createServer(inlineConfig?: InlineConfig): Promise<ViteDevServer>;
1828
1829/** Cache for package.json resolution and package.json contents */
1830type PackageCache = Map<string, PackageData>;
1831interface PackageData {
1832 dir: string;
1833 hasSideEffects: (id: string) => boolean | 'no-treeshake' | null;
1834 webResolvedImports: Record<string, string | undefined>;
1835 nodeResolvedImports: Record<string, string | undefined>;
1836 setResolvedCache: (key: string, entry: string, targetWeb: boolean) => void;
1837 getResolvedCache: (key: string, targetWeb: boolean) => string | undefined;
1838 data: {
1839 [field: string]: any;
1840 name: string;
1841 type: string;
1842 version: string;
1843 main: string;
1844 module: string;
1845 browser: string | Record<string, string | false>;
1846 exports: string | Record<string, any> | string[];
1847 imports: Record<string, any>;
1848 dependencies: Record<string, string>;
1849 };
1850}
1851
1852interface RollupCommonJSOptions {
1853 /**
1854 * A minimatch pattern, or array of patterns, which specifies the files in
1855 * the build the plugin should operate on. By default, all files with
1856 * extension `".cjs"` or those in `extensions` are included, but you can
1857 * narrow this list by only including specific files. These files will be
1858 * analyzed and transpiled if either the analysis does not find ES module
1859 * specific statements or `transformMixedEsModules` is `true`.
1860 * @default undefined
1861 */
1862 include?: string | RegExp | readonly (string | RegExp)[]
1863 /**
1864 * A minimatch pattern, or array of patterns, which specifies the files in
1865 * the build the plugin should _ignore_. By default, all files with
1866 * extensions other than those in `extensions` or `".cjs"` are ignored, but you
1867 * can exclude additional files. See also the `include` option.
1868 * @default undefined
1869 */
1870 exclude?: string | RegExp | readonly (string | RegExp)[]
1871 /**
1872 * For extensionless imports, search for extensions other than .js in the
1873 * order specified. Note that you need to make sure that non-JavaScript files
1874 * are transpiled by another plugin first.
1875 * @default [ '.js' ]
1876 */
1877 extensions?: ReadonlyArray<string>
1878 /**
1879 * If true then uses of `global` won't be dealt with by this plugin
1880 * @default false
1881 */
1882 ignoreGlobal?: boolean
1883 /**
1884 * If false, skips source map generation for CommonJS modules. This will
1885 * improve performance.
1886 * @default true
1887 */
1888 sourceMap?: boolean
1889 /**
1890 * Some `require` calls cannot be resolved statically to be translated to
1891 * imports.
1892 * When this option is set to `false`, the generated code will either
1893 * directly throw an error when such a call is encountered or, when
1894 * `dynamicRequireTargets` is used, when such a call cannot be resolved with a
1895 * configured dynamic require target.
1896 * Setting this option to `true` will instead leave the `require` call in the
1897 * code or use it as a fallback for `dynamicRequireTargets`.
1898 * @default false
1899 */
1900 ignoreDynamicRequires?: boolean
1901 /**
1902 * Instructs the plugin whether to enable mixed module transformations. This
1903 * is useful in scenarios with modules that contain a mix of ES `import`
1904 * statements and CommonJS `require` expressions. Set to `true` if `require`
1905 * calls should be transformed to imports in mixed modules, or `false` if the
1906 * `require` expressions should survive the transformation. The latter can be
1907 * important if the code contains environment detection, or you are coding
1908 * for an environment with special treatment for `require` calls such as
1909 * ElectronJS. See also the `ignore` option.
1910 * @default false
1911 */
1912 transformMixedEsModules?: boolean
1913 /**
1914 * By default, this plugin will try to hoist `require` statements as imports
1915 * to the top of each file. While this works well for many code bases and
1916 * allows for very efficient ESM output, it does not perfectly capture
1917 * CommonJS semantics as the order of side effects like log statements may
1918 * change. But it is especially problematic when there are circular `require`
1919 * calls between CommonJS modules as those often rely on the lazy execution of
1920 * nested `require` calls.
1921 *
1922 * Setting this option to `true` will wrap all CommonJS files in functions
1923 * which are executed when they are required for the first time, preserving
1924 * NodeJS semantics. Note that this can have an impact on the size and
1925 * performance of the generated code.
1926 *
1927 * The default value of `"auto"` will only wrap CommonJS files when they are
1928 * part of a CommonJS dependency cycle, e.g. an index file that is required by
1929 * many of its dependencies. All other CommonJS files are hoisted. This is the
1930 * recommended setting for most code bases.
1931 *
1932 * `false` will entirely prevent wrapping and hoist all files. This may still
1933 * work depending on the nature of cyclic dependencies but will often cause
1934 * problems.
1935 *
1936 * You can also provide a minimatch pattern, or array of patterns, to only
1937 * specify a subset of files which should be wrapped in functions for proper
1938 * `require` semantics.
1939 *
1940 * `"debug"` works like `"auto"` but after bundling, it will display a warning
1941 * containing a list of ids that have been wrapped which can be used as
1942 * minimatch pattern for fine-tuning.
1943 * @default "auto"
1944 */
1945 strictRequires?: boolean | string | RegExp | readonly (string | RegExp)[]
1946 /**
1947 * Sometimes you have to leave require statements unconverted. Pass an array
1948 * containing the IDs or a `id => boolean` function.
1949 * @default []
1950 */
1951 ignore?: ReadonlyArray<string> | ((id: string) => boolean)
1952 /**
1953 * In most cases, where `require` calls are inside a `try-catch` clause,
1954 * they should be left unconverted as it requires an optional dependency
1955 * that may or may not be installed beside the rolled up package.
1956 * Due to the conversion of `require` to a static `import` - the call is
1957 * hoisted to the top of the file, outside the `try-catch` clause.
1958 *
1959 * - `true`: Default. All `require` calls inside a `try` will be left unconverted.
1960 * - `false`: All `require` calls inside a `try` will be converted as if the
1961 * `try-catch` clause is not there.
1962 * - `remove`: Remove all `require` calls from inside any `try` block.
1963 * - `string[]`: Pass an array containing the IDs to left unconverted.
1964 * - `((id: string) => boolean|'remove')`: Pass a function that controls
1965 * individual IDs.
1966 *
1967 * @default true
1968 */
1969 ignoreTryCatch?:
1970 | boolean
1971 | 'remove'
1972 | ReadonlyArray<string>
1973 | ((id: string) => boolean | 'remove')
1974 /**
1975 * Controls how to render imports from external dependencies. By default,
1976 * this plugin assumes that all external dependencies are CommonJS. This
1977 * means they are rendered as default imports to be compatible with e.g.
1978 * NodeJS where ES modules can only import a default export from a CommonJS
1979 * dependency.
1980 *
1981 * If you set `esmExternals` to `true`, this plugin assumes that all
1982 * external dependencies are ES modules and respect the
1983 * `requireReturnsDefault` option. If that option is not set, they will be
1984 * rendered as namespace imports.
1985 *
1986 * You can also supply an array of ids to be treated as ES modules, or a
1987 * function that will be passed each external id to determine whether it is
1988 * an ES module.
1989 * @default false
1990 */
1991 esmExternals?: boolean | ReadonlyArray<string> | ((id: string) => boolean)
1992 /**
1993 * Controls what is returned when requiring an ES module from a CommonJS file.
1994 * When using the `esmExternals` option, this will also apply to external
1995 * modules. By default, this plugin will render those imports as namespace
1996 * imports i.e.
1997 *
1998 * ```js
1999 * // input
2000 * const foo = require('foo');
2001 *
2002 * // output
2003 * import * as foo from 'foo';
2004 * ```
2005 *
2006 * However, there are some situations where this may not be desired.
2007 * For these situations, you can change Rollup's behaviour either globally or
2008 * per module. To change it globally, set the `requireReturnsDefault` option
2009 * to one of the following values:
2010 *
2011 * - `false`: This is the default, requiring an ES module returns its
2012 * namespace. This is the only option that will also add a marker
2013 * `__esModule: true` to the namespace to support interop patterns in
2014 * CommonJS modules that are transpiled ES modules.
2015 * - `"namespace"`: Like `false`, requiring an ES module returns its
2016 * namespace, but the plugin does not add the `__esModule` marker and thus
2017 * creates more efficient code. For external dependencies when using
2018 * `esmExternals: true`, no additional interop code is generated.
2019 * - `"auto"`: This is complementary to how `output.exports: "auto"` works in
2020 * Rollup: If a module has a default export and no named exports, requiring
2021 * that module returns the default export. In all other cases, the namespace
2022 * is returned. For external dependencies when using `esmExternals: true`, a
2023 * corresponding interop helper is added.
2024 * - `"preferred"`: If a module has a default export, requiring that module
2025 * always returns the default export, no matter whether additional named
2026 * exports exist. This is similar to how previous versions of this plugin
2027 * worked. Again for external dependencies when using `esmExternals: true`,
2028 * an interop helper is added.
2029 * - `true`: This will always try to return the default export on require
2030 * without checking if it actually exists. This can throw at build time if
2031 * there is no default export. This is how external dependencies are handled
2032 * when `esmExternals` is not used. The advantage over the other options is
2033 * that, like `false`, this does not add an interop helper for external
2034 * dependencies, keeping the code lean.
2035 *
2036 * To change this for individual modules, you can supply a function for
2037 * `requireReturnsDefault` instead. This function will then be called once for
2038 * each required ES module or external dependency with the corresponding id
2039 * and allows you to return different values for different modules.
2040 * @default false
2041 */
2042 requireReturnsDefault?:
2043 | boolean
2044 | 'auto'
2045 | 'preferred'
2046 | 'namespace'
2047 | ((id: string) => boolean | 'auto' | 'preferred' | 'namespace')
2048
2049 /**
2050 * @default "auto"
2051 */
2052 defaultIsModuleExports?: boolean | 'auto' | ((id: string) => boolean | 'auto')
2053 /**
2054 * Some modules contain dynamic `require` calls, or require modules that
2055 * contain circular dependencies, which are not handled well by static
2056 * imports. Including those modules as `dynamicRequireTargets` will simulate a
2057 * CommonJS (NodeJS-like) environment for them with support for dynamic
2058 * dependencies. It also enables `strictRequires` for those modules.
2059 *
2060 * Note: In extreme cases, this feature may result in some paths being
2061 * rendered as absolute in the final bundle. The plugin tries to avoid
2062 * exposing paths from the local machine, but if you are `dynamicRequirePaths`
2063 * with paths that are far away from your project's folder, that may require
2064 * replacing strings like `"/Users/John/Desktop/foo-project/"` -\> `"/"`.
2065 */
2066 dynamicRequireTargets?: string | ReadonlyArray<string>
2067 /**
2068 * To avoid long paths when using the `dynamicRequireTargets` option, you can use this option to specify a directory
2069 * that is a common parent for all files that use dynamic require statements. Using a directory higher up such as `/`
2070 * may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your
2071 * home directory name. By default, it uses the current working directory.
2072 */
2073 dynamicRequireRoot?: string
2074}
2075
2076interface RollupDynamicImportVarsOptions {
2077 /**
2078 * Files to include in this plugin (default all).
2079 * @default []
2080 */
2081 include?: string | RegExp | (string | RegExp)[]
2082 /**
2083 * Files to exclude in this plugin (default none).
2084 * @default []
2085 */
2086 exclude?: string | RegExp | (string | RegExp)[]
2087 /**
2088 * By default, the plugin quits the build process when it encounters an error. If you set this option to true, it will throw a warning instead and leave the code untouched.
2089 * @default false
2090 */
2091 warnOnError?: boolean
2092}
2093
2094// Modified and inlined to avoid extra dependency
2095// Source: https://github.com/terser/terser/blob/master/tools/terser.d.ts
2096// BSD Licensed https://github.com/terser/terser/blob/master/LICENSE
2097
2098declare namespace Terser {
2099 export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020
2100
2101 export type ConsoleProperty = keyof typeof console
2102 type DropConsoleOption = boolean | ConsoleProperty[]
2103
2104 export interface ParseOptions {
2105 bare_returns?: boolean
2106 /** @deprecated legacy option. Currently, all supported EcmaScript is valid to parse. */
2107 ecma?: ECMA
2108 html5_comments?: boolean
2109 shebang?: boolean
2110 }
2111
2112 export interface CompressOptions {
2113 arguments?: boolean
2114 arrows?: boolean
2115 booleans_as_integers?: boolean
2116 booleans?: boolean
2117 collapse_vars?: boolean
2118 comparisons?: boolean
2119 computed_props?: boolean
2120 conditionals?: boolean
2121 dead_code?: boolean
2122 defaults?: boolean
2123 directives?: boolean
2124 drop_console?: DropConsoleOption
2125 drop_debugger?: boolean
2126 ecma?: ECMA
2127 evaluate?: boolean
2128 expression?: boolean
2129 global_defs?: object
2130 hoist_funs?: boolean
2131 hoist_props?: boolean
2132 hoist_vars?: boolean
2133 ie8?: boolean
2134 if_return?: boolean
2135 inline?: boolean | InlineFunctions
2136 join_vars?: boolean
2137 keep_classnames?: boolean | RegExp
2138 keep_fargs?: boolean
2139 keep_fnames?: boolean | RegExp
2140 keep_infinity?: boolean
2141 loops?: boolean
2142 module?: boolean
2143 negate_iife?: boolean
2144 passes?: number
2145 properties?: boolean
2146 pure_funcs?: string[]
2147 pure_new?: boolean
2148 pure_getters?: boolean | 'strict'
2149 reduce_funcs?: boolean
2150 reduce_vars?: boolean
2151 sequences?: boolean | number
2152 side_effects?: boolean
2153 switches?: boolean
2154 toplevel?: boolean
2155 top_retain?: null | string | string[] | RegExp
2156 typeofs?: boolean
2157 unsafe_arrows?: boolean
2158 unsafe?: boolean
2159 unsafe_comps?: boolean
2160 unsafe_Function?: boolean
2161 unsafe_math?: boolean
2162 unsafe_symbols?: boolean
2163 unsafe_methods?: boolean
2164 unsafe_proto?: boolean
2165 unsafe_regexp?: boolean
2166 unsafe_undefined?: boolean
2167 unused?: boolean
2168 }
2169
2170 export enum InlineFunctions {
2171 Disabled = 0,
2172 SimpleFunctions = 1,
2173 WithArguments = 2,
2174 WithArgumentsAndVariables = 3,
2175 }
2176
2177 export interface MangleOptions {
2178 eval?: boolean
2179 keep_classnames?: boolean | RegExp
2180 keep_fnames?: boolean | RegExp
2181 module?: boolean
2182 nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler
2183 properties?: boolean | ManglePropertiesOptions
2184 reserved?: string[]
2185 safari10?: boolean
2186 toplevel?: boolean
2187 }
2188
2189 /**
2190 * An identifier mangler for which the output is invariant with respect to the source code.
2191 */
2192 export interface SimpleIdentifierMangler {
2193 /**
2194 * Obtains the nth most favored (usually shortest) identifier to rename a variable to.
2195 * The mangler will increment n and retry until the return value is not in use in scope, and is not a reserved word.
2196 * This function is expected to be stable; Evaluating get(n) === get(n) should always return true.
2197 * @param n The ordinal of the identifier.
2198 */
2199 get(n: number): string
2200 }
2201
2202 /**
2203 * An identifier mangler that leverages character frequency analysis to determine identifier precedence.
2204 */
2205 export interface WeightedIdentifierMangler extends SimpleIdentifierMangler {
2206 /**
2207 * Modifies the internal weighting of the input characters by the specified delta.
2208 * Will be invoked on the entire printed AST, and then deduct mangleable identifiers.
2209 * @param chars The characters to modify the weighting of.
2210 * @param delta The numeric weight to add to the characters.
2211 */
2212 consider(chars: string, delta: number): number
2213 /**
2214 * Resets character weights.
2215 */
2216 reset(): void
2217 /**
2218 * Sorts identifiers by character frequency, in preparation for calls to get(n).
2219 */
2220 sort(): void
2221 }
2222
2223 export interface ManglePropertiesOptions {
2224 builtins?: boolean
2225 debug?: boolean
2226 keep_quoted?: boolean | 'strict'
2227 nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler
2228 regex?: RegExp | string
2229 reserved?: string[]
2230 }
2231
2232 export interface FormatOptions {
2233 ascii_only?: boolean
2234 /** @deprecated Not implemented anymore */
2235 beautify?: boolean
2236 braces?: boolean
2237 comments?:
2238 | boolean
2239 | 'all'
2240 | 'some'
2241 | RegExp
2242 | ((
2243 node: any,
2244 comment: {
2245 value: string
2246 type: 'comment1' | 'comment2' | 'comment3' | 'comment4'
2247 pos: number
2248 line: number
2249 col: number
2250 },
2251 ) => boolean)
2252 ecma?: ECMA
2253 ie8?: boolean
2254 keep_numbers?: boolean
2255 indent_level?: number
2256 indent_start?: number
2257 inline_script?: boolean
2258 keep_quoted_props?: boolean
2259 max_line_len?: number | false
2260 preamble?: string
2261 preserve_annotations?: boolean
2262 quote_keys?: boolean
2263 quote_style?: OutputQuoteStyle
2264 safari10?: boolean
2265 semicolons?: boolean
2266 shebang?: boolean
2267 shorthand?: boolean
2268 source_map?: SourceMapOptions
2269 webkit?: boolean
2270 width?: number
2271 wrap_iife?: boolean
2272 wrap_func_args?: boolean
2273 }
2274
2275 export enum OutputQuoteStyle {
2276 PreferDouble = 0,
2277 AlwaysSingle = 1,
2278 AlwaysDouble = 2,
2279 AlwaysOriginal = 3,
2280 }
2281
2282 export interface MinifyOptions {
2283 compress?: boolean | CompressOptions
2284 ecma?: ECMA
2285 enclose?: boolean | string
2286 ie8?: boolean
2287 keep_classnames?: boolean | RegExp
2288 keep_fnames?: boolean | RegExp
2289 mangle?: boolean | MangleOptions
2290 module?: boolean
2291 nameCache?: object
2292 format?: FormatOptions
2293 /** @deprecated */
2294 output?: FormatOptions
2295 parse?: ParseOptions
2296 safari10?: boolean
2297 sourceMap?: boolean | SourceMapOptions
2298 toplevel?: boolean
2299 }
2300
2301 export interface MinifyOutput {
2302 code?: string
2303 map?: object | string
2304 decoded_map?: object | null
2305 }
2306
2307 export interface SourceMapOptions {
2308 /** Source map object, 'inline' or source map file content */
2309 content?: object | string
2310 includeSources?: boolean
2311 filename?: string
2312 root?: string
2313 asObject?: boolean
2314 url?: string | 'inline'
2315 }
2316}
2317
2318interface TerserOptions extends Terser.MinifyOptions {
2319 /**
2320 * Vite-specific option to specify the max number of workers to spawn
2321 * when minifying files with terser.
2322 *
2323 * @default number of CPUs minus 1
2324 */
2325 maxWorkers?: number;
2326}
2327
2328interface BuildOptions {
2329 /**
2330 * Compatibility transform target. The transform is performed with esbuild
2331 * and the lowest supported target is es2015/es6. Note this only handles
2332 * syntax transformation and does not cover polyfills (except for dynamic
2333 * import)
2334 *
2335 * Default: 'modules' - Similar to `@babel/preset-env`'s targets.esmodules,
2336 * transpile targeting browsers that natively support dynamic es module imports.
2337 * https://caniuse.com/es6-module-dynamic-import
2338 *
2339 * Another special value is 'esnext' - which only performs minimal transpiling
2340 * (for minification compat) and assumes native dynamic imports support.
2341 *
2342 * For custom targets, see https://esbuild.github.io/api/#target and
2343 * https://esbuild.github.io/content-types/#javascript for more details.
2344 * @default 'modules'
2345 */
2346 target?: 'modules' | esbuild_TransformOptions['target'] | false;
2347 /**
2348 * whether to inject module preload polyfill.
2349 * Note: does not apply to library mode.
2350 * @default true
2351 * @deprecated use `modulePreload.polyfill` instead
2352 */
2353 polyfillModulePreload?: boolean;
2354 /**
2355 * Configure module preload
2356 * Note: does not apply to library mode.
2357 * @default true
2358 */
2359 modulePreload?: boolean | ModulePreloadOptions;
2360 /**
2361 * Directory relative from `root` where build output will be placed. If the
2362 * directory exists, it will be removed before the build.
2363 * @default 'dist'
2364 */
2365 outDir?: string;
2366 /**
2367 * Directory relative from `outDir` where the built js/css/image assets will
2368 * be placed.
2369 * @default 'assets'
2370 */
2371 assetsDir?: string;
2372 /**
2373 * Static asset files smaller than this number (in bytes) will be inlined as
2374 * base64 strings. Default limit is `4096` (4 KiB). Set to `0` to disable.
2375 * @default 4096
2376 */
2377 assetsInlineLimit?: number | ((filePath: string, content: Buffer) => boolean | undefined);
2378 /**
2379 * Whether to code-split CSS. When enabled, CSS in async chunks will be
2380 * inlined as strings in the chunk and inserted via dynamically created
2381 * style tags when the chunk is loaded.
2382 * @default true
2383 */
2384 cssCodeSplit?: boolean;
2385 /**
2386 * An optional separate target for CSS minification.
2387 * As esbuild only supports configuring targets to mainstream
2388 * browsers, users may need this option when they are targeting
2389 * a niche browser that comes with most modern JavaScript features
2390 * but has poor CSS support, e.g. Android WeChat WebView, which
2391 * doesn't support the #RGBA syntax.
2392 * @default target
2393 */
2394 cssTarget?: esbuild_TransformOptions['target'] | false;
2395 /**
2396 * Override CSS minification specifically instead of defaulting to `build.minify`,
2397 * so you can configure minification for JS and CSS separately.
2398 * @default 'esbuild'
2399 */
2400 cssMinify?: boolean | 'esbuild' | 'lightningcss';
2401 /**
2402 * If `true`, a separate sourcemap file will be created. If 'inline', the
2403 * sourcemap will be appended to the resulting output file as data URI.
2404 * 'hidden' works like `true` except that the corresponding sourcemap
2405 * comments in the bundled files are suppressed.
2406 * @default false
2407 */
2408 sourcemap?: boolean | 'inline' | 'hidden';
2409 /**
2410 * Set to `false` to disable minification, or specify the minifier to use.
2411 * Available options are 'terser' or 'esbuild'.
2412 * @default 'esbuild'
2413 */
2414 minify?: boolean | 'terser' | 'esbuild';
2415 /**
2416 * Options for terser
2417 * https://terser.org/docs/api-reference#minify-options
2418 *
2419 * In addition, you can also pass a `maxWorkers: number` option to specify the
2420 * max number of workers to spawn. Defaults to the number of CPUs minus 1.
2421 */
2422 terserOptions?: TerserOptions;
2423 /**
2424 * Will be merged with internal rollup options.
2425 * https://rollupjs.org/configuration-options/
2426 */
2427 rollupOptions?: RollupOptions;
2428 /**
2429 * Options to pass on to `@rollup/plugin-commonjs`
2430 */
2431 commonjsOptions?: RollupCommonJSOptions;
2432 /**
2433 * Options to pass on to `@rollup/plugin-dynamic-import-vars`
2434 */
2435 dynamicImportVarsOptions?: RollupDynamicImportVarsOptions;
2436 /**
2437 * Whether to write bundle to disk
2438 * @default true
2439 */
2440 write?: boolean;
2441 /**
2442 * Empty outDir on write.
2443 * @default true when outDir is a sub directory of project root
2444 */
2445 emptyOutDir?: boolean | null;
2446 /**
2447 * Copy the public directory to outDir on write.
2448 * @default true
2449 */
2450 copyPublicDir?: boolean;
2451 /**
2452 * Whether to emit a .vite/manifest.json under assets dir to map hash-less filenames
2453 * to their hashed versions. Useful when you want to generate your own HTML
2454 * instead of using the one generated by Vite.
2455 *
2456 * Example:
2457 *
2458 * ```json
2459 * {
2460 * "main.js": {
2461 * "file": "main.68fe3fad.js",
2462 * "css": "main.e6b63442.css",
2463 * "imports": [...],
2464 * "dynamicImports": [...]
2465 * }
2466 * }
2467 * ```
2468 * @default false
2469 */
2470 manifest?: boolean | string;
2471 /**
2472 * Build in library mode. The value should be the global name of the lib in
2473 * UMD mode. This will produce esm + cjs + umd bundle formats with default
2474 * configurations that are suitable for distributing libraries.
2475 * @default false
2476 */
2477 lib?: LibraryOptions | false;
2478 /**
2479 * Produce SSR oriented build. Note this requires specifying SSR entry via
2480 * `rollupOptions.input`.
2481 * @default false
2482 */
2483 ssr?: boolean | string;
2484 /**
2485 * Generate SSR manifest for determining style links and asset preload
2486 * directives in production.
2487 * @default false
2488 */
2489 ssrManifest?: boolean | string;
2490 /**
2491 * Emit assets during SSR.
2492 * @default false
2493 */
2494 ssrEmitAssets?: boolean;
2495 /**
2496 * Set to false to disable reporting compressed chunk sizes.
2497 * Can slightly improve build speed.
2498 * @default true
2499 */
2500 reportCompressedSize?: boolean;
2501 /**
2502 * Adjust chunk size warning limit (in kB).
2503 * @default 500
2504 */
2505 chunkSizeWarningLimit?: number;
2506 /**
2507 * Rollup watch options
2508 * https://rollupjs.org/configuration-options/#watch
2509 * @default null
2510 */
2511 watch?: WatcherOptions | null;
2512}
2513interface LibraryOptions {
2514 /**
2515 * Path of library entry
2516 */
2517 entry: InputOption;
2518 /**
2519 * The name of the exposed global variable. Required when the `formats` option includes
2520 * `umd` or `iife`
2521 */
2522 name?: string;
2523 /**
2524 * Output bundle formats
2525 * @default ['es', 'umd']
2526 */
2527 formats?: LibraryFormats[];
2528 /**
2529 * The name of the package file output. The default file name is the name option
2530 * of the project package.json. It can also be defined as a function taking the
2531 * format as an argument.
2532 */
2533 fileName?: string | ((format: ModuleFormat, entryName: string) => string);
2534}
2535type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife' | 'system';
2536interface ModulePreloadOptions {
2537 /**
2538 * Whether to inject a module preload polyfill.
2539 * Note: does not apply to library mode.
2540 * @default true
2541 */
2542 polyfill?: boolean;
2543 /**
2544 * Resolve the list of dependencies to preload for a given dynamic import
2545 * @experimental
2546 */
2547 resolveDependencies?: ResolveModulePreloadDependenciesFn;
2548}
2549interface ResolvedModulePreloadOptions {
2550 polyfill: boolean;
2551 resolveDependencies?: ResolveModulePreloadDependenciesFn;
2552}
2553type ResolveModulePreloadDependenciesFn = (filename: string, deps: string[], context: {
2554 hostId: string;
2555 hostType: 'html' | 'js';
2556}) => string[];
2557interface ResolvedBuildOptions extends Required<Omit<BuildOptions, 'polyfillModulePreload'>> {
2558 modulePreload: false | ResolvedModulePreloadOptions;
2559}
2560/**
2561 * Bundles the app for production.
2562 * Returns a Promise containing the build result.
2563 */
2564declare function build(inlineConfig?: InlineConfig): Promise<RollupOutput | RollupOutput[] | RollupWatcher>;
2565type RenderBuiltAssetUrl = (filename: string, type: {
2566 type: 'asset' | 'public';
2567 hostId: string;
2568 hostType: 'js' | 'css' | 'html';
2569 ssr: boolean;
2570}) => string | {
2571 relative?: boolean;
2572 runtime?: string;
2573} | undefined;
2574
2575interface ESBuildOptions extends esbuild_TransformOptions {
2576 include?: string | RegExp | string[] | RegExp[];
2577 exclude?: string | RegExp | string[] | RegExp[];
2578 jsxInject?: string;
2579 /**
2580 * This option is not respected. Use `build.minify` instead.
2581 */
2582 minify?: never;
2583}
2584type ESBuildTransformResult = Omit<esbuild_TransformResult, 'map'> & {
2585 map: SourceMap;
2586};
2587declare function transformWithEsbuild(code: string, filename: string, options?: esbuild_TransformOptions, inMap?: object): Promise<ESBuildTransformResult>;
2588
2589type ExportsData = {
2590 hasModuleSyntax: boolean;
2591 exports: readonly string[];
2592 jsxLoader?: boolean;
2593};
2594interface DepsOptimizer {
2595 metadata: DepOptimizationMetadata;
2596 scanProcessing?: Promise<void>;
2597 registerMissingImport: (id: string, resolved: string) => OptimizedDepInfo;
2598 run: () => void;
2599 isOptimizedDepFile: (id: string) => boolean;
2600 isOptimizedDepUrl: (url: string) => boolean;
2601 getOptimizedDepId: (depInfo: OptimizedDepInfo) => string;
2602 close: () => Promise<void>;
2603 options: DepOptimizationOptions;
2604}
2605interface DepOptimizationConfig {
2606 /**
2607 * Force optimize listed dependencies (must be resolvable import paths,
2608 * cannot be globs).
2609 */
2610 include?: string[];
2611 /**
2612 * Do not optimize these dependencies (must be resolvable import paths,
2613 * cannot be globs).
2614 */
2615 exclude?: string[];
2616 /**
2617 * Forces ESM interop when importing these dependencies. Some legacy
2618 * packages advertise themselves as ESM but use `require` internally
2619 * @experimental
2620 */
2621 needsInterop?: string[];
2622 /**
2623 * Options to pass to esbuild during the dep scanning and optimization
2624 *
2625 * Certain options are omitted since changing them would not be compatible
2626 * with Vite's dep optimization.
2627 *
2628 * - `external` is also omitted, use Vite's `optimizeDeps.exclude` option
2629 * - `plugins` are merged with Vite's dep plugin
2630 *
2631 * https://esbuild.github.io/api
2632 */
2633 esbuildOptions?: Omit<esbuild_BuildOptions, 'bundle' | 'entryPoints' | 'external' | 'write' | 'watch' | 'outdir' | 'outfile' | 'outbase' | 'outExtension' | 'metafile'>;
2634 /**
2635 * List of file extensions that can be optimized. A corresponding esbuild
2636 * plugin must exist to handle the specific extension.
2637 *
2638 * By default, Vite can optimize `.mjs`, `.js`, `.ts`, and `.mts` files. This option
2639 * allows specifying additional extensions.
2640 *
2641 * @experimental
2642 */
2643 extensions?: string[];
2644 /**
2645 * Deps optimization during build was removed in Vite 5.1. This option is
2646 * now redundant and will be removed in a future version. Switch to using
2647 * `optimizeDeps.noDiscovery` and an empty or undefined `optimizeDeps.include`.
2648 * true or 'dev' disables the optimizer, false or 'build' leaves it enabled.
2649 * @default 'build'
2650 * @deprecated
2651 * @experimental
2652 */
2653 disabled?: boolean | 'build' | 'dev';
2654 /**
2655 * Automatic dependency discovery. When `noDiscovery` is true, only dependencies
2656 * listed in `include` will be optimized. The scanner isn't run for cold start
2657 * in this case. CJS-only dependencies must be present in `include` during dev.
2658 * @default false
2659 * @experimental
2660 */
2661 noDiscovery?: boolean;
2662 /**
2663 * When enabled, it will hold the first optimized deps results until all static
2664 * imports are crawled on cold start. This avoids the need for full-page reloads
2665 * when new dependencies are discovered and they trigger the generation of new
2666 * common chunks. If all dependencies are found by the scanner plus the explicitly
2667 * defined ones in `include`, it is better to disable this option to let the
2668 * browser process more requests in parallel.
2669 * @default true
2670 * @experimental
2671 */
2672 holdUntilCrawlEnd?: boolean;
2673}
2674type DepOptimizationOptions = DepOptimizationConfig & {
2675 /**
2676 * By default, Vite will crawl your `index.html` to detect dependencies that
2677 * need to be pre-bundled. If `build.rollupOptions.input` is specified, Vite
2678 * will crawl those entry points instead.
2679 *
2680 * If neither of these fit your needs, you can specify custom entries using
2681 * this option - the value should be a fast-glob pattern or array of patterns
2682 * (https://github.com/mrmlnc/fast-glob#basic-syntax) that are relative from
2683 * vite project root. This will overwrite default entries inference.
2684 */
2685 entries?: string | string[];
2686 /**
2687 * Force dep pre-optimization regardless of whether deps have changed.
2688 * @experimental
2689 */
2690 force?: boolean;
2691};
2692interface OptimizedDepInfo {
2693 id: string;
2694 file: string;
2695 src?: string;
2696 needsInterop?: boolean;
2697 browserHash?: string;
2698 fileHash?: string;
2699 /**
2700 * During optimization, ids can still be resolved to their final location
2701 * but the bundles may not yet be saved to disk
2702 */
2703 processing?: Promise<void>;
2704 /**
2705 * ExportData cache, discovered deps will parse the src entry to get exports
2706 * data used both to define if interop is needed and when pre-bundling
2707 */
2708 exportsData?: Promise<ExportsData>;
2709}
2710interface DepOptimizationMetadata {
2711 /**
2712 * The main hash is determined by user config and dependency lockfiles.
2713 * This is checked on server startup to avoid unnecessary re-bundles.
2714 */
2715 hash: string;
2716 /**
2717 * This hash is determined by dependency lockfiles.
2718 * This is checked on server startup to avoid unnecessary re-bundles.
2719 */
2720 lockfileHash: string;
2721 /**
2722 * This hash is determined by user config.
2723 * This is checked on server startup to avoid unnecessary re-bundles.
2724 */
2725 configHash: string;
2726 /**
2727 * The browser hash is determined by the main hash plus additional dependencies
2728 * discovered at runtime. This is used to invalidate browser requests to
2729 * optimized deps.
2730 */
2731 browserHash: string;
2732 /**
2733 * Metadata for each already optimized dependency
2734 */
2735 optimized: Record<string, OptimizedDepInfo>;
2736 /**
2737 * Metadata for non-entry optimized chunks and dynamic imports
2738 */
2739 chunks: Record<string, OptimizedDepInfo>;
2740 /**
2741 * Metadata for each newly discovered dependency after processing
2742 */
2743 discovered: Record<string, OptimizedDepInfo>;
2744 /**
2745 * OptimizedDepInfo list
2746 */
2747 depInfoList: OptimizedDepInfo[];
2748}
2749/**
2750 * Scan and optimize dependencies within a project.
2751 * Used by Vite CLI when running `vite optimize`.
2752 */
2753declare function optimizeDeps(config: ResolvedConfig, force?: boolean | undefined, asCommand?: boolean): Promise<DepOptimizationMetadata>;
2754
2755type SSRTarget = 'node' | 'webworker';
2756type SsrDepOptimizationOptions = DepOptimizationConfig;
2757interface SSROptions {
2758 noExternal?: string | RegExp | (string | RegExp)[] | true;
2759 external?: string[] | true;
2760 /**
2761 * Define the target for the ssr build. The browser field in package.json
2762 * is ignored for node but used if webworker is the target
2763 * @default 'node'
2764 */
2765 target?: SSRTarget;
2766 /**
2767 * Control over which dependencies are optimized during SSR and esbuild options
2768 * During build:
2769 * no external CJS dependencies are optimized by default
2770 * During dev:
2771 * explicit no external CJS dependencies are optimized by default
2772 * @experimental
2773 */
2774 optimizeDeps?: SsrDepOptimizationOptions;
2775 resolve?: {
2776 /**
2777 * Conditions that are used in the plugin pipeline. The default value is the root config's `resolve.conditions`.
2778 *
2779 * Use this to override the default ssr conditions for the ssr build.
2780 *
2781 * @default rootConfig.resolve.conditions
2782 */
2783 conditions?: string[];
2784 /**
2785 * Conditions that are used during ssr import (including `ssrLoadModule`) of externalized dependencies.
2786 *
2787 * @default []
2788 */
2789 externalConditions?: string[];
2790 };
2791}
2792interface ResolvedSSROptions extends SSROptions {
2793 target: SSRTarget;
2794 optimizeDeps: SsrDepOptimizationOptions;
2795}
2796
2797interface FsUtils {
2798 existsSync: (path: string) => boolean;
2799 isDirectory: (path: string) => boolean;
2800 tryResolveRealFile: (path: string, preserveSymlinks?: boolean) => string | undefined;
2801 tryResolveRealFileWithExtensions: (path: string, extensions: string[], preserveSymlinks?: boolean) => string | undefined;
2802 tryResolveRealFileOrType: (path: string, preserveSymlinks?: boolean) => {
2803 path?: string;
2804 type: 'directory' | 'file';
2805 } | undefined;
2806 initWatcher?: (watcher: FSWatcher) => void;
2807}
2808
2809interface ResolveOptions {
2810 /**
2811 * @default ['browser', 'module', 'jsnext:main', 'jsnext']
2812 */
2813 mainFields?: string[];
2814 conditions?: string[];
2815 /**
2816 * @default ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json']
2817 */
2818 extensions?: string[];
2819 dedupe?: string[];
2820 /**
2821 * @default false
2822 */
2823 preserveSymlinks?: boolean;
2824}
2825interface InternalResolveOptions extends Required<ResolveOptions> {
2826 root: string;
2827 isBuild: boolean;
2828 isProduction: boolean;
2829 ssrConfig?: SSROptions;
2830 packageCache?: PackageCache;
2831 fsUtils?: FsUtils;
2832 /**
2833 * src code mode also attempts the following:
2834 * - resolving /xxx as URLs
2835 * - resolving bare imports from optimized deps
2836 */
2837 asSrc?: boolean;
2838 tryIndex?: boolean;
2839 tryPrefix?: string;
2840 preferRelative?: boolean;
2841 isRequire?: boolean;
2842 isFromTsImporter?: boolean;
2843 tryEsmOnly?: boolean;
2844 scan?: boolean;
2845 ssrOptimizeCheck?: boolean;
2846 getDepsOptimizer?: (ssr: boolean) => DepsOptimizer | undefined;
2847 shouldExternalize?: (id: string, importer?: string) => boolean | undefined;
2848}
2849
2850// This file is autogenerated by build-prefixes.js. DO NOT EDIT!
2851
2852interface Targets {
2853 android?: number,
2854 chrome?: number,
2855 edge?: number,
2856 firefox?: number,
2857 ie?: number,
2858 ios_saf?: number,
2859 opera?: number,
2860 safari?: number,
2861 samsung?: number
2862}
2863
2864interface Drafts {
2865 /** Whether to enable @custom-media rules. */
2866 customMedia?: boolean
2867}
2868
2869interface NonStandard {
2870 /** Whether to enable the non-standard >>> and /deep/ selector combinators used by Angular and Vue. */
2871 deepSelectorCombinator?: boolean
2872}
2873
2874interface PseudoClasses {
2875 hover?: string,
2876 active?: string,
2877 focus?: string,
2878 focusVisible?: string,
2879 focusWithin?: string
2880}
2881
2882interface CSSModulesConfig {
2883 /** The pattern to use when renaming class names and other identifiers. Default is `[hash]_[local]`. */
2884 pattern?: string,
2885 /** Whether to rename dashed identifiers, e.g. custom properties. */
2886 dashedIdents?: boolean
2887}
2888
2889/**
2890 * Options are spread, so you can also use options that are not typed here like
2891 * visitor (not exposed because it would impact too much the bundle size)
2892 */
2893type LightningCSSOptions = {
2894 targets?: Targets
2895 include?: number
2896 exclude?: number
2897 drafts?: Drafts
2898 nonStandard?: NonStandard
2899 pseudoClasses?: PseudoClasses
2900 unusedSymbols?: string[]
2901 cssModules?: CSSModulesConfig
2902 errorRecovery?: boolean
2903}
2904
2905interface CSSOptions {
2906 /**
2907 * Using lightningcss is an experimental option to handle CSS modules,
2908 * assets and imports via Lightning CSS. It requires to install it as a
2909 * peer dependency. This is incompatible with the use of preprocessors.
2910 *
2911 * @default 'postcss'
2912 * @experimental
2913 */
2914 transformer?: 'postcss' | 'lightningcss';
2915 /**
2916 * https://github.com/css-modules/postcss-modules
2917 */
2918 modules?: CSSModulesOptions | false;
2919 /**
2920 * Options for preprocessors.
2921 *
2922 * In addition to options specific to each processors, Vite supports `additionalData` option.
2923 * The `additionalData` option can be used to inject extra code for each style content.
2924 */
2925 preprocessorOptions?: Record<string, any>;
2926 /**
2927 * If this option is set, preprocessors will run in workers when possible.
2928 * `true` means the number of CPUs minus 1.
2929 *
2930 * @default 0
2931 * @experimental
2932 */
2933 preprocessorMaxWorkers?: number | true;
2934 postcss?: string | (PostCSS.ProcessOptions & {
2935 plugins?: PostCSS.AcceptedPlugin[];
2936 });
2937 /**
2938 * Enables css sourcemaps during dev
2939 * @default false
2940 * @experimental
2941 */
2942 devSourcemap?: boolean;
2943 /**
2944 * @experimental
2945 */
2946 lightningcss?: LightningCSSOptions;
2947}
2948interface CSSModulesOptions {
2949 getJSON?: (cssFileName: string, json: Record<string, string>, outputFileName: string) => void;
2950 scopeBehaviour?: 'global' | 'local';
2951 globalModulePaths?: RegExp[];
2952 exportGlobals?: boolean;
2953 generateScopedName?: string | ((name: string, filename: string, css: string) => string);
2954 hashPrefix?: string;
2955 /**
2956 * default: undefined
2957 */
2958 localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly' | ((originalClassName: string, generatedClassName: string, inputFile: string) => string);
2959}
2960type ResolvedCSSOptions = Omit<CSSOptions, 'lightningcss'> & {
2961 lightningcss?: LightningCSSOptions & {
2962 targets: LightningCSSOptions['targets'];
2963 };
2964};
2965interface PreprocessCSSResult {
2966 code: string;
2967 map?: SourceMapInput;
2968 modules?: Record<string, string>;
2969 deps?: Set<string>;
2970}
2971/**
2972 * @experimental
2973 */
2974declare function preprocessCSS(code: string, filename: string, config: ResolvedConfig): Promise<PreprocessCSSResult>;
2975declare function formatPostcssSourceMap(rawMap: ExistingRawSourceMap, file: string): Promise<ExistingRawSourceMap>;
2976
2977interface HtmlTagDescriptor {
2978 tag: string;
2979 attrs?: Record<string, string | boolean | undefined>;
2980 children?: string | HtmlTagDescriptor[];
2981 /**
2982 * default: 'head-prepend'
2983 */
2984 injectTo?: 'head' | 'body' | 'head-prepend' | 'body-prepend';
2985}
2986type IndexHtmlTransformResult = string | HtmlTagDescriptor[] | {
2987 html: string;
2988 tags: HtmlTagDescriptor[];
2989};
2990interface IndexHtmlTransformContext {
2991 /**
2992 * public path when served
2993 */
2994 path: string;
2995 /**
2996 * filename on disk
2997 */
2998 filename: string;
2999 server?: ViteDevServer;
3000 bundle?: OutputBundle;
3001 chunk?: OutputChunk;
3002 originalUrl?: string;
3003}
3004type IndexHtmlTransformHook = (this: void, html: string, ctx: IndexHtmlTransformContext) => IndexHtmlTransformResult | void | Promise<IndexHtmlTransformResult | void>;
3005type IndexHtmlTransform = IndexHtmlTransformHook | {
3006 order?: 'pre' | 'post' | null;
3007 /**
3008 * @deprecated renamed to `order`
3009 */
3010 enforce?: 'pre' | 'post';
3011 /**
3012 * @deprecated renamed to `handler`
3013 */
3014 transform: IndexHtmlTransformHook;
3015} | {
3016 order?: 'pre' | 'post' | null;
3017 /**
3018 * @deprecated renamed to `order`
3019 */
3020 enforce?: 'pre' | 'post';
3021 handler: IndexHtmlTransformHook;
3022};
3023
3024/**
3025 * Vite plugins extends the Rollup plugin interface with a few extra
3026 * vite-specific options. A valid vite plugin is also a valid Rollup plugin.
3027 * On the contrary, a Rollup plugin may or may NOT be a valid vite universal
3028 * plugin, since some Rollup features do not make sense in an unbundled
3029 * dev server context. That said, as long as a rollup plugin doesn't have strong
3030 * coupling between its bundle phase and output phase hooks then it should
3031 * just work (that means, most of them).
3032 *
3033 * By default, the plugins are run during both serve and build. When a plugin
3034 * is applied during serve, it will only run **non output plugin hooks** (see
3035 * rollup type definition of {@link rollup#PluginHooks}). You can think of the
3036 * dev server as only running `const bundle = rollup.rollup()` but never calling
3037 * `bundle.generate()`.
3038 *
3039 * A plugin that expects to have different behavior depending on serve/build can
3040 * export a factory function that receives the command being run via options.
3041 *
3042 * If a plugin should be applied only for server or build, a function format
3043 * config file can be used to conditional determine the plugins to use.
3044 */
3045interface Plugin<A = any> extends rollup.Plugin<A> {
3046 /**
3047 * Enforce plugin invocation tier similar to webpack loaders. Hooks ordering
3048 * is still subject to the `order` property in the hook object.
3049 *
3050 * Plugin invocation order:
3051 * - alias resolution
3052 * - `enforce: 'pre'` plugins
3053 * - vite core plugins
3054 * - normal plugins
3055 * - vite build plugins
3056 * - `enforce: 'post'` plugins
3057 * - vite build post plugins
3058 */
3059 enforce?: 'pre' | 'post';
3060 /**
3061 * Apply the plugin only for serve or build, or on certain conditions.
3062 */
3063 apply?: 'serve' | 'build' | ((this: void, config: UserConfig, env: ConfigEnv) => boolean);
3064 /**
3065 * Modify vite config before it's resolved. The hook can either mutate the
3066 * passed-in config directly, or return a partial config object that will be
3067 * deeply merged into existing config.
3068 *
3069 * Note: User plugins are resolved before running this hook so injecting other
3070 * plugins inside the `config` hook will have no effect.
3071 */
3072 config?: ObjectHook<(this: void, config: UserConfig, env: ConfigEnv) => Omit<UserConfig, 'plugins'> | null | void | Promise<Omit<UserConfig, 'plugins'> | null | void>>;
3073 /**
3074 * Use this hook to read and store the final resolved vite config.
3075 */
3076 configResolved?: ObjectHook<(this: void, config: ResolvedConfig) => void | Promise<void>>;
3077 /**
3078 * Configure the vite server. The hook receives the {@link ViteDevServer}
3079 * instance. This can also be used to store a reference to the server
3080 * for use in other hooks.
3081 *
3082 * The hooks will be called before internal middlewares are applied. A hook
3083 * can return a post hook that will be called after internal middlewares
3084 * are applied. Hook can be async functions and will be called in series.
3085 */
3086 configureServer?: ObjectHook<ServerHook>;
3087 /**
3088 * Configure the preview server. The hook receives the {@link PreviewServer}
3089 * instance. This can also be used to store a reference to the server
3090 * for use in other hooks.
3091 *
3092 * The hooks are called before other middlewares are applied. A hook can
3093 * return a post hook that will be called after other middlewares are
3094 * applied. Hooks can be async functions and will be called in series.
3095 */
3096 configurePreviewServer?: ObjectHook<PreviewServerHook>;
3097 /**
3098 * Transform index.html.
3099 * The hook receives the following arguments:
3100 *
3101 * - html: string
3102 * - ctx?: vite.ServerContext (only present during serve)
3103 * - bundle?: rollup.OutputBundle (only present during build)
3104 *
3105 * It can either return a transformed string, or a list of html tag
3106 * descriptors that will be injected into the `<head>` or `<body>`.
3107 *
3108 * By default the transform is applied **after** vite's internal html
3109 * transform. If you need to apply the transform before vite, use an object:
3110 * `{ order: 'pre', handler: hook }`
3111 */
3112 transformIndexHtml?: IndexHtmlTransform;
3113 /**
3114 * Perform custom handling of HMR updates.
3115 * The handler receives a context containing changed filename, timestamp, a
3116 * list of modules affected by the file change, and the dev server instance.
3117 *
3118 * - The hook can return a filtered list of modules to narrow down the update.
3119 * e.g. for a Vue SFC, we can narrow down the part to update by comparing
3120 * the descriptors.
3121 *
3122 * - The hook can also return an empty array and then perform custom updates
3123 * by sending a custom hmr payload via server.ws.send().
3124 *
3125 * - If the hook doesn't return a value, the hmr update will be performed as
3126 * normal.
3127 */
3128 handleHotUpdate?: ObjectHook<(this: void, ctx: HmrContext) => Array<ModuleNode> | void | Promise<Array<ModuleNode> | void>>;
3129 /**
3130 * extend hooks with ssr flag
3131 */
3132 resolveId?: ObjectHook<(this: PluginContext, source: string, importer: string | undefined, options: {
3133 attributes: Record<string, string>;
3134 custom?: CustomPluginOptions;
3135 ssr?: boolean;
3136 isEntry: boolean;
3137 }) => Promise<ResolveIdResult> | ResolveIdResult>;
3138 load?: ObjectHook<(this: PluginContext, id: string, options?: {
3139 ssr?: boolean;
3140 }) => Promise<LoadResult> | LoadResult>;
3141 transform?: ObjectHook<(this: TransformPluginContext, code: string, id: string, options?: {
3142 ssr?: boolean;
3143 }) => Promise<rollup.TransformResult> | rollup.TransformResult>;
3144}
3145type HookHandler<T> = T extends ObjectHook<infer H> ? H : T;
3146type PluginWithRequiredHook<K extends keyof Plugin> = Plugin & {
3147 [P in K]: NonNullable<Plugin[P]>;
3148};
3149
3150interface JsonOptions {
3151 /**
3152 * Generate a named export for every property of the JSON object
3153 * @default true
3154 */
3155 namedExports?: boolean;
3156 /**
3157 * Generate performant output as JSON.parse("stringified").
3158 * Enabling this will disable namedExports.
3159 * @default false
3160 */
3161 stringify?: boolean;
3162}
3163
3164interface ConfigEnv {
3165 /**
3166 * 'serve': during dev (`vite` command)
3167 * 'build': when building for production (`vite build` command)
3168 */
3169 command: 'build' | 'serve';
3170 mode: string;
3171 isSsrBuild?: boolean;
3172 isPreview?: boolean;
3173}
3174/**
3175 * spa: include SPA fallback middleware and configure sirv with `single: true` in preview
3176 *
3177 * mpa: only include non-SPA HTML middlewares
3178 *
3179 * custom: don't include HTML middlewares
3180 */
3181type AppType = 'spa' | 'mpa' | 'custom';
3182type UserConfigFnObject = (env: ConfigEnv) => UserConfig;
3183type UserConfigFnPromise = (env: ConfigEnv) => Promise<UserConfig>;
3184type UserConfigFn = (env: ConfigEnv) => UserConfig | Promise<UserConfig>;
3185type UserConfigExport = UserConfig | Promise<UserConfig> | UserConfigFnObject | UserConfigFnPromise | UserConfigFn;
3186/**
3187 * Type helper to make it easier to use vite.config.ts
3188 * accepts a direct {@link UserConfig} object, or a function that returns it.
3189 * The function receives a {@link ConfigEnv} object.
3190 */
3191declare function defineConfig(config: UserConfig): UserConfig;
3192declare function defineConfig(config: Promise<UserConfig>): Promise<UserConfig>;
3193declare function defineConfig(config: UserConfigFnObject): UserConfigFnObject;
3194declare function defineConfig(config: UserConfigExport): UserConfigExport;
3195type PluginOption = Plugin | false | null | undefined | PluginOption[] | Promise<Plugin | false | null | undefined | PluginOption[]>;
3196interface UserConfig {
3197 /**
3198 * Project root directory. Can be an absolute path, or a path relative from
3199 * the location of the config file itself.
3200 * @default process.cwd()
3201 */
3202 root?: string;
3203 /**
3204 * Base public path when served in development or production.
3205 * @default '/'
3206 */
3207 base?: string;
3208 /**
3209 * Directory to serve as plain static assets. Files in this directory are
3210 * served and copied to build dist dir as-is without transform. The value
3211 * can be either an absolute file system path or a path relative to project root.
3212 *
3213 * Set to `false` or an empty string to disable copied static assets to build dist dir.
3214 * @default 'public'
3215 */
3216 publicDir?: string | false;
3217 /**
3218 * Directory to save cache files. Files in this directory are pre-bundled
3219 * deps or some other cache files that generated by vite, which can improve
3220 * the performance. You can use `--force` flag or manually delete the directory
3221 * to regenerate the cache files. The value can be either an absolute file
3222 * system path or a path relative to project root.
3223 * Default to `.vite` when no `package.json` is detected.
3224 * @default 'node_modules/.vite'
3225 */
3226 cacheDir?: string;
3227 /**
3228 * Explicitly set a mode to run in. This will override the default mode for
3229 * each command, and can be overridden by the command line --mode option.
3230 */
3231 mode?: string;
3232 /**
3233 * Define global variable replacements.
3234 * Entries will be defined on `window` during dev and replaced during build.
3235 */
3236 define?: Record<string, any>;
3237 /**
3238 * Array of vite plugins to use.
3239 */
3240 plugins?: PluginOption[];
3241 /**
3242 * Configure resolver
3243 */
3244 resolve?: ResolveOptions & {
3245 alias?: AliasOptions;
3246 };
3247 /**
3248 * HTML related options
3249 */
3250 html?: HTMLOptions;
3251 /**
3252 * CSS related options (preprocessors and CSS modules)
3253 */
3254 css?: CSSOptions;
3255 /**
3256 * JSON loading options
3257 */
3258 json?: JsonOptions;
3259 /**
3260 * Transform options to pass to esbuild.
3261 * Or set to `false` to disable esbuild.
3262 */
3263 esbuild?: ESBuildOptions | false;
3264 /**
3265 * Specify additional picomatch patterns to be treated as static assets.
3266 */
3267 assetsInclude?: string | RegExp | (string | RegExp)[];
3268 /**
3269 * Server specific options, e.g. host, port, https...
3270 */
3271 server?: ServerOptions;
3272 /**
3273 * Build specific options
3274 */
3275 build?: BuildOptions;
3276 /**
3277 * Preview specific options, e.g. host, port, https...
3278 */
3279 preview?: PreviewOptions;
3280 /**
3281 * Dep optimization options
3282 */
3283 optimizeDeps?: DepOptimizationOptions;
3284 /**
3285 * SSR specific options
3286 */
3287 ssr?: SSROptions;
3288 /**
3289 * Experimental features
3290 *
3291 * Features under this field could change in the future and might NOT follow semver.
3292 * Please be careful and always pin Vite's version when using them.
3293 * @experimental
3294 */
3295 experimental?: ExperimentalOptions;
3296 /**
3297 * Legacy options
3298 *
3299 * Features under this field only follow semver for patches, they could be removed in a
3300 * future minor version. Please always pin Vite's version to a minor when using them.
3301 */
3302 legacy?: LegacyOptions;
3303 /**
3304 * Log level.
3305 * @default 'info'
3306 */
3307 logLevel?: LogLevel;
3308 /**
3309 * Custom logger.
3310 */
3311 customLogger?: Logger;
3312 /**
3313 * @default true
3314 */
3315 clearScreen?: boolean;
3316 /**
3317 * Environment files directory. Can be an absolute path, or a path relative from
3318 * root.
3319 * @default root
3320 */
3321 envDir?: string;
3322 /**
3323 * Env variables starts with `envPrefix` will be exposed to your client source code via import.meta.env.
3324 * @default 'VITE_'
3325 */
3326 envPrefix?: string | string[];
3327 /**
3328 * Worker bundle options
3329 */
3330 worker?: {
3331 /**
3332 * Output format for worker bundle
3333 * @default 'iife'
3334 */
3335 format?: 'es' | 'iife';
3336 /**
3337 * Vite plugins that apply to worker bundle. The plugins returned by this function
3338 * should be new instances every time it is called, because they are used for each
3339 * rollup worker bundling process.
3340 */
3341 plugins?: () => PluginOption[];
3342 /**
3343 * Rollup options to build worker bundle
3344 */
3345 rollupOptions?: Omit<RollupOptions, 'plugins' | 'input' | 'onwarn' | 'preserveEntrySignatures'>;
3346 };
3347 /**
3348 * Whether your application is a Single Page Application (SPA),
3349 * a Multi-Page Application (MPA), or Custom Application (SSR
3350 * and frameworks with custom HTML handling)
3351 * @default 'spa'
3352 */
3353 appType?: AppType;
3354}
3355interface HTMLOptions {
3356 /**
3357 * A nonce value placeholder that will be used when generating script/style tags.
3358 *
3359 * Make sure that this placeholder will be replaced with a unique value for each request by the server.
3360 */
3361 cspNonce?: string;
3362}
3363interface ExperimentalOptions {
3364 /**
3365 * Append fake `&lang.(ext)` when queries are specified, to preserve the file extension for following plugins to process.
3366 *
3367 * @experimental
3368 * @default false
3369 */
3370 importGlobRestoreExtension?: boolean;
3371 /**
3372 * Allow finegrain control over assets and public files paths
3373 *
3374 * @experimental
3375 */
3376 renderBuiltUrl?: RenderBuiltAssetUrl;
3377 /**
3378 * Enables support of HMR partial accept via `import.meta.hot.acceptExports`.
3379 *
3380 * @experimental
3381 * @default false
3382 */
3383 hmrPartialAccept?: boolean;
3384 /**
3385 * Skips SSR transform to make it easier to use Vite with Node ESM loaders.
3386 * @warning Enabling this will break normal operation of Vite's SSR in development mode.
3387 *
3388 * @experimental
3389 * @default false
3390 */
3391 skipSsrTransform?: boolean;
3392}
3393interface LegacyOptions {
3394 /**
3395 * In Vite 4, SSR-externalized modules (modules not bundled and loaded by Node.js at runtime)
3396 * are implicitly proxied in dev to automatically handle `default` and `__esModule` access.
3397 * However, this does not correctly reflect how it works in the Node.js runtime, causing
3398 * inconsistencies between dev and prod.
3399 *
3400 * In Vite 5, the proxy is removed so dev and prod are consistent, but if you still require
3401 * the old behaviour, you can enable this option. If so, please leave your feedback at
3402 * https://github.com/vitejs/vite/discussions/14697.
3403 */
3404 proxySsrExternalModules?: boolean;
3405}
3406interface ResolvedWorkerOptions {
3407 format: 'es' | 'iife';
3408 plugins: (bundleChain: string[]) => Promise<Plugin[]>;
3409 rollupOptions: RollupOptions;
3410}
3411interface InlineConfig extends UserConfig {
3412 configFile?: string | false;
3413 envFile?: false;
3414}
3415type ResolvedConfig = Readonly<Omit<UserConfig, 'plugins' | 'css' | 'assetsInclude' | 'optimizeDeps' | 'worker' | 'build'> & {
3416 configFile: string | undefined;
3417 configFileDependencies: string[];
3418 inlineConfig: InlineConfig;
3419 root: string;
3420 base: string;
3421 publicDir: string;
3422 cacheDir: string;
3423 command: 'build' | 'serve';
3424 mode: string;
3425 isWorker: boolean;
3426 isProduction: boolean;
3427 envDir: string;
3428 env: Record<string, any>;
3429 resolve: Required<ResolveOptions> & {
3430 alias: Alias[];
3431 };
3432 plugins: readonly Plugin[];
3433 css: ResolvedCSSOptions;
3434 esbuild: ESBuildOptions | false;
3435 server: ResolvedServerOptions;
3436 build: ResolvedBuildOptions;
3437 preview: ResolvedPreviewOptions;
3438 ssr: ResolvedSSROptions;
3439 assetsInclude: (file: string) => boolean;
3440 logger: Logger;
3441 createResolver: (options?: Partial<InternalResolveOptions>) => ResolveFn;
3442 optimizeDeps: DepOptimizationOptions;
3443 worker: ResolvedWorkerOptions;
3444 appType: AppType;
3445 experimental: ExperimentalOptions;
3446} & PluginHookUtils>;
3447interface PluginHookUtils {
3448 getSortedPlugins: <K extends keyof Plugin>(hookName: K) => PluginWithRequiredHook<K>[];
3449 getSortedPluginHooks: <K extends keyof Plugin>(hookName: K) => NonNullable<HookHandler<Plugin[K]>>[];
3450}
3451type ResolveFn = (id: string, importer?: string, aliasOnly?: boolean, ssr?: boolean) => Promise<string | undefined>;
3452declare function resolveConfig(inlineConfig: InlineConfig, command: 'build' | 'serve', defaultMode?: string, defaultNodeEnv?: string, isPreview?: boolean): Promise<ResolvedConfig>;
3453declare function sortUserPlugins(plugins: (Plugin | Plugin[])[] | undefined): [Plugin[], Plugin[], Plugin[]];
3454declare function loadConfigFromFile(configEnv: ConfigEnv, configFile?: string, configRoot?: string, logLevel?: LogLevel, customLogger?: Logger): Promise<{
3455 path: string;
3456 config: UserConfig;
3457 dependencies: string[];
3458} | null>;
3459
3460declare function buildErrorMessage(err: RollupError, args?: string[], includeStack?: boolean): string;
3461
3462interface FetchModuleOptions {
3463 inlineSourceMap?: boolean;
3464 processSourceMap?<T extends NonNullable<TransformResult['map']>>(map: T): T;
3465}
3466/**
3467 * Fetch module information for Vite runtime.
3468 * @experimental
3469 */
3470declare function fetchModule(server: ViteDevServer, url: string, importer?: string, options?: FetchModuleOptions): Promise<FetchResult>;
3471
3472declare const VERSION: string;
3473
3474declare const isCSSRequest: (request: string) => boolean;
3475/**
3476 * @deprecated use build.rollupOptions.output.manualChunks or framework specific configuration
3477 */
3478declare class SplitVendorChunkCache {
3479 cache: Map<string, boolean>;
3480 constructor();
3481 reset(): void;
3482}
3483/**
3484 * @deprecated use build.rollupOptions.output.manualChunks or framework specific configuration
3485 */
3486declare function splitVendorChunk(options?: {
3487 cache?: SplitVendorChunkCache;
3488}): GetManualChunk;
3489/**
3490 * @deprecated use build.rollupOptions.output.manualChunks or framework specific configuration
3491 */
3492declare function splitVendorChunkPlugin(): Plugin;
3493
3494/**
3495 * Inlined to keep `@rollup/pluginutils` in devDependencies
3496 */
3497type FilterPattern = ReadonlyArray<string | RegExp> | string | RegExp | null;
3498declare const createFilter: (include?: FilterPattern, exclude?: FilterPattern, options?: {
3499 resolve?: string | false | null;
3500}) => (id: string | unknown) => boolean;
3501declare const rollupVersion: string;
3502declare function normalizePath(id: string): string;
3503declare function mergeConfig<D extends Record<string, any>, O extends Record<string, any>>(defaults: D extends Function ? never : D, overrides: O extends Function ? never : O, isRoot?: boolean): Record<string, any>;
3504declare function mergeAlias(a?: AliasOptions, b?: AliasOptions): AliasOptions | undefined;
3505
3506interface SendOptions {
3507 etag?: string;
3508 cacheControl?: string;
3509 headers?: OutgoingHttpHeaders;
3510 map?: SourceMap | {
3511 mappings: '';
3512 } | null;
3513}
3514declare function send(req: IncomingMessage, res: ServerResponse, content: string | Buffer, type: string, options: SendOptions): void;
3515
3516/**
3517 * Search up for the nearest workspace root
3518 */
3519declare function searchForWorkspaceRoot(current: string, root?: string): string;
3520
3521/**
3522 * Check if the url is allowed to be served, via the `server.fs` config.
3523 */
3524declare function isFileServingAllowed(url: string, server: ViteDevServer): boolean;
3525
3526declare function loadEnv(mode: string, envDir: string, prefixes?: string | string[]): Record<string, string>;
3527declare function resolveEnvPrefix({ envPrefix, }: UserConfig): string[];
3528
3529type Manifest = Record<string, ManifestChunk>;
3530interface ManifestChunk {
3531 src?: string;
3532 file: string;
3533 css?: string[];
3534 assets?: string[];
3535 isEntry?: boolean;
3536 name?: string;
3537 isDynamicEntry?: boolean;
3538 imports?: string[];
3539 dynamicImports?: string[];
3540}
3541
3542/**
3543 * @experimental
3544 */
3545interface MainThreadRuntimeOptions extends Omit<ViteRuntimeOptions, 'root' | 'fetchModule' | 'hmr'> {
3546 /**
3547 * Disable HMR or configure HMR logger.
3548 */
3549 hmr?: false | {
3550 logger?: false | HMRLogger;
3551 };
3552 /**
3553 * Provide a custom module runner. This controls how the code is executed.
3554 */
3555 runner?: ViteModuleRunner;
3556}
3557/**
3558 * Create an instance of the Vite SSR runtime that support HMR.
3559 * @experimental
3560 */
3561declare function createViteRuntime(server: ViteDevServer, options?: MainThreadRuntimeOptions): Promise<ViteRuntime>;
3562
3563/**
3564 * The connector class to establish HMR communication between the server and the Vite runtime.
3565 * @experimental
3566 */
3567declare class ServerHMRConnector implements HMRRuntimeConnection {
3568 private handlers;
3569 private hmrChannel;
3570 private hmrClient;
3571 private connected;
3572 constructor(server: ViteDevServer);
3573 isReady(): boolean;
3574 send(message: string): void;
3575 onUpdate(handler: (payload: HMRPayload) => void): void;
3576}
3577
3578export { type Alias, type AliasOptions, type AnymatchFn, type AnymatchPattern, type AppType, type AwaitWriteFinishOptions, type BindCLIShortcutsOptions, type BuildOptions, type CLIShortcut, type CSSModulesOptions, type CSSOptions, type CommonServerOptions, type ConfigEnv, Connect, type CorsOptions, type CorsOrigin, type DepOptimizationConfig, type DepOptimizationMetadata, type DepOptimizationOptions, type ESBuildOptions, type ESBuildTransformResult, type ExperimentalOptions, type ExportsData, FSWatcher, type FetchModuleOptions, type FileSystemServeOptions, type FilterPattern, type HMRBroadcaster, type HMRBroadcasterClient, type HMRChannel, type HTMLOptions, type HmrContext, type HmrOptions, type HookHandler, type HtmlTagDescriptor, HttpProxy, type HttpServer, type IndexHtmlTransform, type IndexHtmlTransformContext, type IndexHtmlTransformHook, type IndexHtmlTransformResult, type InlineConfig, type InternalResolveOptions, type JsonOptions, type LegacyOptions, type LibraryFormats, type LibraryOptions, type LightningCSSOptions, type LogErrorOptions, type LogLevel, type LogOptions, type LogType, type Logger, type LoggerOptions, type MainThreadRuntimeOptions, type Manifest, type ManifestChunk, type MapToFunction, type AnymatchMatcher as Matcher, ModuleGraph, ModuleNode, type ModulePreloadOptions, type OptimizedDepInfo, type Plugin, PluginContainer, type PluginHookUtils, type PluginOption, type PreprocessCSSResult, type PreviewOptions, type PreviewServer, type PreviewServerHook, type ProxyOptions, type RenderBuiltAssetUrl, type ResolveFn, type ResolveModulePreloadDependenciesFn, type ResolveOptions, type ResolvedBuildOptions, type ResolvedCSSOptions, type ResolvedConfig, type ResolvedModulePreloadOptions, type ResolvedPreviewOptions, type ResolvedSSROptions, type ResolvedServerOptions, type ResolvedServerUrls, type ResolvedUrl, type ResolvedWorkerOptions, type ResolverFunction, type ResolverObject, type RollupCommonJSOptions, type RollupDynamicImportVarsOptions, type SSROptions, type SSRTarget, type SendOptions, type ServerHMRChannel, ServerHMRConnector, type ServerHook, type ServerOptions, SplitVendorChunkCache, type SsrDepOptimizationOptions, Terser, type TerserOptions, type TransformOptions, type TransformResult, type UserConfig, type UserConfigExport, type UserConfigFn, type UserConfigFnObject, type UserConfigFnPromise, type ViteDevServer, type WatchOptions, WebSocket, WebSocketAlias, type WebSocketClient, type WebSocketCustomListener, WebSocketServer, build, buildErrorMessage, createFilter, createLogger, createServer, createViteRuntime, defineConfig, fetchModule, formatPostcssSourceMap, isCSSRequest, isFileServingAllowed, loadConfigFromFile, loadEnv, mergeAlias, mergeConfig, normalizePath, optimizeDeps, preprocessCSS, preview, resolveConfig, resolveEnvPrefix, rollupVersion, searchForWorkspaceRoot, send, sortUserPlugins, splitVendorChunk, splitVendorChunkPlugin, transformWithEsbuild, VERSION as version };
Note: See TracBrowser for help on using the repository browser.