You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4194 lines
149 KiB

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