source: node_modules/vite/dist/node/index.d.ts@ 57e58a3

Last change on this file since 57e58a3 was 57e58a3, checked in by ste08 <sjovanoska@…>, 4 months ago

Initial commit

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