UNPKG

149 kBTypeScriptView Raw
1/// <reference types="node" />
2import { PluginHooks, RollupError, SourceMap, ModuleInfo, PartialResolvedId, RollupOptions, WatcherOptions, InputOption, ModuleFormat, RollupOutput, RollupWatcher, MinimalPluginContext, InputOptions, CustomPluginOptions, LoadResult, SourceDescription, SourceMapInput, ExistingRawSourceMap, OutputBundle, OutputChunk, ObjectHook, ResolveIdResult, 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';
32export { GeneralImportGlobOptions, ImportGlobFunction, ImportGlobOptions, KnownAsTypeMap } from '../../types/importGlob.js';
33export { ChunkMetadata } from '../../types/metadata.js';
34
35interface Alias {
36 find: string | RegExp
37 replacement: string
38 /**
39 * Instructs the plugin to use an alternative resolving algorithm,
40 * rather than the Rollup's resolver.
41 * @default null
42 */
43 customResolver?: ResolverFunction | ResolverObject | null
44}
45
46type MapToFunction<T> = T extends Function ? T : never
47
48type ResolverFunction = MapToFunction<PluginHooks['resolveId']>
49
50interface ResolverObject {
51 buildStart?: PluginHooks['buildStart']
52 resolveId: ResolverFunction
53}
54
55/**
56 * Specifies an `Object`, or an `Array` of `Object`,
57 * which defines aliases used to replace values in `import` or `require` statements.
58 * With either format, the order of the entries is important,
59 * in that the first defined rules are applied first.
60 *
61 * This is passed to \@rollup/plugin-alias as the "entries" field
62 * https://github.com/rollup/plugins/tree/master/packages/alias#entries
63 */
64type AliasOptions = readonly Alias[] | { [find: string]: string }
65
66type AnymatchFn = (testString: string) => boolean
67type AnymatchPattern = string | RegExp | AnymatchFn
68type AnymatchMatcher = AnymatchPattern | AnymatchPattern[]
69
70// Inlined to avoid extra dependency (chokidar is bundled in the published build)
71
72declare class FSWatcher extends EventEmitter implements fs.FSWatcher {
73 options: WatchOptions
74
75 /**
76 * Constructs a new FSWatcher instance with optional WatchOptions parameter.
77 */
78 constructor(options?: WatchOptions)
79
80 /**
81 * When called, requests that the Node.js event loop not exit so long as the fs.FSWatcher is active.
82 * Calling watcher.ref() multiple times will have no effect.
83 */
84 ref(): this
85
86 /**
87 * When called, the active fs.FSWatcher object will not require the Node.js event loop to remain active.
88 * If there is no other activity keeping the event loop running, the process may exit before the fs.FSWatcher object's callback is invoked.
89 * Calling watcher.unref() multiple times will have no effect.
90 */
91 unref(): this
92
93 /**
94 * Add files, directories, or glob patterns for tracking. Takes an array of strings or just one
95 * string.
96 */
97 add(paths: string | ReadonlyArray<string>): this
98
99 /**
100 * Stop watching files, directories, or glob patterns. Takes an array of strings or just one
101 * string.
102 */
103 unwatch(paths: string | ReadonlyArray<string>): this
104
105 /**
106 * Returns an object representing all the paths on the file system being watched by this
107 * `FSWatcher` instance. The object's keys are all the directories (using absolute paths unless
108 * the `cwd` option was used), and the values are arrays of the names of the items contained in
109 * each directory.
110 */
111 getWatched(): {
112 [directory: string]: string[]
113 }
114
115 /**
116 * Removes all listeners from watched files.
117 */
118 close(): Promise<void>
119
120 on(
121 event: 'add' | 'addDir' | 'change',
122 listener: (path: string, stats?: fs.Stats) => void,
123 ): this
124
125 on(
126 event: 'all',
127 listener: (
128 eventName: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir',
129 path: string,
130 stats?: fs.Stats,
131 ) => void,
132 ): this
133
134 /**
135 * Error occurred
136 */
137 on(event: 'error', listener: (error: Error) => void): this
138
139 /**
140 * Exposes the native Node `fs.FSWatcher events`
141 */
142 on(
143 event: 'raw',
144 listener: (eventName: string, path: string, details: any) => void,
145 ): this
146
147 /**
148 * Fires when the initial scan is complete
149 */
150 on(event: 'ready', listener: () => void): this
151
152 on(event: 'unlink' | 'unlinkDir', listener: (path: string) => void): this
153
154 on(event: string, listener: (...args: any[]) => void): this
155}
156
157interface WatchOptions {
158 /**
159 * Indicates whether the process should continue to run as long as files are being watched. If
160 * set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`,
161 * even if the process continues to run.
162 */
163 persistent?: boolean
164
165 /**
166 * ([anymatch](https://github.com/micromatch/anymatch)-compatible definition) Defines files/paths to
167 * be ignored. The whole relative or absolute path is tested, not just filename. If a function
168 * with two arguments is provided, it gets called twice per path - once with a single argument
169 * (the path), second time with two arguments (the path and the
170 * [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path).
171 */
172 ignored?: AnymatchMatcher
173
174 /**
175 * If set to `false` then `add`/`addDir` events are also emitted for matching paths while
176 * instantiating the watching as chokidar discovers these file paths (before the `ready` event).
177 */
178 ignoreInitial?: boolean
179
180 /**
181 * When `false`, only the symlinks themselves will be watched for changes instead of following
182 * the link references and bubbling events through the link's path.
183 */
184 followSymlinks?: boolean
185
186 /**
187 * The base directory from which watch `paths` are to be derived. Paths emitted with events will
188 * be relative to this.
189 */
190 cwd?: string
191
192 /**
193 * If set to true then the strings passed to .watch() and .add() are treated as literal path
194 * names, even if they look like globs.
195 *
196 * @default false
197 */
198 disableGlobbing?: boolean
199
200 /**
201 * Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU
202 * utilization, consider setting this to `false`. It is typically necessary to **set this to
203 * `true` to successfully watch files over a network**, and it may be necessary to successfully
204 * watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides
205 * the `useFsEvents` default.
206 */
207 usePolling?: boolean
208
209 /**
210 * Whether to use the `fsevents` watching interface if available. When set to `true` explicitly
211 * and `fsevents` is available this supersedes the `usePolling` setting. When set to `false` on
212 * OS X, `usePolling: true` becomes the default.
213 */
214 useFsEvents?: boolean
215
216 /**
217 * If relying upon the [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object that
218 * may get passed with `add`, `addDir`, and `change` events, set this to `true` to ensure it is
219 * provided even in cases where it wasn't already available from the underlying watch events.
220 */
221 alwaysStat?: boolean
222
223 /**
224 * If set, limits how many levels of subdirectories will be traversed.
225 */
226 depth?: number
227
228 /**
229 * Interval of file system polling.
230 */
231 interval?: number
232
233 /**
234 * Interval of file system polling for binary files. ([see list of binary extensions](https://gi
235 * thub.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))
236 */
237 binaryInterval?: number
238
239 /**
240 * Indicates whether to watch files that don't have read permissions if possible. If watching
241 * fails due to `EPERM` or `EACCES` with this set to `true`, the errors will be suppressed
242 * silently.
243 */
244 ignorePermissionErrors?: boolean
245
246 /**
247 * `true` if `useFsEvents` and `usePolling` are `false`. Automatically filters out artifacts
248 * that occur when using editors that use "atomic writes" instead of writing directly to the
249 * source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a `change`
250 * event rather than `unlink` then `add`. If the default of 100 ms does not work well for you,
251 * you can override it by setting `atomic` to a custom value, in milliseconds.
252 */
253 atomic?: boolean | number
254
255 /**
256 * can be set to an object in order to adjust timing params:
257 */
258 awaitWriteFinish?: AwaitWriteFinishOptions | boolean
259}
260
261interface AwaitWriteFinishOptions {
262 /**
263 * Amount of time in milliseconds for a file size to remain constant before emitting its event.
264 */
265 stabilityThreshold?: number
266
267 /**
268 * File size polling interval.
269 */
270 pollInterval?: number
271}
272
273// Inlined to avoid extra dependency
274// MIT Licensed https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/LICENSE
275
276declare namespace Connect {
277 export type ServerHandle = HandleFunction | http.Server
278
279 export class IncomingMessage extends http.IncomingMessage {
280 originalUrl?: http.IncomingMessage['url'] | undefined
281 }
282
283 export type NextFunction = (err?: any) => void
284
285 export type SimpleHandleFunction = (
286 req: IncomingMessage,
287 res: http.ServerResponse,
288 ) => void
289 export type NextHandleFunction = (
290 req: IncomingMessage,
291 res: http.ServerResponse,
292 next: NextFunction,
293 ) => void
294 export type ErrorHandleFunction = (
295 err: any,
296 req: IncomingMessage,
297 res: http.ServerResponse,
298 next: NextFunction,
299 ) => void
300 export type HandleFunction =
301 | SimpleHandleFunction
302 | NextHandleFunction
303 | ErrorHandleFunction
304
305 export interface ServerStackItem {
306 route: string
307 handle: ServerHandle
308 }
309
310 export interface Server extends NodeJS.EventEmitter {
311 (req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void
312
313 route: string
314 stack: ServerStackItem[]
315
316 /**
317 * Utilize the given middleware `handle` to the given `route`,
318 * defaulting to _/_. This "route" is the mount-point for the
319 * middleware, when given a value other than _/_ the middleware
320 * is only effective when that segment is present in the request's
321 * pathname.
322 *
323 * For example if we were to mount a function at _/admin_, it would
324 * be invoked on _/admin_, and _/admin/settings_, however it would
325 * not be invoked for _/_, or _/posts_.
326 */
327 use(fn: NextHandleFunction): Server
328 use(fn: HandleFunction): Server
329 use(route: string, fn: NextHandleFunction): Server
330 use(route: string, fn: HandleFunction): Server
331
332 /**
333 * Handle server requests, punting them down
334 * the middleware stack.
335 */
336 handle(
337 req: http.IncomingMessage,
338 res: http.ServerResponse,
339 next: Function,
340 ): void
341
342 /**
343 * Listen for connections.
344 *
345 * This method takes the same arguments
346 * as node's `http.Server#listen()`.
347 *
348 * HTTP and HTTPS:
349 *
350 * If you run your application both as HTTP
351 * and HTTPS you may wrap them individually,
352 * since your Connect "server" is really just
353 * a JavaScript `Function`.
354 *
355 * var connect = require('connect')
356 * , http = require('http')
357 * , https = require('https');
358 *
359 * var app = connect();
360 *
361 * http.createServer(app).listen(80);
362 * https.createServer(options, app).listen(443);
363 */
364 listen(
365 port: number,
366 hostname?: string,
367 backlog?: number,
368 callback?: Function,
369 ): http.Server
370 listen(port: number, hostname?: string, callback?: Function): http.Server
371 listen(path: string, callback?: Function): http.Server
372 listen(handle: any, listeningListener?: Function): http.Server
373 }
374}
375
376// Inlined to avoid extra dependency
377// MIT Licensed https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/LICENSE
378
379declare namespace HttpProxy {
380 export type ProxyTarget = ProxyTargetUrl | ProxyTargetDetailed
381
382 export type ProxyTargetUrl = string | Partial<url.Url>
383
384 export interface ProxyTargetDetailed {
385 host: string
386 port: number
387 protocol?: string | undefined
388 hostname?: string | undefined
389 socketPath?: string | undefined
390 key?: string | undefined
391 passphrase?: string | undefined
392 pfx?: Buffer | string | undefined
393 cert?: string | undefined
394 ca?: string | undefined
395 ciphers?: string | undefined
396 secureProtocol?: string | undefined
397 }
398
399 export type ErrorCallback = (
400 err: Error,
401 req: http.IncomingMessage,
402 res: http.ServerResponse,
403 target?: ProxyTargetUrl,
404 ) => void
405
406 export class Server extends events.EventEmitter {
407 /**
408 * Creates the proxy server with specified options.
409 * @param options - Config object passed to the proxy
410 */
411 constructor(options?: ServerOptions)
412
413 /**
414 * Used for proxying regular HTTP(S) requests
415 * @param req - Client request.
416 * @param res - Client response.
417 * @param options - Additional options.
418 * @param callback - Error callback.
419 */
420 web(
421 req: http.IncomingMessage,
422 res: http.ServerResponse,
423 options?: ServerOptions,
424 callback?: ErrorCallback,
425 ): void
426
427 /**
428 * Used for proxying regular HTTP(S) requests
429 * @param req - Client request.
430 * @param socket - Client socket.
431 * @param head - Client head.
432 * @param options - Additional options.
433 * @param callback - Error callback.
434 */
435 ws(
436 req: http.IncomingMessage,
437 socket: unknown,
438 head: unknown,
439 options?: ServerOptions,
440 callback?: ErrorCallback,
441 ): void
442
443 /**
444 * A function that wraps the object in a webserver, for your convenience
445 * @param port - Port to listen on
446 */
447 listen(port: number): Server
448
449 /**
450 * A function that closes the inner webserver and stops listening on given port
451 */
452 close(callback?: () => void): void
453
454 /**
455 * Creates the proxy server with specified options.
456 * @param options - Config object passed to the proxy
457 * @returns Proxy object with handlers for `ws` and `web` requests
458 */
459 static createProxyServer(options?: ServerOptions): Server
460
461 /**
462 * Creates the proxy server with specified options.
463 * @param options - Config object passed to the proxy
464 * @returns Proxy object with handlers for `ws` and `web` requests
465 */
466 static createServer(options?: ServerOptions): Server
467
468 /**
469 * Creates the proxy server with specified options.
470 * @param options - Config object passed to the proxy
471 * @returns Proxy object with handlers for `ws` and `web` requests
472 */
473 static createProxy(options?: ServerOptions): Server
474
475 addListener(event: string, listener: () => void): this
476 on(event: string, listener: () => void): this
477 on(event: 'error', listener: ErrorCallback): this
478 on(
479 event: 'start',
480 listener: (
481 req: http.IncomingMessage,
482 res: http.ServerResponse,
483 target: ProxyTargetUrl,
484 ) => void,
485 ): this
486 on(
487 event: 'proxyReq',
488 listener: (
489 proxyReq: http.ClientRequest,
490 req: http.IncomingMessage,
491 res: http.ServerResponse,
492 options: ServerOptions,
493 ) => void,
494 ): this
495 on(
496 event: 'proxyRes',
497 listener: (
498 proxyRes: http.IncomingMessage,
499 req: http.IncomingMessage,
500 res: http.ServerResponse,
501 ) => void,
502 ): this
503 on(
504 event: 'proxyReqWs',
505 listener: (
506 proxyReq: http.ClientRequest,
507 req: http.IncomingMessage,
508 socket: net.Socket,
509 options: ServerOptions,
510 head: any,
511 ) => void,
512 ): this
513 on(
514 event: 'econnreset',
515 listener: (
516 err: Error,
517 req: http.IncomingMessage,
518 res: http.ServerResponse,
519 target: ProxyTargetUrl,
520 ) => void,
521 ): this
522 on(
523 event: 'end',
524 listener: (
525 req: http.IncomingMessage,
526 res: http.ServerResponse,
527 proxyRes: http.IncomingMessage,
528 ) => void,
529 ): this
530 on(
531 event: 'close',
532 listener: (
533 proxyRes: http.IncomingMessage,
534 proxySocket: net.Socket,
535 proxyHead: any,
536 ) => void,
537 ): this
538
539 once(event: string, listener: () => void): this
540 removeListener(event: string, listener: () => void): this
541 removeAllListeners(event?: string): this
542 getMaxListeners(): number
543 setMaxListeners(n: number): this
544 listeners(event: string): Array<() => void>
545 emit(event: string, ...args: any[]): boolean
546 listenerCount(type: string): number
547 }
548
549 export interface ServerOptions {
550 /** URL string to be parsed with the url module. */
551 target?: ProxyTarget | undefined
552 /** URL string to be parsed with the url module. */
553 forward?: ProxyTargetUrl | undefined
554 /** Object to be passed to http(s).request. */
555 agent?: any
556 /** Object to be passed to https.createServer(). */
557 ssl?: any
558 /** If you want to proxy websockets. */
559 ws?: boolean | undefined
560 /** Adds x- forward headers. */
561 xfwd?: boolean | undefined
562 /** Verify SSL certificate. */
563 secure?: boolean | undefined
564 /** Explicitly specify if we are proxying to another proxy. */
565 toProxy?: boolean | undefined
566 /** Specify whether you want to prepend the target's path to the proxy path. */
567 prependPath?: boolean | undefined
568 /** Specify whether you want to ignore the proxy path of the incoming request. */
569 ignorePath?: boolean | undefined
570 /** Local interface string to bind for outgoing connections. */
571 localAddress?: string | undefined
572 /** Changes the origin of the host header to the target URL. */
573 changeOrigin?: boolean | undefined
574 /** specify whether you want to keep letter case of response header key */
575 preserveHeaderKeyCase?: boolean | undefined
576 /** Basic authentication i.e. 'user:password' to compute an Authorization header. */
577 auth?: string | undefined
578 /** Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null. */
579 hostRewrite?: string | undefined
580 /** Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false. */
581 autoRewrite?: boolean | undefined
582 /** Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null. */
583 protocolRewrite?: string | undefined
584 /** rewrites domain of set-cookie headers. */
585 cookieDomainRewrite?:
586 | false
587 | string
588 | { [oldDomain: string]: string }
589 | undefined
590 /** rewrites path of set-cookie headers. Default: false */
591 cookiePathRewrite?:
592 | false
593 | string
594 | { [oldPath: string]: string }
595 | undefined
596 /** object with extra headers to be added to target requests. */
597 headers?: { [header: string]: string } | undefined
598 /** Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes) */
599 proxyTimeout?: number | undefined
600 /** Timeout (in milliseconds) for incoming requests */
601 timeout?: number | undefined
602 /** Specify whether you want to follow redirects. Default: false */
603 followRedirects?: boolean | undefined
604 /** 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 */
605 selfHandleResponse?: boolean | undefined
606 /** Buffer */
607 buffer?: stream.Stream | undefined
608 }
609}
610
611interface ProxyOptions extends HttpProxy.ServerOptions {
612 /**
613 * rewrite path
614 */
615 rewrite?: (path: string) => string;
616 /**
617 * configure the proxy server (e.g. listen to events)
618 */
619 configure?: (proxy: HttpProxy.Server, options: ProxyOptions) => void;
620 /**
621 * webpack-dev-server style bypass function
622 */
623 bypass?: (req: http.IncomingMessage,
624 /** undefined for WebSocket upgrade requests */
625 res: http.ServerResponse | undefined, options: ProxyOptions) => void | null | undefined | false | string;
626 /**
627 * rewrite the Origin header of a WebSocket request to match the target
628 *
629 * **Exercise caution as rewriting the Origin can leave the proxying open to [CSRF attacks](https://owasp.org/www-community/attacks/csrf).**
630 */
631 rewriteWsOrigin?: boolean | undefined;
632}
633
634type LogType = 'error' | 'warn' | 'info';
635type LogLevel = LogType | 'silent';
636interface Logger {
637 info(msg: string, options?: LogOptions): void;
638 warn(msg: string, options?: LogOptions): void;
639 warnOnce(msg: string, options?: LogOptions): void;
640 error(msg: string, options?: LogErrorOptions): void;
641 clearScreen(type: LogType): void;
642 hasErrorLogged(error: Error | RollupError): boolean;
643 hasWarned: boolean;
644}
645interface LogOptions {
646 clear?: boolean;
647 timestamp?: boolean;
648 environment?: string;
649}
650interface LogErrorOptions extends LogOptions {
651 error?: Error | RollupError | null;
652}
653interface LoggerOptions {
654 prefix?: string;
655 allowClearScreen?: boolean;
656 customLogger?: Logger;
657 console?: Console;
658}
659declare function createLogger(level?: LogLevel, options?: LoggerOptions): Logger;
660
661interface CommonServerOptions {
662 /**
663 * Specify server port. Note if the port is already being used, Vite will
664 * automatically try the next available port so this may not be the actual
665 * port the server ends up listening on.
666 */
667 port?: number;
668 /**
669 * If enabled, vite will exit if specified port is already in use
670 */
671 strictPort?: boolean;
672 /**
673 * Specify which IP addresses the server should listen on.
674 * Set to 0.0.0.0 to listen on all addresses, including LAN and public addresses.
675 */
676 host?: string | boolean;
677 /**
678 * Enable TLS + HTTP/2.
679 * Note: this downgrades to TLS only when the proxy option is also used.
680 */
681 https?: HttpsServerOptions;
682 /**
683 * Open browser window on startup
684 */
685 open?: boolean | string;
686 /**
687 * Configure custom proxy rules for the dev server. Expects an object
688 * of `{ key: options }` pairs.
689 * Uses [`http-proxy`](https://github.com/http-party/node-http-proxy).
690 * Full options [here](https://github.com/http-party/node-http-proxy#options).
691 *
692 * Example `vite.config.js`:
693 * ``` js
694 * module.exports = {
695 * proxy: {
696 * // string shorthand: /foo -> http://localhost:4567/foo
697 * '/foo': 'http://localhost:4567',
698 * // with options
699 * '/api': {
700 * target: 'http://jsonplaceholder.typicode.com',
701 * changeOrigin: true,
702 * rewrite: path => path.replace(/^\/api/, '')
703 * }
704 * }
705 * }
706 * ```
707 */
708 proxy?: Record<string, string | ProxyOptions>;
709 /**
710 * Configure CORS for the dev server.
711 * Uses https://github.com/expressjs/cors.
712 * Set to `true` to allow all methods from any origin, or configure separately
713 * using an object.
714 */
715 cors?: CorsOptions | boolean;
716 /**
717 * Specify server response headers.
718 */
719 headers?: OutgoingHttpHeaders;
720}
721/**
722 * https://github.com/expressjs/cors#configuration-options
723 */
724interface CorsOptions {
725 origin?: CorsOrigin | ((origin: string | undefined, cb: (err: Error, origins: CorsOrigin) => void) => void);
726 methods?: string | string[];
727 allowedHeaders?: string | string[];
728 exposedHeaders?: string | string[];
729 credentials?: boolean;
730 maxAge?: number;
731 preflightContinue?: boolean;
732 optionsSuccessStatus?: number;
733}
734type CorsOrigin = boolean | string | RegExp | (string | RegExp)[];
735
736type RequiredExceptFor<T, K extends keyof T> = Pick<T, K> & Required<Omit<T, K>>;
737
738interface PreviewOptions extends CommonServerOptions {
739}
740interface ResolvedPreviewOptions extends RequiredExceptFor<PreviewOptions, 'host' | 'https' | 'proxy'> {
741}
742interface PreviewServer {
743 /**
744 * The resolved vite config object
745 */
746 config: ResolvedConfig;
747 /**
748 * Stop the server.
749 */
750 close(): Promise<void>;
751 /**
752 * A connect app instance.
753 * - Can be used to attach custom middlewares to the preview server.
754 * - Can also be used as the handler function of a custom http server
755 * or as a middleware in any connect-style Node.js frameworks
756 *
757 * https://github.com/senchalabs/connect#use-middleware
758 */
759 middlewares: Connect.Server;
760 /**
761 * native Node http server instance
762 */
763 httpServer: HttpServer;
764 /**
765 * The resolved urls Vite prints on the CLI (URL-encoded). Returns `null`
766 * if the server is not listening on any port.
767 */
768 resolvedUrls: ResolvedServerUrls | null;
769 /**
770 * Print server urls
771 */
772 printUrls(): void;
773 /**
774 * Bind CLI shortcuts
775 */
776 bindCLIShortcuts(options?: BindCLIShortcutsOptions<PreviewServer>): void;
777}
778type PreviewServerHook = (this: void, server: PreviewServer) => (() => void) | void | Promise<(() => void) | void>;
779/**
780 * Starts the Vite server in preview mode, to simulate a production deployment
781 */
782declare function preview(inlineConfig?: InlineConfig): Promise<PreviewServer>;
783
784type BindCLIShortcutsOptions<Server = ViteDevServer | PreviewServer> = {
785 /**
786 * Print a one-line shortcuts "help" hint to the terminal
787 */
788 print?: boolean;
789 /**
790 * Custom shortcuts to run when a key is pressed. These shortcuts take priority
791 * over the default shortcuts if they have the same keys (except the `h` key).
792 * To disable a default shortcut, define the same key but with `action: undefined`.
793 */
794 customShortcuts?: CLIShortcut<Server>[];
795};
796type CLIShortcut<Server = ViteDevServer | PreviewServer> = {
797 key: string;
798 description: string;
799 action?(server: Server): void | Promise<void>;
800};
801
802declare class PartialEnvironment {
803 name: string;
804 getTopLevelConfig(): ResolvedConfig;
805 config: ResolvedConfig & ResolvedEnvironmentOptions;
806 /**
807 * @deprecated use environment.config instead
808 **/
809 get options(): ResolvedEnvironmentOptions;
810 logger: Logger;
811 constructor(name: string, topLevelConfig: ResolvedConfig, options?: ResolvedEnvironmentOptions);
812}
813declare class BaseEnvironment extends PartialEnvironment {
814 get plugins(): Plugin[];
815 constructor(name: string, config: ResolvedConfig, options?: ResolvedEnvironmentOptions);
816}
817/**
818 * This class discourages users from inversely checking the `mode`
819 * to determine the type of environment, e.g.
820 *
821 * ```js
822 * const isDev = environment.mode !== 'build' // bad
823 * const isDev = environment.mode === 'dev' // good
824 * ```
825 *
826 * You should also not check against `"unknown"` specfically. It's
827 * a placeholder for more possible environment types.
828 */
829declare class UnknownEnvironment extends BaseEnvironment {
830 mode: "unknown";
831}
832
833declare class ScanEnvironment extends BaseEnvironment {
834 mode: "scan";
835 get pluginContainer(): EnvironmentPluginContainer;
836 init(): Promise<void>;
837}
838
839type ExportsData = {
840 hasModuleSyntax: boolean;
841 exports: readonly string[];
842 jsxLoader?: boolean;
843};
844interface DepsOptimizer {
845 init: () => Promise<void>;
846 metadata: DepOptimizationMetadata;
847 scanProcessing?: Promise<void>;
848 registerMissingImport: (id: string, resolved: string) => OptimizedDepInfo;
849 run: () => void;
850 isOptimizedDepFile: (id: string) => boolean;
851 isOptimizedDepUrl: (url: string) => boolean;
852 getOptimizedDepId: (depInfo: OptimizedDepInfo) => string;
853 close: () => Promise<void>;
854 options: DepOptimizationOptions;
855}
856interface DepOptimizationConfig {
857 /**
858 * Force optimize listed dependencies (must be resolvable import paths,
859 * cannot be globs).
860 */
861 include?: string[];
862 /**
863 * Do not optimize these dependencies (must be resolvable import paths,
864 * cannot be globs).
865 */
866 exclude?: string[];
867 /**
868 * Forces ESM interop when importing these dependencies. Some legacy
869 * packages advertise themselves as ESM but use `require` internally
870 * @experimental
871 */
872 needsInterop?: string[];
873 /**
874 * Options to pass to esbuild during the dep scanning and optimization
875 *
876 * Certain options are omitted since changing them would not be compatible
877 * with Vite's dep optimization.
878 *
879 * - `external` is also omitted, use Vite's `optimizeDeps.exclude` option
880 * - `plugins` are merged with Vite's dep plugin
881 *
882 * https://esbuild.github.io/api
883 */
884 esbuildOptions?: Omit<esbuild_BuildOptions, 'bundle' | 'entryPoints' | 'external' | 'write' | 'watch' | 'outdir' | 'outfile' | 'outbase' | 'outExtension' | 'metafile'>;
885 /**
886 * List of file extensions that can be optimized. A corresponding esbuild
887 * plugin must exist to handle the specific extension.
888 *
889 * By default, Vite can optimize `.mjs`, `.js`, `.ts`, and `.mts` files. This option
890 * allows specifying additional extensions.
891 *
892 * @experimental
893 */
894 extensions?: string[];
895 /**
896 * Deps optimization during build was removed in Vite 5.1. This option is
897 * now redundant and will be removed in a future version. Switch to using
898 * `optimizeDeps.noDiscovery` and an empty or undefined `optimizeDeps.include`.
899 * true or 'dev' disables the optimizer, false or 'build' leaves it enabled.
900 * @default 'build'
901 * @deprecated
902 * @experimental
903 */
904 disabled?: boolean | 'build' | 'dev';
905 /**
906 * Automatic dependency discovery. When `noDiscovery` is true, only dependencies
907 * listed in `include` will be optimized. The scanner isn't run for cold start
908 * in this case. CJS-only dependencies must be present in `include` during dev.
909 * @default false
910 * @experimental
911 */
912 noDiscovery?: boolean;
913 /**
914 * When enabled, it will hold the first optimized deps results until all static
915 * imports are crawled on cold start. This avoids the need for full-page reloads
916 * when new dependencies are discovered and they trigger the generation of new
917 * common chunks. If all dependencies are found by the scanner plus the explicitly
918 * defined ones in `include`, it is better to disable this option to let the
919 * browser process more requests in parallel.
920 * @default true
921 * @experimental
922 */
923 holdUntilCrawlEnd?: boolean;
924}
925type DepOptimizationOptions = DepOptimizationConfig & {
926 /**
927 * By default, Vite will crawl your `index.html` to detect dependencies that
928 * need to be pre-bundled. If `build.rollupOptions.input` is specified, Vite
929 * will crawl those entry points instead.
930 *
931 * If neither of these fit your needs, you can specify custom entries using
932 * this option - the value should be a tinyglobby pattern or array of patterns
933 * (https://github.com/SuperchupuDev/tinyglobby) that are relative from
934 * vite project root. This will overwrite default entries inference.
935 */
936 entries?: string | string[];
937 /**
938 * Force dep pre-optimization regardless of whether deps have changed.
939 * @experimental
940 */
941 force?: boolean;
942};
943interface OptimizedDepInfo {
944 id: string;
945 file: string;
946 src?: string;
947 needsInterop?: boolean;
948 browserHash?: string;
949 fileHash?: string;
950 /**
951 * During optimization, ids can still be resolved to their final location
952 * but the bundles may not yet be saved to disk
953 */
954 processing?: Promise<void>;
955 /**
956 * ExportData cache, discovered deps will parse the src entry to get exports
957 * data used both to define if interop is needed and when pre-bundling
958 */
959 exportsData?: Promise<ExportsData>;
960}
961interface DepOptimizationMetadata {
962 /**
963 * The main hash is determined by user config and dependency lockfiles.
964 * This is checked on server startup to avoid unnecessary re-bundles.
965 */
966 hash: string;
967 /**
968 * This hash is determined by dependency lockfiles.
969 * This is checked on server startup to avoid unnecessary re-bundles.
970 */
971 lockfileHash: string;
972 /**
973 * This hash is determined by user config.
974 * This is checked on server startup to avoid unnecessary re-bundles.
975 */
976 configHash: string;
977 /**
978 * The browser hash is determined by the main hash plus additional dependencies
979 * discovered at runtime. This is used to invalidate browser requests to
980 * optimized deps.
981 */
982 browserHash: string;
983 /**
984 * Metadata for each already optimized dependency
985 */
986 optimized: Record<string, OptimizedDepInfo>;
987 /**
988 * Metadata for non-entry optimized chunks and dynamic imports
989 */
990 chunks: Record<string, OptimizedDepInfo>;
991 /**
992 * Metadata for each newly discovered dependency after processing
993 */
994 discovered: Record<string, OptimizedDepInfo>;
995 /**
996 * OptimizedDepInfo list
997 */
998 depInfoList: OptimizedDepInfo[];
999}
1000/**
1001 * Scan and optimize dependencies within a project.
1002 * Used by Vite CLI when running `vite optimize`.
1003 */
1004declare function optimizeDeps(config: ResolvedConfig, force?: boolean | undefined, asCommand?: boolean): Promise<DepOptimizationMetadata>;
1005
1006interface TransformResult {
1007 code: string;
1008 map: SourceMap | {
1009 mappings: '';
1010 } | null;
1011 ssr?: boolean;
1012 etag?: string;
1013 deps?: string[];
1014 dynamicDeps?: string[];
1015}
1016interface TransformOptions {
1017 /**
1018 * @deprecated inferred from environment
1019 */
1020 ssr?: boolean;
1021}
1022
1023declare class EnvironmentModuleNode {
1024 environment: string;
1025 /**
1026 * Public served url path, starts with /
1027 */
1028 url: string;
1029 /**
1030 * Resolved file system path + query
1031 */
1032 id: string | null;
1033 file: string | null;
1034 type: 'js' | 'css';
1035 info?: ModuleInfo;
1036 meta?: Record<string, any>;
1037 importers: Set<EnvironmentModuleNode>;
1038 importedModules: Set<EnvironmentModuleNode>;
1039 acceptedHmrDeps: Set<EnvironmentModuleNode>;
1040 acceptedHmrExports: Set<string> | null;
1041 importedBindings: Map<string, Set<string>> | null;
1042 isSelfAccepting?: boolean;
1043 transformResult: TransformResult | null;
1044 ssrModule: Record<string, any> | null;
1045 ssrError: Error | null;
1046 lastHMRTimestamp: number;
1047 lastInvalidationTimestamp: number;
1048 /**
1049 * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870
1050 */
1051 constructor(url: string, environment: string, setIsSelfAccepting?: boolean);
1052}
1053type ResolvedUrl = [
1054 url: string,
1055 resolvedId: string,
1056 meta: object | null | undefined
1057];
1058declare class EnvironmentModuleGraph {
1059 environment: string;
1060 urlToModuleMap: Map<string, EnvironmentModuleNode>;
1061 idToModuleMap: Map<string, EnvironmentModuleNode>;
1062 etagToModuleMap: Map<string, EnvironmentModuleNode>;
1063 fileToModulesMap: Map<string, Set<EnvironmentModuleNode>>;
1064 constructor(environment: string, resolveId: (url: string) => Promise<PartialResolvedId | null>);
1065 getModuleByUrl(rawUrl: string): Promise<EnvironmentModuleNode | undefined>;
1066 getModuleById(id: string): EnvironmentModuleNode | undefined;
1067 getModulesByFile(file: string): Set<EnvironmentModuleNode> | undefined;
1068 onFileChange(file: string): void;
1069 onFileDelete(file: string): void;
1070 invalidateModule(mod: EnvironmentModuleNode, seen?: Set<EnvironmentModuleNode>, timestamp?: number, isHmr?: boolean,
1071 ): void;
1072 invalidateAll(): void;
1073 /**
1074 * Update the module graph based on a module's updated imports information
1075 * If there are dependencies that no longer have any importers, they are
1076 * returned as a Set.
1077 *
1078 * @param staticImportedUrls Subset of `importedModules` where they're statically imported in code.
1079 * This is only used for soft invalidations so `undefined` is fine but may cause more runtime processing.
1080 */
1081 updateModuleInfo(mod: EnvironmentModuleNode, importedModules: Set<string | EnvironmentModuleNode>, importedBindings: Map<string, Set<string>> | null, acceptedModules: Set<string | EnvironmentModuleNode>, acceptedExports: Set<string> | null, isSelfAccepting: boolean,
1082 ): Promise<Set<EnvironmentModuleNode> | undefined>;
1083 ensureEntryFromUrl(rawUrl: string, setIsSelfAccepting?: boolean): Promise<EnvironmentModuleNode>;
1084 createFileOnlyEntry(file: string): EnvironmentModuleNode;
1085 resolveUrl(url: string): Promise<ResolvedUrl>;
1086 updateModuleTransformResult(mod: EnvironmentModuleNode, result: TransformResult | null): void;
1087 getModuleByEtag(etag: string): EnvironmentModuleNode | undefined;
1088}
1089
1090declare class ModuleNode {
1091 _moduleGraph: ModuleGraph;
1092 _clientModule: EnvironmentModuleNode | undefined;
1093 _ssrModule: EnvironmentModuleNode | undefined;
1094 constructor(moduleGraph: ModuleGraph, clientModule?: EnvironmentModuleNode, ssrModule?: EnvironmentModuleNode);
1095 _get<T extends keyof EnvironmentModuleNode>(prop: T): EnvironmentModuleNode[T];
1096 _set<T extends keyof EnvironmentModuleNode>(prop: T, value: EnvironmentModuleNode[T]): void;
1097 _wrapModuleSet(prop: ModuleSetNames, module: EnvironmentModuleNode | undefined): Set<ModuleNode>;
1098 _getModuleSetUnion(prop: 'importedModules' | 'importers'): Set<ModuleNode>;
1099 _getModuleInfoUnion(prop: 'info'): ModuleInfo | undefined;
1100 _getModuleObjectUnion(prop: 'meta'): Record<string, any> | undefined;
1101 get url(): string;
1102 set url(value: string);
1103 get id(): string | null;
1104 set id(value: string | null);
1105 get file(): string | null;
1106 set file(value: string | null);
1107 get type(): 'js' | 'css';
1108 get info(): ModuleInfo | undefined;
1109 get meta(): Record<string, any> | undefined;
1110 get importers(): Set<ModuleNode>;
1111 get clientImportedModules(): Set<ModuleNode>;
1112 get ssrImportedModules(): Set<ModuleNode>;
1113 get importedModules(): Set<ModuleNode>;
1114 get acceptedHmrDeps(): Set<ModuleNode>;
1115 get acceptedHmrExports(): Set<string> | null;
1116 get importedBindings(): Map<string, Set<string>> | null;
1117 get isSelfAccepting(): boolean | undefined;
1118 get transformResult(): TransformResult | null;
1119 set transformResult(value: TransformResult | null);
1120 get ssrTransformResult(): TransformResult | null;
1121 set ssrTransformResult(value: TransformResult | null);
1122 get ssrModule(): Record<string, any> | null;
1123 get ssrError(): Error | null;
1124 get lastHMRTimestamp(): number;
1125 set lastHMRTimestamp(value: number);
1126 get lastInvalidationTimestamp(): number;
1127 get invalidationState(): TransformResult | 'HARD_INVALIDATED' | undefined;
1128 get ssrInvalidationState(): TransformResult | 'HARD_INVALIDATED' | undefined;
1129}
1130declare class ModuleGraph {
1131 urlToModuleMap: Map<string, ModuleNode>;
1132 idToModuleMap: Map<string, ModuleNode>;
1133 etagToModuleMap: Map<string, ModuleNode>;
1134 fileToModulesMap: Map<string, Set<ModuleNode>>;
1135 private moduleNodeCache;
1136 constructor(moduleGraphs: {
1137 client: () => EnvironmentModuleGraph;
1138 ssr: () => EnvironmentModuleGraph;
1139 });
1140 getModuleById(id: string): ModuleNode | undefined;
1141 getModuleByUrl(url: string, _ssr?: boolean): Promise<ModuleNode | undefined>;
1142 getModulesByFile(file: string): Set<ModuleNode> | undefined;
1143 onFileChange(file: string): void;
1144 onFileDelete(file: string): void;
1145 invalidateModule(mod: ModuleNode, seen?: Set<ModuleNode>, timestamp?: number, isHmr?: boolean,
1146 ): void;
1147 invalidateAll(): void;
1148 ensureEntryFromUrl(rawUrl: string, ssr?: boolean, setIsSelfAccepting?: boolean): Promise<ModuleNode>;
1149 createFileOnlyEntry(file: string): ModuleNode;
1150 resolveUrl(url: string, ssr?: boolean): Promise<ResolvedUrl>;
1151 updateModuleTransformResult(mod: ModuleNode, result: TransformResult | null, ssr?: boolean): void;
1152 getModuleByEtag(etag: string): ModuleNode | undefined;
1153 getBackwardCompatibleBrowserModuleNode(clientModule: EnvironmentModuleNode): ModuleNode;
1154 getBackwardCompatibleServerModuleNode(ssrModule: EnvironmentModuleNode): ModuleNode;
1155 getBackwardCompatibleModuleNode(mod: EnvironmentModuleNode): ModuleNode;
1156 getBackwardCompatibleModuleNodeDual(clientModule?: EnvironmentModuleNode, ssrModule?: EnvironmentModuleNode): ModuleNode;
1157}
1158type ModuleSetNames = 'acceptedHmrDeps' | 'importedModules';
1159
1160interface HmrOptions {
1161 protocol?: string;
1162 host?: string;
1163 port?: number;
1164 clientPort?: number;
1165 path?: string;
1166 timeout?: number;
1167 overlay?: boolean;
1168 server?: HttpServer;
1169}
1170interface HotUpdateOptions {
1171 type: 'create' | 'update' | 'delete';
1172 file: string;
1173 timestamp: number;
1174 modules: Array<EnvironmentModuleNode>;
1175 read: () => string | Promise<string>;
1176 server: ViteDevServer;
1177 /**
1178 * @deprecated use this.environment in the hotUpdate hook instead
1179 **/
1180 environment: DevEnvironment;
1181}
1182interface HmrContext {
1183 file: string;
1184 timestamp: number;
1185 modules: Array<ModuleNode>;
1186 read: () => string | Promise<string>;
1187 server: ViteDevServer;
1188}
1189interface HotChannelClient {
1190 send(payload: HotPayload): void;
1191}
1192/** @deprecated use `HotChannelClient` instead */
1193type HMRBroadcasterClient = HotChannelClient;
1194type HotChannelListener<T extends string = string> = (data: InferCustomEventPayload<T>, client: HotChannelClient) => void;
1195interface HotChannel<Api = any> {
1196 /**
1197 * Broadcast events to all clients
1198 */
1199 send?(payload: HotPayload): void;
1200 /**
1201 * Handle custom event emitted by `import.meta.hot.send`
1202 */
1203 on?<T extends string>(event: T, listener: HotChannelListener<T>): void;
1204 on?(event: 'connection', listener: () => void): void;
1205 /**
1206 * Unregister event listener
1207 */
1208 off?(event: string, listener: Function): void;
1209 /**
1210 * Start listening for messages
1211 */
1212 listen?(): void;
1213 /**
1214 * Disconnect all clients, called when server is closed or restarted.
1215 */
1216 close?(): Promise<unknown> | void;
1217 api?: Api;
1218}
1219/** @deprecated use `HotChannel` instead */
1220type HMRChannel = HotChannel;
1221interface NormalizedHotChannelClient {
1222 /**
1223 * Send event to the client
1224 */
1225 send(payload: HotPayload): void;
1226 /**
1227 * Send custom event
1228 */
1229 send(event: string, payload?: CustomPayload['data']): void;
1230}
1231interface NormalizedHotChannel<Api = any> {
1232 /**
1233 * Broadcast events to all clients
1234 */
1235 send(payload: HotPayload): void;
1236 /**
1237 * Send custom event
1238 */
1239 send<T extends string>(event: T, payload?: InferCustomEventPayload<T>): void;
1240 /**
1241 * Handle custom event emitted by `import.meta.hot.send`
1242 */
1243 on<T extends string>(event: T, listener: (data: InferCustomEventPayload<T>, client: NormalizedHotChannelClient) => void): void;
1244 on(event: 'connection', listener: () => void): void;
1245 /**
1246 * Unregister event listener
1247 */
1248 off(event: string, listener: Function): void;
1249 handleInvoke(payload: HotPayload): Promise<{
1250 result: any;
1251 } | {
1252 error: any;
1253 }>;
1254 /**
1255 * Start listening for messages
1256 */
1257 listen(): void;
1258 /**
1259 * Disconnect all clients, called when server is closed or restarted.
1260 */
1261 close(): Promise<unknown> | void;
1262 api?: Api;
1263}
1264type ServerHotChannelApi = {
1265 innerEmitter: EventEmitter;
1266 outsideEmitter: EventEmitter;
1267};
1268type ServerHotChannel = HotChannel<ServerHotChannelApi>;
1269/** @deprecated use `ServerHotChannel` instead */
1270type ServerHMRChannel = ServerHotChannel;
1271declare function createServerHotChannel(): ServerHotChannel;
1272/** @deprecated use `environment.hot` instead */
1273interface HotBroadcaster extends NormalizedHotChannel {
1274 readonly channels: NormalizedHotChannel[];
1275 /**
1276 * A noop.
1277 * @deprecated
1278 */
1279 addChannel(channel: HotChannel): HotBroadcaster;
1280 close(): Promise<unknown[]>;
1281}
1282/** @deprecated use `environment.hot` instead */
1283type HMRBroadcaster = HotBroadcaster;
1284
1285// Modified and inlined to avoid extra dependency
1286// Source: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/ws/index.d.ts
1287
1288declare const WebSocketAlias: typeof WebSocket
1289interface WebSocketAlias extends WebSocket {}
1290
1291// WebSocket socket.
1292declare class WebSocket extends EventEmitter {
1293 /** The connection is not yet open. */
1294 static readonly CONNECTING: 0
1295 /** The connection is open and ready to communicate. */
1296 static readonly OPEN: 1
1297 /** The connection is in the process of closing. */
1298 static readonly CLOSING: 2
1299 /** The connection is closed. */
1300 static readonly CLOSED: 3
1301
1302 binaryType: 'nodebuffer' | 'arraybuffer' | 'fragments'
1303 readonly bufferedAmount: number
1304 readonly extensions: string
1305 /** Indicates whether the websocket is paused */
1306 readonly isPaused: boolean
1307 readonly protocol: string
1308 /** The current state of the connection */
1309 readonly readyState:
1310 | typeof WebSocket.CONNECTING
1311 | typeof WebSocket.OPEN
1312 | typeof WebSocket.CLOSING
1313 | typeof WebSocket.CLOSED
1314 readonly url: string
1315
1316 /** The connection is not yet open. */
1317 readonly CONNECTING: 0
1318 /** The connection is open and ready to communicate. */
1319 readonly OPEN: 1
1320 /** The connection is in the process of closing. */
1321 readonly CLOSING: 2
1322 /** The connection is closed. */
1323 readonly CLOSED: 3
1324
1325 onopen: ((event: WebSocket.Event) => void) | null
1326 onerror: ((event: WebSocket.ErrorEvent) => void) | null
1327 onclose: ((event: WebSocket.CloseEvent) => void) | null
1328 onmessage: ((event: WebSocket.MessageEvent) => void) | null
1329
1330 constructor(address: null)
1331 constructor(
1332 address: string | URL,
1333 options?: WebSocket.ClientOptions | ClientRequestArgs,
1334 )
1335 constructor(
1336 address: string | URL,
1337 protocols?: string | string[],
1338 options?: WebSocket.ClientOptions | ClientRequestArgs,
1339 )
1340
1341 close(code?: number, data?: string | Buffer): void
1342 ping(data?: any, mask?: boolean, cb?: (err: Error) => void): void
1343 pong(data?: any, mask?: boolean, cb?: (err: Error) => void): void
1344 send(data: any, cb?: (err?: Error) => void): void
1345 send(
1346 data: any,
1347 options: {
1348 mask?: boolean | undefined
1349 binary?: boolean | undefined
1350 compress?: boolean | undefined
1351 fin?: boolean | undefined
1352 },
1353 cb?: (err?: Error) => void,
1354 ): void
1355 terminate(): void
1356
1357 /**
1358 * Pause the websocket causing it to stop emitting events. Some events can still be
1359 * emitted after this is called, until all buffered data is consumed. This method
1360 * is a noop if the ready state is `CONNECTING` or `CLOSED`.
1361 */
1362 pause(): void
1363 /**
1364 * Make a paused socket resume emitting events. This method is a noop if the ready
1365 * state is `CONNECTING` or `CLOSED`.
1366 */
1367 resume(): void
1368
1369 // HTML5 WebSocket events
1370 addEventListener(
1371 method: 'message',
1372 cb: (event: WebSocket.MessageEvent) => void,
1373 options?: WebSocket.EventListenerOptions,
1374 ): void
1375 addEventListener(
1376 method: 'close',
1377 cb: (event: WebSocket.CloseEvent) => void,
1378 options?: WebSocket.EventListenerOptions,
1379 ): void
1380 addEventListener(
1381 method: 'error',
1382 cb: (event: WebSocket.ErrorEvent) => void,
1383 options?: WebSocket.EventListenerOptions,
1384 ): void
1385 addEventListener(
1386 method: 'open',
1387 cb: (event: WebSocket.Event) => void,
1388 options?: WebSocket.EventListenerOptions,
1389 ): void
1390
1391 removeEventListener(
1392 method: 'message',
1393 cb: (event: WebSocket.MessageEvent) => void,
1394 ): void
1395 removeEventListener(
1396 method: 'close',
1397 cb: (event: WebSocket.CloseEvent) => void,
1398 ): void
1399 removeEventListener(
1400 method: 'error',
1401 cb: (event: WebSocket.ErrorEvent) => void,
1402 ): void
1403 removeEventListener(
1404 method: 'open',
1405 cb: (event: WebSocket.Event) => void,
1406 ): void
1407
1408 // Events
1409 on(
1410 event: 'close',
1411 listener: (this: WebSocket, code: number, reason: Buffer) => void,
1412 ): this
1413 on(event: 'error', listener: (this: WebSocket, err: Error) => void): this
1414 on(
1415 event: 'upgrade',
1416 listener: (this: WebSocket, request: IncomingMessage) => void,
1417 ): this
1418 on(
1419 event: 'message',
1420 listener: (
1421 this: WebSocket,
1422 data: WebSocket.RawData,
1423 isBinary: boolean,
1424 ) => void,
1425 ): this
1426 on(event: 'open', listener: (this: WebSocket) => void): this
1427 on(
1428 event: 'ping' | 'pong',
1429 listener: (this: WebSocket, data: Buffer) => void,
1430 ): this
1431 on(
1432 event: 'unexpected-response',
1433 listener: (
1434 this: WebSocket,
1435 request: ClientRequest,
1436 response: IncomingMessage,
1437 ) => void,
1438 ): this
1439 on(
1440 event: string | symbol,
1441 listener: (this: WebSocket, ...args: any[]) => void,
1442 ): this
1443
1444 once(
1445 event: 'close',
1446 listener: (this: WebSocket, code: number, reason: Buffer) => void,
1447 ): this
1448 once(event: 'error', listener: (this: WebSocket, err: Error) => void): this
1449 once(
1450 event: 'upgrade',
1451 listener: (this: WebSocket, request: IncomingMessage) => void,
1452 ): this
1453 once(
1454 event: 'message',
1455 listener: (
1456 this: WebSocket,
1457 data: WebSocket.RawData,
1458 isBinary: boolean,
1459 ) => void,
1460 ): this
1461 once(event: 'open', listener: (this: WebSocket) => void): this
1462 once(
1463 event: 'ping' | 'pong',
1464 listener: (this: WebSocket, data: Buffer) => void,
1465 ): this
1466 once(
1467 event: 'unexpected-response',
1468 listener: (
1469 this: WebSocket,
1470 request: ClientRequest,
1471 response: IncomingMessage,
1472 ) => void,
1473 ): this
1474 once(
1475 event: string | symbol,
1476 listener: (this: WebSocket, ...args: any[]) => void,
1477 ): this
1478
1479 off(
1480 event: 'close',
1481 listener: (this: WebSocket, code: number, reason: Buffer) => void,
1482 ): this
1483 off(event: 'error', listener: (this: WebSocket, err: Error) => void): this
1484 off(
1485 event: 'upgrade',
1486 listener: (this: WebSocket, request: IncomingMessage) => void,
1487 ): this
1488 off(
1489 event: 'message',
1490 listener: (
1491 this: WebSocket,
1492 data: WebSocket.RawData,
1493 isBinary: boolean,
1494 ) => void,
1495 ): this
1496 off(event: 'open', listener: (this: WebSocket) => void): this
1497 off(
1498 event: 'ping' | 'pong',
1499 listener: (this: WebSocket, data: Buffer) => void,
1500 ): this
1501 off(
1502 event: 'unexpected-response',
1503 listener: (
1504 this: WebSocket,
1505 request: ClientRequest,
1506 response: IncomingMessage,
1507 ) => void,
1508 ): this
1509 off(
1510 event: string | symbol,
1511 listener: (this: WebSocket, ...args: any[]) => void,
1512 ): this
1513
1514 addListener(
1515 event: 'close',
1516 listener: (code: number, reason: Buffer) => void,
1517 ): this
1518 addListener(event: 'error', listener: (err: Error) => void): this
1519 addListener(
1520 event: 'upgrade',
1521 listener: (request: IncomingMessage) => void,
1522 ): this
1523 addListener(
1524 event: 'message',
1525 listener: (data: WebSocket.RawData, isBinary: boolean) => void,
1526 ): this
1527 addListener(event: 'open', listener: () => void): this
1528 addListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
1529 addListener(
1530 event: 'unexpected-response',
1531 listener: (request: ClientRequest, response: IncomingMessage) => void,
1532 ): this
1533 addListener(event: string | symbol, listener: (...args: any[]) => void): this
1534
1535 removeListener(
1536 event: 'close',
1537 listener: (code: number, reason: Buffer) => void,
1538 ): this
1539 removeListener(event: 'error', listener: (err: Error) => void): this
1540 removeListener(
1541 event: 'upgrade',
1542 listener: (request: IncomingMessage) => void,
1543 ): this
1544 removeListener(
1545 event: 'message',
1546 listener: (data: WebSocket.RawData, isBinary: boolean) => void,
1547 ): this
1548 removeListener(event: 'open', listener: () => void): this
1549 removeListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
1550 removeListener(
1551 event: 'unexpected-response',
1552 listener: (request: ClientRequest, response: IncomingMessage) => void,
1553 ): this
1554 removeListener(
1555 event: string | symbol,
1556 listener: (...args: any[]) => void,
1557 ): this
1558}
1559
1560declare namespace WebSocket {
1561 /**
1562 * Data represents the raw message payload received over the WebSocket.
1563 */
1564 type RawData = Buffer | ArrayBuffer | Buffer[]
1565
1566 /**
1567 * Data represents the message payload received over the WebSocket.
1568 */
1569 type Data = string | Buffer | ArrayBuffer | Buffer[]
1570
1571 /**
1572 * CertMeta represents the accepted types for certificate & key data.
1573 */
1574 type CertMeta = string | string[] | Buffer | Buffer[]
1575
1576 /**
1577 * VerifyClientCallbackSync is a synchronous callback used to inspect the
1578 * incoming message. The return value (boolean) of the function determines
1579 * whether or not to accept the handshake.
1580 */
1581 type VerifyClientCallbackSync = (info: {
1582 origin: string
1583 secure: boolean
1584 req: IncomingMessage
1585 }) => boolean
1586
1587 /**
1588 * VerifyClientCallbackAsync is an asynchronous callback used to inspect the
1589 * incoming message. The return value (boolean) of the function determines
1590 * whether or not to accept the handshake.
1591 */
1592 type VerifyClientCallbackAsync = (
1593 info: { origin: string; secure: boolean; req: IncomingMessage },
1594 callback: (
1595 res: boolean,
1596 code?: number,
1597 message?: string,
1598 headers?: OutgoingHttpHeaders,
1599 ) => void,
1600 ) => void
1601
1602 interface ClientOptions extends SecureContextOptions {
1603 protocol?: string | undefined
1604 followRedirects?: boolean | undefined
1605 generateMask?(mask: Buffer): void
1606 handshakeTimeout?: number | undefined
1607 maxRedirects?: number | undefined
1608 perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
1609 localAddress?: string | undefined
1610 protocolVersion?: number | undefined
1611 headers?: { [key: string]: string } | undefined
1612 origin?: string | undefined
1613 agent?: Agent | undefined
1614 host?: string | undefined
1615 family?: number | undefined
1616 checkServerIdentity?(servername: string, cert: CertMeta): boolean
1617 rejectUnauthorized?: boolean | undefined
1618 maxPayload?: number | undefined
1619 skipUTF8Validation?: boolean | undefined
1620 }
1621
1622 interface PerMessageDeflateOptions {
1623 serverNoContextTakeover?: boolean | undefined
1624 clientNoContextTakeover?: boolean | undefined
1625 serverMaxWindowBits?: number | undefined
1626 clientMaxWindowBits?: number | undefined
1627 zlibDeflateOptions?:
1628 | {
1629 flush?: number | undefined
1630 finishFlush?: number | undefined
1631 chunkSize?: number | undefined
1632 windowBits?: number | undefined
1633 level?: number | undefined
1634 memLevel?: number | undefined
1635 strategy?: number | undefined
1636 dictionary?: Buffer | Buffer[] | DataView | undefined
1637 info?: boolean | undefined
1638 }
1639 | undefined
1640 zlibInflateOptions?: ZlibOptions | undefined
1641 threshold?: number | undefined
1642 concurrencyLimit?: number | undefined
1643 }
1644
1645 interface Event {
1646 type: string
1647 target: WebSocket
1648 }
1649
1650 interface ErrorEvent {
1651 error: any
1652 message: string
1653 type: string
1654 target: WebSocket
1655 }
1656
1657 interface CloseEvent {
1658 wasClean: boolean
1659 code: number
1660 reason: string
1661 type: string
1662 target: WebSocket
1663 }
1664
1665 interface MessageEvent {
1666 data: Data
1667 type: string
1668 target: WebSocket
1669 }
1670
1671 interface EventListenerOptions {
1672 once?: boolean | undefined
1673 }
1674
1675 interface ServerOptions {
1676 host?: string | undefined
1677 port?: number | undefined
1678 backlog?: number | undefined
1679 server?: Server | HttpsServer | undefined
1680 verifyClient?:
1681 | VerifyClientCallbackAsync
1682 | VerifyClientCallbackSync
1683 | undefined
1684 handleProtocols?: (
1685 protocols: Set<string>,
1686 request: IncomingMessage,
1687 ) => string | false
1688 path?: string | undefined
1689 noServer?: boolean | undefined
1690 clientTracking?: boolean | undefined
1691 perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
1692 maxPayload?: number | undefined
1693 skipUTF8Validation?: boolean | undefined
1694 WebSocket?: typeof WebSocket.WebSocket | undefined
1695 }
1696
1697 interface AddressInfo {
1698 address: string
1699 family: string
1700 port: number
1701 }
1702
1703 // WebSocket Server
1704 class Server<T extends WebSocket = WebSocket> extends EventEmitter {
1705 options: ServerOptions
1706 path: string
1707 clients: Set<T>
1708
1709 constructor(options?: ServerOptions, callback?: () => void)
1710
1711 address(): AddressInfo | string
1712 close(cb?: (err?: Error) => void): void
1713 handleUpgrade(
1714 request: IncomingMessage,
1715 socket: Duplex,
1716 upgradeHead: Buffer,
1717 callback: (client: T, request: IncomingMessage) => void,
1718 ): void
1719 shouldHandle(request: IncomingMessage): boolean | Promise<boolean>
1720
1721 // Events
1722 on(
1723 event: 'connection',
1724 cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
1725 ): this
1726 on(event: 'error', cb: (this: Server<T>, error: Error) => void): this
1727 on(
1728 event: 'headers',
1729 cb: (
1730 this: Server<T>,
1731 headers: string[],
1732 request: IncomingMessage,
1733 ) => void,
1734 ): this
1735 on(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
1736 on(
1737 event: string | symbol,
1738 listener: (this: Server<T>, ...args: any[]) => void,
1739 ): this
1740
1741 once(
1742 event: 'connection',
1743 cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
1744 ): this
1745 once(event: 'error', cb: (this: Server<T>, error: Error) => void): this
1746 once(
1747 event: 'headers',
1748 cb: (
1749 this: Server<T>,
1750 headers: string[],
1751 request: IncomingMessage,
1752 ) => void,
1753 ): this
1754 once(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
1755 once(
1756 event: string | symbol,
1757 listener: (this: Server<T>, ...args: any[]) => void,
1758 ): this
1759
1760 off(
1761 event: 'connection',
1762 cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
1763 ): this
1764 off(event: 'error', cb: (this: Server<T>, error: Error) => void): this
1765 off(
1766 event: 'headers',
1767 cb: (
1768 this: Server<T>,
1769 headers: string[],
1770 request: IncomingMessage,
1771 ) => void,
1772 ): this
1773 off(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
1774 off(
1775 event: string | symbol,
1776 listener: (this: Server<T>, ...args: any[]) => void,
1777 ): this
1778
1779 addListener(
1780 event: 'connection',
1781 cb: (client: T, request: IncomingMessage) => void,
1782 ): this
1783 addListener(event: 'error', cb: (err: Error) => void): this
1784 addListener(
1785 event: 'headers',
1786 cb: (headers: string[], request: IncomingMessage) => void,
1787 ): this
1788 addListener(event: 'close' | 'listening', cb: () => void): this
1789 addListener(
1790 event: string | symbol,
1791 listener: (...args: any[]) => void,
1792 ): this
1793
1794 removeListener(event: 'connection', cb: (client: T) => void): this
1795 removeListener(event: 'error', cb: (err: Error) => void): this
1796 removeListener(
1797 event: 'headers',
1798 cb: (headers: string[], request: IncomingMessage) => void,
1799 ): this
1800 removeListener(event: 'close' | 'listening', cb: () => void): this
1801 removeListener(
1802 event: string | symbol,
1803 listener: (...args: any[]) => void,
1804 ): this
1805 }
1806
1807 const WebSocketServer: typeof Server
1808 interface WebSocketServer extends Server {}
1809 const WebSocket: typeof WebSocketAlias
1810 interface WebSocket extends WebSocketAlias {}
1811
1812 // WebSocket stream
1813 function createWebSocketStream(
1814 websocket: WebSocket,
1815 options?: DuplexOptions,
1816 ): Duplex
1817}
1818
1819type WebSocketCustomListener<T> = (data: T, client: WebSocketClient, invoke?: 'send' | `send:${string}`) => void;
1820declare const isWebSocketServer: unique symbol;
1821interface WebSocketServer extends NormalizedHotChannel {
1822 /**
1823 * Handle custom event emitted by `import.meta.hot.send`
1824 */
1825 on: WebSocket.Server['on'] & {
1826 <T extends string>(event: T, listener: WebSocketCustomListener<InferCustomEventPayload<T>>): void;
1827 };
1828 /**
1829 * Unregister event listener.
1830 */
1831 off: WebSocket.Server['off'] & {
1832 (event: string, listener: Function): void;
1833 };
1834 /**
1835 * Listen on port and host
1836 */
1837 listen(): void;
1838 /**
1839 * Disconnect all clients and terminate the server.
1840 */
1841 close(): Promise<void>;
1842 [isWebSocketServer]: true;
1843 /**
1844 * Get all connected clients.
1845 */
1846 clients: Set<WebSocketClient>;
1847}
1848interface WebSocketClient extends NormalizedHotChannelClient {
1849 /**
1850 * The raw WebSocket instance
1851 * @advanced
1852 */
1853 socket: WebSocket;
1854}
1855
1856interface DevEnvironmentContext {
1857 hot: boolean;
1858 transport?: HotChannel | WebSocketServer;
1859 options?: EnvironmentOptions;
1860 remoteRunner?: {
1861 inlineSourceMap?: boolean;
1862 };
1863 depsOptimizer?: DepsOptimizer;
1864}
1865declare class DevEnvironment extends BaseEnvironment {
1866 mode: "dev";
1867 moduleGraph: EnvironmentModuleGraph;
1868 depsOptimizer?: DepsOptimizer;
1869 get pluginContainer(): EnvironmentPluginContainer;
1870 /**
1871 * Hot channel for this environment. If not provided or disabled,
1872 * it will be a noop channel that does nothing.
1873 *
1874 * @example
1875 * environment.hot.send({ type: 'full-reload' })
1876 */
1877 hot: NormalizedHotChannel;
1878 constructor(name: string, config: ResolvedConfig, context: DevEnvironmentContext);
1879 init(options?: {
1880 watcher?: FSWatcher;
1881 /**
1882 * the previous instance used for the environment with the same name
1883 *
1884 * when using, the consumer should check if it's an instance generated from the same class or factory function
1885 */
1886 previousInstance?: DevEnvironment;
1887 }): Promise<void>;
1888 /**
1889 * When the dev server is restarted, the methods are called in the following order:
1890 * - new instance `init`
1891 * - previous instance `close`
1892 * - new instance `listen`
1893 */
1894 listen(server: ViteDevServer): Promise<void>;
1895 fetchModule(id: string, importer?: string, options?: FetchFunctionOptions): Promise<FetchResult>;
1896 reloadModule(module: EnvironmentModuleNode): Promise<void>;
1897 transformRequest(url: string): Promise<TransformResult | null>;
1898 warmupRequest(url: string): Promise<void>;
1899 close(): Promise<void>;
1900 /**
1901 * Calling `await environment.waitForRequestsIdle(id)` will wait until all static imports
1902 * are processed after the first transformRequest call. If called from a load or transform
1903 * plugin hook, the id needs to be passed as a parameter to avoid deadlocks.
1904 * Calling this function after the first static imports section of the module graph has been
1905 * processed will resolve immediately.
1906 * @experimental
1907 */
1908 waitForRequestsIdle(ignoredId?: string): Promise<void>;
1909}
1910
1911interface RollupCommonJSOptions {
1912 /**
1913 * A minimatch pattern, or array of patterns, which specifies the files in
1914 * the build the plugin should operate on. By default, all files with
1915 * extension `".cjs"` or those in `extensions` are included, but you can
1916 * narrow this list by only including specific files. These files will be
1917 * analyzed and transpiled if either the analysis does not find ES module
1918 * specific statements or `transformMixedEsModules` is `true`.
1919 * @default undefined
1920 */
1921 include?: string | RegExp | readonly (string | RegExp)[]
1922 /**
1923 * A minimatch pattern, or array of patterns, which specifies the files in
1924 * the build the plugin should _ignore_. By default, all files with
1925 * extensions other than those in `extensions` or `".cjs"` are ignored, but you
1926 * can exclude additional files. See also the `include` option.
1927 * @default undefined
1928 */
1929 exclude?: string | RegExp | readonly (string | RegExp)[]
1930 /**
1931 * For extensionless imports, search for extensions other than .js in the
1932 * order specified. Note that you need to make sure that non-JavaScript files
1933 * are transpiled by another plugin first.
1934 * @default [ '.js' ]
1935 */
1936 extensions?: ReadonlyArray<string>
1937 /**
1938 * If true then uses of `global` won't be dealt with by this plugin
1939 * @default false
1940 */
1941 ignoreGlobal?: boolean
1942 /**
1943 * If false, skips source map generation for CommonJS modules. This will
1944 * improve performance.
1945 * @default true
1946 */
1947 sourceMap?: boolean
1948 /**
1949 * Some `require` calls cannot be resolved statically to be translated to
1950 * imports.
1951 * When this option is set to `false`, the generated code will either
1952 * directly throw an error when such a call is encountered or, when
1953 * `dynamicRequireTargets` is used, when such a call cannot be resolved with a
1954 * configured dynamic require target.
1955 * Setting this option to `true` will instead leave the `require` call in the
1956 * code or use it as a fallback for `dynamicRequireTargets`.
1957 * @default false
1958 */
1959 ignoreDynamicRequires?: boolean
1960 /**
1961 * Instructs the plugin whether to enable mixed module transformations. This
1962 * is useful in scenarios with modules that contain a mix of ES `import`
1963 * statements and CommonJS `require` expressions. Set to `true` if `require`
1964 * calls should be transformed to imports in mixed modules, or `false` if the
1965 * `require` expressions should survive the transformation. The latter can be
1966 * important if the code contains environment detection, or you are coding
1967 * for an environment with special treatment for `require` calls such as
1968 * ElectronJS. See also the `ignore` option.
1969 * @default false
1970 */
1971 transformMixedEsModules?: boolean
1972 /**
1973 * By default, this plugin will try to hoist `require` statements as imports
1974 * to the top of each file. While this works well for many code bases and
1975 * allows for very efficient ESM output, it does not perfectly capture
1976 * CommonJS semantics as the order of side effects like log statements may
1977 * change. But it is especially problematic when there are circular `require`
1978 * calls between CommonJS modules as those often rely on the lazy execution of
1979 * nested `require` calls.
1980 *
1981 * Setting this option to `true` will wrap all CommonJS files in functions
1982 * which are executed when they are required for the first time, preserving
1983 * NodeJS semantics. Note that this can have an impact on the size and
1984 * performance of the generated code.
1985 *
1986 * The default value of `"auto"` will only wrap CommonJS files when they are
1987 * part of a CommonJS dependency cycle, e.g. an index file that is required by
1988 * many of its dependencies. All other CommonJS files are hoisted. This is the
1989 * recommended setting for most code bases.
1990 *
1991 * `false` will entirely prevent wrapping and hoist all files. This may still
1992 * work depending on the nature of cyclic dependencies but will often cause
1993 * problems.
1994 *
1995 * You can also provide a minimatch pattern, or array of patterns, to only
1996 * specify a subset of files which should be wrapped in functions for proper
1997 * `require` semantics.
1998 *
1999 * `"debug"` works like `"auto"` but after bundling, it will display a warning
2000 * containing a list of ids that have been wrapped which can be used as
2001 * minimatch pattern for fine-tuning.
2002 * @default "auto"
2003 */
2004 strictRequires?: boolean | string | RegExp | readonly (string | RegExp)[]
2005 /**
2006 * Sometimes you have to leave require statements unconverted. Pass an array
2007 * containing the IDs or a `id => boolean` function.
2008 * @default []
2009 */
2010 ignore?: ReadonlyArray<string> | ((id: string) => boolean)
2011 /**
2012 * In most cases, where `require` calls are inside a `try-catch` clause,
2013 * they should be left unconverted as it requires an optional dependency
2014 * that may or may not be installed beside the rolled up package.
2015 * Due to the conversion of `require` to a static `import` - the call is
2016 * hoisted to the top of the file, outside the `try-catch` clause.
2017 *
2018 * - `true`: Default. All `require` calls inside a `try` will be left unconverted.
2019 * - `false`: All `require` calls inside a `try` will be converted as if the
2020 * `try-catch` clause is not there.
2021 * - `remove`: Remove all `require` calls from inside any `try` block.
2022 * - `string[]`: Pass an array containing the IDs to left unconverted.
2023 * - `((id: string) => boolean|'remove')`: Pass a function that controls
2024 * individual IDs.
2025 *
2026 * @default true
2027 */
2028 ignoreTryCatch?:
2029 | boolean
2030 | 'remove'
2031 | ReadonlyArray<string>
2032 | ((id: string) => boolean | 'remove')
2033 /**
2034 * Controls how to render imports from external dependencies. By default,
2035 * this plugin assumes that all external dependencies are CommonJS. This
2036 * means they are rendered as default imports to be compatible with e.g.
2037 * NodeJS where ES modules can only import a default export from a CommonJS
2038 * dependency.
2039 *
2040 * If you set `esmExternals` to `true`, this plugin assumes that all
2041 * external dependencies are ES modules and respect the
2042 * `requireReturnsDefault` option. If that option is not set, they will be
2043 * rendered as namespace imports.
2044 *
2045 * You can also supply an array of ids to be treated as ES modules, or a
2046 * function that will be passed each external id to determine whether it is
2047 * an ES module.
2048 * @default false
2049 */
2050 esmExternals?: boolean | ReadonlyArray<string> | ((id: string) => boolean)
2051 /**
2052 * Controls what is returned when requiring an ES module from a CommonJS file.
2053 * When using the `esmExternals` option, this will also apply to external
2054 * modules. By default, this plugin will render those imports as namespace
2055 * imports i.e.
2056 *
2057 * ```js
2058 * // input
2059 * const foo = require('foo');
2060 *
2061 * // output
2062 * import * as foo from 'foo';
2063 * ```
2064 *
2065 * However, there are some situations where this may not be desired.
2066 * For these situations, you can change Rollup's behaviour either globally or
2067 * per module. To change it globally, set the `requireReturnsDefault` option
2068 * to one of the following values:
2069 *
2070 * - `false`: This is the default, requiring an ES module returns its
2071 * namespace. This is the only option that will also add a marker
2072 * `__esModule: true` to the namespace to support interop patterns in
2073 * CommonJS modules that are transpiled ES modules.
2074 * - `"namespace"`: Like `false`, requiring an ES module returns its
2075 * namespace, but the plugin does not add the `__esModule` marker and thus
2076 * creates more efficient code. For external dependencies when using
2077 * `esmExternals: true`, no additional interop code is generated.
2078 * - `"auto"`: This is complementary to how `output.exports: "auto"` works in
2079 * Rollup: If a module has a default export and no named exports, requiring
2080 * that module returns the default export. In all other cases, the namespace
2081 * is returned. For external dependencies when using `esmExternals: true`, a
2082 * corresponding interop helper is added.
2083 * - `"preferred"`: If a module has a default export, requiring that module
2084 * always returns the default export, no matter whether additional named
2085 * exports exist. This is similar to how previous versions of this plugin
2086 * worked. Again for external dependencies when using `esmExternals: true`,
2087 * an interop helper is added.
2088 * - `true`: This will always try to return the default export on require
2089 * without checking if it actually exists. This can throw at build time if
2090 * there is no default export. This is how external dependencies are handled
2091 * when `esmExternals` is not used. The advantage over the other options is
2092 * that, like `false`, this does not add an interop helper for external
2093 * dependencies, keeping the code lean.
2094 *
2095 * To change this for individual modules, you can supply a function for
2096 * `requireReturnsDefault` instead. This function will then be called once for
2097 * each required ES module or external dependency with the corresponding id
2098 * and allows you to return different values for different modules.
2099 * @default false
2100 */
2101 requireReturnsDefault?:
2102 | boolean
2103 | 'auto'
2104 | 'preferred'
2105 | 'namespace'
2106 | ((id: string) => boolean | 'auto' | 'preferred' | 'namespace')
2107
2108 /**
2109 * @default "auto"
2110 */
2111 defaultIsModuleExports?: boolean | 'auto' | ((id: string) => boolean | 'auto')
2112 /**
2113 * Some modules contain dynamic `require` calls, or require modules that
2114 * contain circular dependencies, which are not handled well by static
2115 * imports. Including those modules as `dynamicRequireTargets` will simulate a
2116 * CommonJS (NodeJS-like) environment for them with support for dynamic
2117 * dependencies. It also enables `strictRequires` for those modules.
2118 *
2119 * Note: In extreme cases, this feature may result in some paths being
2120 * rendered as absolute in the final bundle. The plugin tries to avoid
2121 * exposing paths from the local machine, but if you are `dynamicRequirePaths`
2122 * with paths that are far away from your project's folder, that may require
2123 * replacing strings like `"/Users/John/Desktop/foo-project/"` -\> `"/"`.
2124 */
2125 dynamicRequireTargets?: string | ReadonlyArray<string>
2126 /**
2127 * To avoid long paths when using the `dynamicRequireTargets` option, you can use this option to specify a directory
2128 * that is a common parent for all files that use dynamic require statements. Using a directory higher up such as `/`
2129 * may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your
2130 * home directory name. By default, it uses the current working directory.
2131 */
2132 dynamicRequireRoot?: string
2133}
2134
2135interface RollupDynamicImportVarsOptions {
2136 /**
2137 * Files to include in this plugin (default all).
2138 * @default []
2139 */
2140 include?: string | RegExp | (string | RegExp)[]
2141 /**
2142 * Files to exclude in this plugin (default none).
2143 * @default []
2144 */
2145 exclude?: string | RegExp | (string | RegExp)[]
2146 /**
2147 * 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.
2148 * @default false
2149 */
2150 warnOnError?: boolean
2151}
2152
2153// Modified and inlined to avoid extra dependency
2154// Source: https://github.com/terser/terser/blob/master/tools/terser.d.ts
2155// BSD Licensed https://github.com/terser/terser/blob/master/LICENSE
2156
2157declare namespace Terser {
2158 export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020
2159
2160 export type ConsoleProperty = keyof typeof console
2161 type DropConsoleOption = boolean | ConsoleProperty[]
2162
2163 export interface ParseOptions {
2164 bare_returns?: boolean
2165 /** @deprecated legacy option. Currently, all supported EcmaScript is valid to parse. */
2166 ecma?: ECMA
2167 html5_comments?: boolean
2168 shebang?: boolean
2169 }
2170
2171 export interface CompressOptions {
2172 arguments?: boolean
2173 arrows?: boolean
2174 booleans_as_integers?: boolean
2175 booleans?: boolean
2176 collapse_vars?: boolean
2177 comparisons?: boolean
2178 computed_props?: boolean
2179 conditionals?: boolean
2180 dead_code?: boolean
2181 defaults?: boolean
2182 directives?: boolean
2183 drop_console?: DropConsoleOption
2184 drop_debugger?: boolean
2185 ecma?: ECMA
2186 evaluate?: boolean
2187 expression?: boolean
2188 global_defs?: object
2189 hoist_funs?: boolean
2190 hoist_props?: boolean
2191 hoist_vars?: boolean
2192 ie8?: boolean
2193 if_return?: boolean
2194 inline?: boolean | InlineFunctions
2195 join_vars?: boolean
2196 keep_classnames?: boolean | RegExp
2197 keep_fargs?: boolean
2198 keep_fnames?: boolean | RegExp
2199 keep_infinity?: boolean
2200 loops?: boolean
2201 module?: boolean
2202 negate_iife?: boolean
2203 passes?: number
2204 properties?: boolean
2205 pure_funcs?: string[]
2206 pure_new?: boolean
2207 pure_getters?: boolean | 'strict'
2208 reduce_funcs?: boolean
2209 reduce_vars?: boolean
2210 sequences?: boolean | number
2211 side_effects?: boolean
2212 switches?: boolean
2213 toplevel?: boolean
2214 top_retain?: null | string | string[] | RegExp
2215 typeofs?: boolean
2216 unsafe_arrows?: boolean
2217 unsafe?: boolean
2218 unsafe_comps?: boolean
2219 unsafe_Function?: boolean