index.d.ts 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907
  1. /// <reference types="node" />
  2. import type { Agent } from 'http';
  3. import type { BuildOptions as BuildOptions_2 } from 'esbuild';
  4. import type { ClientRequest } from 'http';
  5. import type { ClientRequestArgs } from 'http';
  6. import type { CustomPluginOptions } from 'rollup';
  7. import type { Duplex } from 'stream';
  8. import type { DuplexOptions } from 'stream';
  9. import { TransformOptions as EsbuildTransformOptions } from 'esbuild';
  10. import { EventEmitter } from 'events';
  11. import * as events from 'events';
  12. import type { ExistingRawSourceMap } from 'rollup';
  13. import type * as fs from 'fs';
  14. import type { GetManualChunk } from 'rollup';
  15. import * as http from 'http';
  16. import type { IncomingMessage } from 'http';
  17. import type { InputOptions } from 'rollup';
  18. import type { LoadResult } from 'rollup';
  19. import type { ModuleFormat } from 'rollup';
  20. import type { ModuleInfo } from 'rollup';
  21. import type * as net from 'net';
  22. import type { OutgoingHttpHeaders } from 'http';
  23. import type { OutputBundle } from 'rollup';
  24. import type { OutputChunk } from 'rollup';
  25. import type { PartialResolvedId } from 'rollup';
  26. import type { Plugin as Plugin_2 } from 'rollup';
  27. import type { PluginContext } from 'rollup';
  28. import type { PluginHooks } from 'rollup';
  29. import type * as PostCSS from 'postcss';
  30. import type { ResolveIdResult } from 'rollup';
  31. import type { RollupError } from 'rollup';
  32. import type { RollupOptions } from 'rollup';
  33. import type { RollupOutput } from 'rollup';
  34. import type { RollupWatcher } from 'rollup';
  35. import type { SecureContextOptions } from 'tls';
  36. import type { Server } from 'http';
  37. import type { Server as Server_2 } from 'https';
  38. import type { Server as Server_3 } from 'net';
  39. import type { ServerOptions as ServerOptions_2 } from 'https';
  40. import type { ServerResponse } from 'http';
  41. import type { SourceDescription } from 'rollup';
  42. import type { SourceMap } from 'rollup';
  43. import type * as stream from 'stream';
  44. import type { TransformPluginContext } from 'rollup';
  45. import type { TransformResult as TransformResult_2 } from 'esbuild';
  46. import type { TransformResult as TransformResult_3 } from 'rollup';
  47. import type * as url from 'url';
  48. import type { URL as URL_2 } from 'url';
  49. import type { WatcherOptions } from 'rollup';
  50. import type { ZlibOptions } from 'zlib';
  51. export declare interface Alias {
  52. find: string | RegExp
  53. replacement: string
  54. /**
  55. * Instructs the plugin to use an alternative resolving algorithm,
  56. * rather than the Rollup's resolver.
  57. * @default null
  58. */
  59. customResolver?: ResolverFunction | ResolverObject | null
  60. }
  61. /**
  62. * Specifies an `Object`, or an `Array` of `Object`,
  63. * which defines aliases used to replace values in `import` or `require` statements.
  64. * With either format, the order of the entries is important,
  65. * in that the first defined rules are applied first.
  66. *
  67. * This is passed to \@rollup/plugin-alias as the "entries" field
  68. * https://github.com/rollup/plugins/tree/master/packages/alias#entries
  69. */
  70. export declare type AliasOptions = readonly Alias[] | { [find: string]: string }
  71. export declare type AnymatchFn = (testString: string) => boolean
  72. export declare type AnymatchPattern = string | RegExp | AnymatchFn
  73. export declare interface AwaitWriteFinishOptions {
  74. /**
  75. * Amount of time in milliseconds for a file size to remain constant before emitting its event.
  76. */
  77. stabilityThreshold?: number
  78. /**
  79. * File size polling interval.
  80. */
  81. pollInterval?: number
  82. }
  83. /**
  84. * Bundles the app for production.
  85. * Returns a Promise containing the build result.
  86. */
  87. export declare function build(inlineConfig?: InlineConfig): Promise<RollupOutput | RollupOutput[] | RollupWatcher>;
  88. export declare interface BuildOptions {
  89. /**
  90. * Base public path when served in production.
  91. * @deprecated `base` is now a root-level config option.
  92. */
  93. base?: string;
  94. /**
  95. * Compatibility transform target. The transform is performed with esbuild
  96. * and the lowest supported target is es2015/es6. Note this only handles
  97. * syntax transformation and does not cover polyfills (except for dynamic
  98. * import)
  99. *
  100. * Default: 'modules' - Similar to `@babel/preset-env`'s targets.esmodules,
  101. * transpile targeting browsers that natively support dynamic es module imports.
  102. * https://caniuse.com/es6-module-dynamic-import
  103. *
  104. * Another special value is 'esnext' - which only performs minimal transpiling
  105. * (for minification compat) and assumes native dynamic imports support.
  106. *
  107. * For custom targets, see https://esbuild.github.io/api/#target and
  108. * https://esbuild.github.io/content-types/#javascript for more details.
  109. */
  110. target?: 'modules' | EsbuildTransformOptions['target'] | false;
  111. /**
  112. * whether to inject module preload polyfill.
  113. * Note: does not apply to library mode.
  114. * @default true
  115. */
  116. polyfillModulePreload?: boolean;
  117. /**
  118. * whether to inject dynamic import polyfill.
  119. * Note: does not apply to library mode.
  120. * @default false
  121. * @deprecated use plugin-legacy for browsers that don't support dynamic import
  122. */
  123. polyfillDynamicImport?: boolean;
  124. /**
  125. * Directory relative from `root` where build output will be placed. If the
  126. * directory exists, it will be removed before the build.
  127. * @default 'dist'
  128. */
  129. outDir?: string;
  130. /**
  131. * Directory relative from `outDir` where the built js/css/image assets will
  132. * be placed.
  133. * @default 'assets'
  134. */
  135. assetsDir?: string;
  136. /**
  137. * Static asset files smaller than this number (in bytes) will be inlined as
  138. * base64 strings. Default limit is `4096` (4kb). Set to `0` to disable.
  139. * @default 4096
  140. */
  141. assetsInlineLimit?: number;
  142. /**
  143. * Whether to code-split CSS. When enabled, CSS in async chunks will be
  144. * inlined as strings in the chunk and inserted via dynamically created
  145. * style tags when the chunk is loaded.
  146. * @default true
  147. */
  148. cssCodeSplit?: boolean;
  149. /**
  150. * An optional separate target for CSS minification.
  151. * As esbuild only supports configuring targets to mainstream
  152. * browsers, users may need this option when they are targeting
  153. * a niche browser that comes with most modern JavaScript features
  154. * but has poor CSS support, e.g. Android WeChat WebView, which
  155. * doesn't support the #RGBA syntax.
  156. */
  157. cssTarget?: EsbuildTransformOptions['target'] | false;
  158. /**
  159. * If `true`, a separate sourcemap file will be created. If 'inline', the
  160. * sourcemap will be appended to the resulting output file as data URI.
  161. * 'hidden' works like `true` except that the corresponding sourcemap
  162. * comments in the bundled files are suppressed.
  163. * @default false
  164. */
  165. sourcemap?: boolean | 'inline' | 'hidden';
  166. /**
  167. * Set to `false` to disable minification, or specify the minifier to use.
  168. * Available options are 'terser' or 'esbuild'.
  169. * @default 'esbuild'
  170. */
  171. minify?: boolean | 'terser' | 'esbuild';
  172. /**
  173. * Options for terser
  174. * https://terser.org/docs/api-reference#minify-options
  175. */
  176. terserOptions?: Terser.MinifyOptions;
  177. /**
  178. * @deprecated Vite now uses esbuild for CSS minification.
  179. */
  180. cleanCssOptions?: any;
  181. /**
  182. * Will be merged with internal rollup options.
  183. * https://rollupjs.org/guide/en/#big-list-of-options
  184. */
  185. rollupOptions?: RollupOptions;
  186. /**
  187. * Options to pass on to `@rollup/plugin-commonjs`
  188. */
  189. commonjsOptions?: RollupCommonJSOptions;
  190. /**
  191. * Options to pass on to `@rollup/plugin-dynamic-import-vars`
  192. */
  193. dynamicImportVarsOptions?: RollupDynamicImportVarsOptions;
  194. /**
  195. * Whether to write bundle to disk
  196. * @default true
  197. */
  198. write?: boolean;
  199. /**
  200. * Empty outDir on write.
  201. * @default true when outDir is a sub directory of project root
  202. */
  203. emptyOutDir?: boolean | null;
  204. /**
  205. * Whether to emit a manifest.json under assets dir to map hash-less filenames
  206. * to their hashed versions. Useful when you want to generate your own HTML
  207. * instead of using the one generated by Vite.
  208. *
  209. * Example:
  210. *
  211. * ```json
  212. * {
  213. * "main.js": {
  214. * "file": "main.68fe3fad.js",
  215. * "css": "main.e6b63442.css",
  216. * "imports": [...],
  217. * "dynamicImports": [...]
  218. * }
  219. * }
  220. * ```
  221. * @default false
  222. */
  223. manifest?: boolean | string;
  224. /**
  225. * Build in library mode. The value should be the global name of the lib in
  226. * UMD mode. This will produce esm + cjs + umd bundle formats with default
  227. * configurations that are suitable for distributing libraries.
  228. */
  229. lib?: LibraryOptions | false;
  230. /**
  231. * Produce SSR oriented build. Note this requires specifying SSR entry via
  232. * `rollupOptions.input`.
  233. */
  234. ssr?: boolean | string;
  235. /**
  236. * Generate SSR manifest for determining style links and asset preload
  237. * directives in production.
  238. */
  239. ssrManifest?: boolean | string;
  240. /**
  241. * Set to false to disable reporting compressed chunk sizes.
  242. * Can slightly improve build speed.
  243. */
  244. reportCompressedSize?: boolean;
  245. /**
  246. * Set to false to disable brotli compressed size reporting for build.
  247. * Can slightly improve build speed.
  248. * @deprecated use `build.reportCompressedSize` instead.
  249. */
  250. brotliSize?: boolean;
  251. /**
  252. * Adjust chunk size warning limit (in kbs).
  253. * @default 500
  254. */
  255. chunkSizeWarningLimit?: number;
  256. /**
  257. * Rollup watch options
  258. * https://rollupjs.org/guide/en/#watchoptions
  259. */
  260. watch?: WatcherOptions | null;
  261. }
  262. export declare interface ChunkMetadata {
  263. importedAssets: Set<string>;
  264. importedCss: Set<string>;
  265. }
  266. export declare interface CommonServerOptions {
  267. /**
  268. * Specify server port. Note if the port is already being used, Vite will
  269. * automatically try the next available port so this may not be the actual
  270. * port the server ends up listening on.
  271. */
  272. port?: number;
  273. /**
  274. * If enabled, vite will exit if specified port is already in use
  275. */
  276. strictPort?: boolean;
  277. /**
  278. * Specify which IP addresses the server should listen on.
  279. * Set to 0.0.0.0 to listen on all addresses, including LAN and public addresses.
  280. */
  281. host?: string | boolean;
  282. /**
  283. * Enable TLS + HTTP/2.
  284. * Note: this downgrades to TLS only when the proxy option is also used.
  285. */
  286. https?: boolean | ServerOptions_2;
  287. /**
  288. * Open browser window on startup
  289. */
  290. open?: boolean | string;
  291. /**
  292. * Configure custom proxy rules for the dev server. Expects an object
  293. * of `{ key: options }` pairs.
  294. * Uses [`http-proxy`](https://github.com/http-party/node-http-proxy).
  295. * Full options [here](https://github.com/http-party/node-http-proxy#options).
  296. *
  297. * Example `vite.config.js`:
  298. * ``` js
  299. * module.exports = {
  300. * proxy: {
  301. * // string shorthand
  302. * '/foo': 'http://localhost:4567/foo',
  303. * // with options
  304. * '/api': {
  305. * target: 'http://jsonplaceholder.typicode.com',
  306. * changeOrigin: true,
  307. * rewrite: path => path.replace(/^\/api/, '')
  308. * }
  309. * }
  310. * }
  311. * ```
  312. */
  313. proxy?: Record<string, string | ProxyOptions>;
  314. /**
  315. * Configure CORS for the dev server.
  316. * Uses https://github.com/expressjs/cors.
  317. * Set to `true` to allow all methods from any origin, or configure separately
  318. * using an object.
  319. */
  320. cors?: CorsOptions | boolean;
  321. /**
  322. * Specify server response headers.
  323. */
  324. headers?: OutgoingHttpHeaders;
  325. }
  326. export declare interface ConfigEnv {
  327. command: 'build' | 'serve';
  328. mode: string;
  329. }
  330. export declare namespace Connect {
  331. export type ServerHandle = HandleFunction | http.Server
  332. export class IncomingMessage extends http.IncomingMessage {
  333. originalUrl?: http.IncomingMessage['url']
  334. }
  335. export type NextFunction = (err?: any) => void
  336. export type SimpleHandleFunction = (
  337. req: IncomingMessage,
  338. res: http.ServerResponse
  339. ) => void
  340. export type NextHandleFunction = (
  341. req: IncomingMessage,
  342. res: http.ServerResponse,
  343. next: NextFunction
  344. ) => void
  345. export type ErrorHandleFunction = (
  346. err: any,
  347. req: IncomingMessage,
  348. res: http.ServerResponse,
  349. next: NextFunction
  350. ) => void
  351. export type HandleFunction =
  352. | SimpleHandleFunction
  353. | NextHandleFunction
  354. | ErrorHandleFunction
  355. export interface ServerStackItem {
  356. route: string
  357. handle: ServerHandle
  358. }
  359. export interface Server extends NodeJS.EventEmitter {
  360. (req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void
  361. route: string
  362. stack: ServerStackItem[]
  363. /**
  364. * Utilize the given middleware `handle` to the given `route`,
  365. * defaulting to _/_. This "route" is the mount-point for the
  366. * middleware, when given a value other than _/_ the middleware
  367. * is only effective when that segment is present in the request's
  368. * pathname.
  369. *
  370. * For example if we were to mount a function at _/admin_, it would
  371. * be invoked on _/admin_, and _/admin/settings_, however it would
  372. * not be invoked for _/_, or _/posts_.
  373. */
  374. use(fn: NextHandleFunction): Server
  375. use(fn: HandleFunction): Server
  376. use(route: string, fn: NextHandleFunction): Server
  377. use(route: string, fn: HandleFunction): Server
  378. /**
  379. * Handle server requests, punting them down
  380. * the middleware stack.
  381. */
  382. handle(
  383. req: http.IncomingMessage,
  384. res: http.ServerResponse,
  385. next: Function
  386. ): void
  387. /**
  388. * Listen for connections.
  389. *
  390. * This method takes the same arguments
  391. * as node's `http.Server#listen()`.
  392. *
  393. * HTTP and HTTPS:
  394. *
  395. * If you run your application both as HTTP
  396. * and HTTPS you may wrap them individually,
  397. * since your Connect "server" is really just
  398. * a JavaScript `Function`.
  399. *
  400. * var connect = require('connect')
  401. * , http = require('http')
  402. * , https = require('https');
  403. *
  404. * var app = connect();
  405. *
  406. * http.createServer(app).listen(80);
  407. * https.createServer(options, app).listen(443);
  408. */
  409. listen(
  410. port: number,
  411. hostname?: string,
  412. backlog?: number,
  413. callback?: Function
  414. ): http.Server
  415. listen(port: number, hostname?: string, callback?: Function): http.Server
  416. listen(path: string, callback?: Function): http.Server
  417. listen(handle: any, listeningListener?: Function): http.Server
  418. }
  419. }
  420. export declare interface ConnectedPayload {
  421. type: 'connected'
  422. }
  423. /**
  424. * https://github.com/expressjs/cors#configuration-options
  425. */
  426. export declare interface CorsOptions {
  427. origin?: CorsOrigin | ((origin: string, cb: (err: Error, origins: CorsOrigin) => void) => void);
  428. methods?: string | string[];
  429. allowedHeaders?: string | string[];
  430. exposedHeaders?: string | string[];
  431. credentials?: boolean;
  432. maxAge?: number;
  433. preflightContinue?: boolean;
  434. optionsSuccessStatus?: number;
  435. }
  436. export declare type CorsOrigin = boolean | string | RegExp | (string | RegExp)[];
  437. export declare function createLogger(level?: LogLevel, options?: LoggerOptions): Logger;
  438. export declare function createServer(inlineConfig?: InlineConfig): Promise<ViteDevServer>;
  439. export declare interface CSSModulesOptions {
  440. getJSON?: (cssFileName: string, json: Record<string, string>, outputFileName: string) => void;
  441. scopeBehaviour?: 'global' | 'local';
  442. globalModulePaths?: RegExp[];
  443. generateScopedName?: string | ((name: string, filename: string, css: string) => string);
  444. hashPrefix?: string;
  445. /**
  446. * default: null
  447. */
  448. localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly' | null;
  449. }
  450. export declare interface CSSOptions {
  451. /**
  452. * https://github.com/css-modules/postcss-modules
  453. */
  454. modules?: CSSModulesOptions | false;
  455. preprocessorOptions?: Record<string, any>;
  456. postcss?: string | (PostCSS.ProcessOptions & {
  457. plugins?: PostCSS.Plugin[];
  458. });
  459. /**
  460. * Enables css sourcemaps during dev
  461. * @default false
  462. * @experimental
  463. */
  464. devSourcemap?: boolean;
  465. }
  466. export declare interface CustomEventMap {
  467. 'vite:beforeUpdate': UpdatePayload
  468. 'vite:beforePrune': PrunePayload
  469. 'vite:beforeFullReload': FullReloadPayload
  470. 'vite:error': ErrorPayload
  471. }
  472. export declare interface CustomPayload {
  473. type: 'custom'
  474. event: string
  475. data?: any
  476. }
  477. /**
  478. * Type helper to make it easier to use vite.config.ts
  479. * accepts a direct {@link UserConfig} object, or a function that returns it.
  480. * The function receives a {@link ConfigEnv} object that exposes two properties:
  481. * `command` (either `'build'` or `'serve'`), and `mode`.
  482. */
  483. export declare function defineConfig(config: UserConfigExport): UserConfigExport;
  484. export declare interface DepOptimizationMetadata {
  485. /**
  486. * The main hash is determined by user config and dependency lockfiles.
  487. * This is checked on server startup to avoid unnecessary re-bundles.
  488. */
  489. hash: string;
  490. /**
  491. * The browser hash is determined by the main hash plus additional dependencies
  492. * discovered at runtime. This is used to invalidate browser requests to
  493. * optimized deps.
  494. */
  495. browserHash: string;
  496. /**
  497. * Metadata for each already optimized dependency
  498. */
  499. optimized: Record<string, OptimizedDepInfo>;
  500. /**
  501. * Metadata for non-entry optimized chunks and dynamic imports
  502. */
  503. chunks: Record<string, OptimizedDepInfo>;
  504. /**
  505. * Metadata for each newly discovered dependency after processing
  506. */
  507. discovered: Record<string, OptimizedDepInfo>;
  508. /**
  509. * OptimizedDepInfo list
  510. */
  511. depInfoList: OptimizedDepInfo[];
  512. }
  513. export declare interface DepOptimizationOptions {
  514. /**
  515. * By default, Vite will crawl your `index.html` to detect dependencies that
  516. * need to be pre-bundled. If `build.rollupOptions.input` is specified, Vite
  517. * will crawl those entry points instead.
  518. *
  519. * If neither of these fit your needs, you can specify custom entries using
  520. * this option - the value should be a fast-glob pattern or array of patterns
  521. * (https://github.com/mrmlnc/fast-glob#basic-syntax) that are relative from
  522. * vite project root. This will overwrite default entries inference.
  523. */
  524. entries?: string | string[];
  525. /**
  526. * Force optimize listed dependencies (must be resolvable import paths,
  527. * cannot be globs).
  528. */
  529. include?: string[];
  530. /**
  531. * Do not optimize these dependencies (must be resolvable import paths,
  532. * cannot be globs).
  533. */
  534. exclude?: string[];
  535. /**
  536. * Options to pass to esbuild during the dep scanning and optimization
  537. *
  538. * Certain options are omitted since changing them would not be compatible
  539. * with Vite's dep optimization.
  540. *
  541. * - `external` is also omitted, use Vite's `optimizeDeps.exclude` option
  542. * - `plugins` are merged with Vite's dep plugin
  543. * - `keepNames` takes precedence over the deprecated `optimizeDeps.keepNames`
  544. *
  545. * https://esbuild.github.io/api
  546. */
  547. esbuildOptions?: Omit<BuildOptions_2, 'bundle' | 'entryPoints' | 'external' | 'write' | 'watch' | 'outdir' | 'outfile' | 'outbase' | 'outExtension' | 'metafile'>;
  548. /**
  549. * @deprecated use `esbuildOptions.keepNames`
  550. */
  551. keepNames?: boolean;
  552. /**
  553. * List of file extensions that can be optimized. A corresponding esbuild
  554. * plugin must exist to handle the specific extension.
  555. *
  556. * By default, Vite can optimize `.mjs`, `.js`, and `.ts` files. This option
  557. * allows specifying additional extensions.
  558. *
  559. * @experimental
  560. */
  561. extensions?: string[];
  562. /**
  563. * Disables dependencies optimizations
  564. * @default false
  565. * @experimental
  566. */
  567. disabled?: boolean;
  568. }
  569. export declare interface DepOptimizationProcessing {
  570. promise: Promise<void>;
  571. resolve: () => void;
  572. }
  573. export declare interface DepOptimizationResult {
  574. metadata: DepOptimizationMetadata;
  575. /**
  576. * When doing a re-run, if there are newly discovered dependendencies
  577. * the page reload will be delayed until the next rerun so we need
  578. * to be able to discard the result
  579. */
  580. commit: () => Promise<void>;
  581. cancel: () => void;
  582. }
  583. export declare interface ErrorPayload {
  584. type: 'error'
  585. err: {
  586. [name: string]: any
  587. message: string
  588. stack: string
  589. id?: string
  590. frame?: string
  591. plugin?: string
  592. pluginCode?: string
  593. loc?: {
  594. file?: string
  595. line: number
  596. column: number
  597. }
  598. }
  599. }
  600. export declare interface ESBuildOptions extends EsbuildTransformOptions {
  601. include?: string | RegExp | string[] | RegExp[];
  602. exclude?: string | RegExp | string[] | RegExp[];
  603. jsxInject?: string;
  604. }
  605. export { EsbuildTransformOptions }
  606. export declare type ESBuildTransformResult = Omit<TransformResult_2, 'map'> & {
  607. map: SourceMap;
  608. };
  609. export declare interface FileSystemServeOptions {
  610. /**
  611. * Strictly restrict file accessing outside of allowing paths.
  612. *
  613. * Set to `false` to disable the warning
  614. *
  615. * @default true
  616. */
  617. strict?: boolean;
  618. /**
  619. * Restrict accessing files outside the allowed directories.
  620. *
  621. * Accepts absolute path or a path relative to project root.
  622. * Will try to search up for workspace root by default.
  623. */
  624. allow?: string[];
  625. /**
  626. * Restrict accessing files that matches the patterns.
  627. *
  628. * This will have higher priority than `allow`.
  629. * Glob patterns are supported.
  630. *
  631. * @default ['.env', '.env.*', '*.crt', '*.pem']
  632. *
  633. * @experimental
  634. */
  635. deny?: string[];
  636. }
  637. export declare function formatPostcssSourceMap(rawMap: ExistingRawSourceMap, file: string): ExistingRawSourceMap;
  638. export declare class FSWatcher extends EventEmitter implements fs.FSWatcher {
  639. options: WatchOptions
  640. /**
  641. * Constructs a new FSWatcher instance with optional WatchOptions parameter.
  642. */
  643. constructor(options?: WatchOptions)
  644. /**
  645. * Add files, directories, or glob patterns for tracking. Takes an array of strings or just one
  646. * string.
  647. */
  648. add(paths: string | ReadonlyArray<string>): this
  649. /**
  650. * Stop watching files, directories, or glob patterns. Takes an array of strings or just one
  651. * string.
  652. */
  653. unwatch(paths: string | ReadonlyArray<string>): this
  654. /**
  655. * Returns an object representing all the paths on the file system being watched by this
  656. * `FSWatcher` instance. The object's keys are all the directories (using absolute paths unless
  657. * the `cwd` option was used), and the values are arrays of the names of the items contained in
  658. * each directory.
  659. */
  660. getWatched(): {
  661. [directory: string]: string[]
  662. }
  663. /**
  664. * Removes all listeners from watched files.
  665. */
  666. close(): Promise<void>
  667. on(
  668. event: 'add' | 'addDir' | 'change',
  669. listener: (path: string, stats?: fs.Stats) => void
  670. ): this
  671. on(
  672. event: 'all',
  673. listener: (
  674. eventName: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir',
  675. path: string,
  676. stats?: fs.Stats
  677. ) => void
  678. ): this
  679. /**
  680. * Error occurred
  681. */
  682. on(event: 'error', listener: (error: Error) => void): this
  683. /**
  684. * Exposes the native Node `fs.FSWatcher events`
  685. */
  686. on(
  687. event: 'raw',
  688. listener: (eventName: string, path: string, details: any) => void
  689. ): this
  690. /**
  691. * Fires when the initial scan is complete
  692. */
  693. on(event: 'ready', listener: () => void): this
  694. on(event: 'unlink' | 'unlinkDir', listener: (path: string) => void): this
  695. on(event: string, listener: (...args: any[]) => void): this
  696. }
  697. export declare interface FullReloadPayload {
  698. type: 'full-reload'
  699. path?: string
  700. }
  701. export declare interface HmrContext {
  702. file: string;
  703. timestamp: number;
  704. modules: Array<ModuleNode>;
  705. read: () => string | Promise<string>;
  706. server: ViteDevServer;
  707. }
  708. export declare interface HmrOptions {
  709. protocol?: string;
  710. host?: string;
  711. port?: number;
  712. clientPort?: number;
  713. path?: string;
  714. timeout?: number;
  715. overlay?: boolean;
  716. server?: Server;
  717. }
  718. export declare type HMRPayload =
  719. | ConnectedPayload
  720. | UpdatePayload
  721. | FullReloadPayload
  722. | CustomPayload
  723. | ErrorPayload
  724. | PrunePayload
  725. export declare interface HtmlTagDescriptor {
  726. tag: string;
  727. attrs?: Record<string, string | boolean | undefined>;
  728. children?: string | HtmlTagDescriptor[];
  729. /**
  730. * default: 'head-prepend'
  731. */
  732. injectTo?: 'head' | 'body' | 'head-prepend' | 'body-prepend';
  733. }
  734. export declare namespace HttpProxy {
  735. export type ProxyTarget = ProxyTargetUrl | ProxyTargetDetailed
  736. export type ProxyTargetUrl = string | Partial<url.Url>
  737. export interface ProxyTargetDetailed {
  738. host: string
  739. port: number
  740. protocol?: string
  741. hostname?: string
  742. socketPath?: string
  743. key?: string
  744. passphrase?: string
  745. pfx?: Buffer | string
  746. cert?: string
  747. ca?: string
  748. ciphers?: string
  749. secureProtocol?: string
  750. }
  751. export type ErrorCallback = (
  752. err: Error,
  753. req: http.IncomingMessage,
  754. res: http.ServerResponse,
  755. target?: ProxyTargetUrl
  756. ) => void
  757. export class Server extends events.EventEmitter {
  758. /**
  759. * Creates the proxy server with specified options.
  760. * @param options - Config object passed to the proxy
  761. */
  762. constructor(options?: ServerOptions)
  763. /**
  764. * Used for proxying regular HTTP(S) requests
  765. * @param req - Client request.
  766. * @param res - Client response.
  767. * @param options - Additionnal options.
  768. */
  769. web(
  770. req: http.IncomingMessage,
  771. res: http.ServerResponse,
  772. options?: ServerOptions,
  773. callback?: ErrorCallback
  774. ): void
  775. /**
  776. * Used for proxying regular HTTP(S) requests
  777. * @param req - Client request.
  778. * @param socket - Client socket.
  779. * @param head - Client head.
  780. * @param options - Additional options.
  781. */
  782. ws(
  783. req: http.IncomingMessage,
  784. socket: unknown,
  785. head: unknown,
  786. options?: ServerOptions,
  787. callback?: ErrorCallback
  788. ): void
  789. /**
  790. * A function that wraps the object in a webserver, for your convenience
  791. * @param port - Port to listen on
  792. */
  793. listen(port: number): Server
  794. /**
  795. * A function that closes the inner webserver and stops listening on given port
  796. */
  797. close(callback?: () => void): void
  798. /**
  799. * Creates the proxy server with specified options.
  800. * @param options - Config object passed to the proxy
  801. * @returns Proxy object with handlers for `ws` and `web` requests
  802. */
  803. static createProxyServer(options?: ServerOptions): Server
  804. /**
  805. * Creates the proxy server with specified options.
  806. * @param options - Config object passed to the proxy
  807. * @returns Proxy object with handlers for `ws` and `web` requests
  808. */
  809. static createServer(options?: ServerOptions): Server
  810. /**
  811. * Creates the proxy server with specified options.
  812. * @param options - Config object passed to the proxy
  813. * @returns Proxy object with handlers for `ws` and `web` requests
  814. */
  815. static createProxy(options?: ServerOptions): Server
  816. addListener(event: string, listener: () => void): this
  817. on(event: string, listener: () => void): this
  818. on(event: 'error', listener: ErrorCallback): this
  819. on(
  820. event: 'start',
  821. listener: (
  822. req: http.IncomingMessage,
  823. res: http.ServerResponse,
  824. target: ProxyTargetUrl
  825. ) => void
  826. ): this
  827. on(
  828. event: 'proxyReq',
  829. listener: (
  830. proxyReq: http.ClientRequest,
  831. req: http.IncomingMessage,
  832. res: http.ServerResponse,
  833. options: ServerOptions
  834. ) => void
  835. ): this
  836. on(
  837. event: 'proxyRes',
  838. listener: (
  839. proxyRes: http.IncomingMessage,
  840. req: http.IncomingMessage,
  841. res: http.ServerResponse
  842. ) => void
  843. ): this
  844. on(
  845. event: 'proxyReqWs',
  846. listener: (
  847. proxyReq: http.ClientRequest,
  848. req: http.IncomingMessage,
  849. socket: net.Socket,
  850. options: ServerOptions,
  851. head: any
  852. ) => void
  853. ): this
  854. on(
  855. event: 'econnreset',
  856. listener: (
  857. err: Error,
  858. req: http.IncomingMessage,
  859. res: http.ServerResponse,
  860. target: ProxyTargetUrl
  861. ) => void
  862. ): this
  863. on(
  864. event: 'end',
  865. listener: (
  866. req: http.IncomingMessage,
  867. res: http.ServerResponse,
  868. proxyRes: http.IncomingMessage
  869. ) => void
  870. ): this
  871. on(
  872. event: 'close',
  873. listener: (
  874. proxyRes: http.IncomingMessage,
  875. proxySocket: net.Socket,
  876. proxyHead: any
  877. ) => void
  878. ): this
  879. once(event: string, listener: () => void): this
  880. removeListener(event: string, listener: () => void): this
  881. removeAllListeners(event?: string): this
  882. getMaxListeners(): number
  883. setMaxListeners(n: number): this
  884. listeners(event: string): Array<() => void>
  885. emit(event: string, ...args: any[]): boolean
  886. listenerCount(type: string): number
  887. }
  888. export interface ServerOptions {
  889. /** URL string to be parsed with the url module. */
  890. target?: ProxyTarget
  891. /** URL string to be parsed with the url module. */
  892. forward?: ProxyTargetUrl
  893. /** Object to be passed to http(s).request. */
  894. agent?: any
  895. /** Object to be passed to https.createServer(). */
  896. ssl?: any
  897. /** If you want to proxy websockets. */
  898. ws?: boolean
  899. /** Adds x- forward headers. */
  900. xfwd?: boolean
  901. /** Verify SSL certificate. */
  902. secure?: boolean
  903. /** Explicitly specify if we are proxying to another proxy. */
  904. toProxy?: boolean
  905. /** Specify whether you want to prepend the target's path to the proxy path. */
  906. prependPath?: boolean
  907. /** Specify whether you want to ignore the proxy path of the incoming request. */
  908. ignorePath?: boolean
  909. /** Local interface string to bind for outgoing connections. */
  910. localAddress?: string
  911. /** Changes the origin of the host header to the target URL. */
  912. changeOrigin?: boolean
  913. /** specify whether you want to keep letter case of response header key */
  914. preserveHeaderKeyCase?: boolean
  915. /** Basic authentication i.e. 'user:password' to compute an Authorization header. */
  916. auth?: string
  917. /** Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null. */
  918. hostRewrite?: string
  919. /** Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false. */
  920. autoRewrite?: boolean
  921. /** Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null. */
  922. protocolRewrite?: string
  923. /** rewrites domain of set-cookie headers. */
  924. cookieDomainRewrite?: false | string | { [oldDomain: string]: string }
  925. /** rewrites path of set-cookie headers. Default: false */
  926. cookiePathRewrite?: false | string | { [oldPath: string]: string }
  927. /** object with extra headers to be added to target requests. */
  928. headers?: { [header: string]: string }
  929. /** Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes) */
  930. proxyTimeout?: number
  931. /** Timeout (in milliseconds) for incoming requests */
  932. timeout?: number
  933. /** Specify whether you want to follow redirects. Default: false */
  934. followRedirects?: boolean
  935. /** 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 */
  936. selfHandleResponse?: boolean
  937. /** Buffer */
  938. buffer?: stream.Stream
  939. }
  940. }
  941. export declare type IndexHtmlTransform = IndexHtmlTransformHook | {
  942. enforce?: 'pre' | 'post';
  943. transform: IndexHtmlTransformHook;
  944. };
  945. export declare interface IndexHtmlTransformContext {
  946. /**
  947. * public path when served
  948. */
  949. path: string;
  950. /**
  951. * filename on disk
  952. */
  953. filename: string;
  954. server?: ViteDevServer;
  955. bundle?: OutputBundle;
  956. chunk?: OutputChunk;
  957. originalUrl?: string;
  958. }
  959. export declare type IndexHtmlTransformHook = (html: string, ctx: IndexHtmlTransformContext) => IndexHtmlTransformResult | void | Promise<IndexHtmlTransformResult | void>;
  960. export declare type IndexHtmlTransformResult = string | HtmlTagDescriptor[] | {
  961. html: string;
  962. tags: HtmlTagDescriptor[];
  963. };
  964. export declare type InferCustomEventPayload<T extends string> =
  965. T extends keyof CustomEventMap ? CustomEventMap[T] : any
  966. export declare interface InlineConfig extends UserConfig {
  967. configFile?: string | false;
  968. envFile?: false;
  969. }
  970. export declare interface InternalResolveOptions extends ResolveOptions {
  971. root: string;
  972. isBuild: boolean;
  973. isProduction: boolean;
  974. ssrConfig?: SSROptions;
  975. packageCache?: PackageCache;
  976. /**
  977. * src code mode also attempts the following:
  978. * - resolving /xxx as URLs
  979. * - resolving bare imports from optimized deps
  980. */
  981. asSrc?: boolean;
  982. tryIndex?: boolean;
  983. tryPrefix?: string;
  984. skipPackageJson?: boolean;
  985. preferRelative?: boolean;
  986. preserveSymlinks?: boolean;
  987. isRequire?: boolean;
  988. isFromTsImporter?: boolean;
  989. tryEsmOnly?: boolean;
  990. scan?: boolean;
  991. }
  992. export declare interface JsonOptions {
  993. /**
  994. * Generate a named export for every property of the JSON object
  995. * @default true
  996. */
  997. namedExports?: boolean;
  998. /**
  999. * Generate performant output as JSON.parse("stringified").
  1000. * Enabling this will disable namedExports.
  1001. * @default false
  1002. */
  1003. stringify?: boolean;
  1004. }
  1005. export declare type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife';
  1006. export declare interface LibraryOptions {
  1007. entry: string;
  1008. name?: string;
  1009. formats?: LibraryFormats[];
  1010. fileName?: string | ((format: ModuleFormat) => string);
  1011. }
  1012. export declare function loadConfigFromFile(configEnv: ConfigEnv, configFile?: string, configRoot?: string, logLevel?: LogLevel): Promise<{
  1013. path: string;
  1014. config: UserConfig;
  1015. dependencies: string[];
  1016. } | null>;
  1017. export declare function loadEnv(mode: string, envDir: string, prefixes?: string | string[]): Record<string, string>;
  1018. export declare interface LogErrorOptions extends LogOptions {
  1019. error?: Error | RollupError | null;
  1020. }
  1021. export declare interface Logger {
  1022. info(msg: string, options?: LogOptions): void;
  1023. warn(msg: string, options?: LogOptions): void;
  1024. warnOnce(msg: string, options?: LogOptions): void;
  1025. error(msg: string, options?: LogErrorOptions): void;
  1026. clearScreen(type: LogType): void;
  1027. hasErrorLogged(error: Error | RollupError): boolean;
  1028. hasWarned: boolean;
  1029. }
  1030. export declare interface LoggerOptions {
  1031. prefix?: string;
  1032. allowClearScreen?: boolean;
  1033. customLogger?: Logger;
  1034. }
  1035. export declare type LogLevel = LogType | 'silent';
  1036. export declare interface LogOptions {
  1037. clear?: boolean;
  1038. timestamp?: boolean;
  1039. }
  1040. export declare type LogType = 'error' | 'warn' | 'info';
  1041. export declare type Manifest = Record<string, ManifestChunk>;
  1042. export declare interface ManifestChunk {
  1043. src?: string;
  1044. file: string;
  1045. css?: string[];
  1046. assets?: string[];
  1047. isEntry?: boolean;
  1048. isDynamicEntry?: boolean;
  1049. imports?: string[];
  1050. dynamicImports?: string[];
  1051. }
  1052. export declare type Matcher = AnymatchPattern | AnymatchPattern[]
  1053. export declare function mergeConfig(defaults: Record<string, any>, overrides: Record<string, any>, isRoot?: boolean): Record<string, any>;
  1054. export declare class ModuleGraph {
  1055. private resolveId;
  1056. urlToModuleMap: Map<string, ModuleNode>;
  1057. idToModuleMap: Map<string, ModuleNode>;
  1058. fileToModulesMap: Map<string, Set<ModuleNode>>;
  1059. safeModulesPath: Set<string>;
  1060. constructor(resolveId: (url: string, ssr: boolean) => Promise<PartialResolvedId | null>);
  1061. getModuleByUrl(rawUrl: string, ssr?: boolean): Promise<ModuleNode | undefined>;
  1062. getModuleById(id: string): ModuleNode | undefined;
  1063. getModulesByFile(file: string): Set<ModuleNode> | undefined;
  1064. onFileChange(file: string): void;
  1065. invalidateModule(mod: ModuleNode, seen?: Set<ModuleNode>, timestamp?: number): void;
  1066. invalidateAll(): void;
  1067. /**
  1068. * Update the module graph based on a module's updated imports information
  1069. * If there are dependencies that no longer have any importers, they are
  1070. * returned as a Set.
  1071. */
  1072. updateModuleInfo(mod: ModuleNode, importedModules: Set<string | ModuleNode>, acceptedModules: Set<string | ModuleNode>, isSelfAccepting: boolean, ssr?: boolean): Promise<Set<ModuleNode> | undefined>;
  1073. ensureEntryFromUrl(rawUrl: string, ssr?: boolean): Promise<ModuleNode>;
  1074. createFileOnlyEntry(file: string): ModuleNode;
  1075. resolveUrl(url: string, ssr?: boolean): Promise<ResolvedUrl>;
  1076. }
  1077. export declare class ModuleNode {
  1078. /**
  1079. * Public served url path, starts with /
  1080. */
  1081. url: string;
  1082. /**
  1083. * Resolved file system path + query
  1084. */
  1085. id: string | null;
  1086. file: string | null;
  1087. type: 'js' | 'css';
  1088. info?: ModuleInfo;
  1089. meta?: Record<string, any>;
  1090. importers: Set<ModuleNode>;
  1091. importedModules: Set<ModuleNode>;
  1092. acceptedHmrDeps: Set<ModuleNode>;
  1093. isSelfAccepting?: boolean;
  1094. transformResult: TransformResult | null;
  1095. ssrTransformResult: TransformResult | null;
  1096. ssrModule: Record<string, any> | null;
  1097. ssrError: Error | null;
  1098. lastHMRTimestamp: number;
  1099. lastInvalidationTimestamp: number;
  1100. constructor(url: string);
  1101. }
  1102. export declare function normalizePath(id: string): string;
  1103. export declare interface OptimizedDepInfo {
  1104. id: string;
  1105. file: string;
  1106. src?: string;
  1107. needsInterop?: boolean;
  1108. browserHash?: string;
  1109. fileHash?: string;
  1110. /**
  1111. * During optimization, ids can still be resolved to their final location
  1112. * but the bundles may not yet be saved to disk
  1113. */
  1114. processing?: Promise<void>;
  1115. }
  1116. export declare interface OptimizedDeps {
  1117. metadata: DepOptimizationMetadata;
  1118. scanProcessing?: Promise<void>;
  1119. registerMissingImport: (id: string, resolved: string) => OptimizedDepInfo;
  1120. }
  1121. /**
  1122. * Used by Vite CLI when running `vite optimize`
  1123. */
  1124. export declare function optimizeDeps(config: ResolvedConfig, force?: boolean | undefined, asCommand?: boolean): Promise<DepOptimizationMetadata>;
  1125. /** Cache for package.json resolution and package.json contents */
  1126. export declare type PackageCache = Map<string, PackageData>;
  1127. export declare interface PackageData {
  1128. dir: string;
  1129. hasSideEffects: (id: string) => boolean | 'no-treeshake';
  1130. webResolvedImports: Record<string, string | undefined>;
  1131. nodeResolvedImports: Record<string, string | undefined>;
  1132. setResolvedCache: (key: string, entry: string, targetWeb: boolean) => void;
  1133. getResolvedCache: (key: string, targetWeb: boolean) => string | undefined;
  1134. data: {
  1135. [field: string]: any;
  1136. version: string;
  1137. main: string;
  1138. module: string;
  1139. browser: string | Record<string, string | false>;
  1140. exports: string | Record<string, any> | string[];
  1141. dependencies: Record<string, string>;
  1142. };
  1143. }
  1144. /**
  1145. * Vite plugins extends the Rollup plugin interface with a few extra
  1146. * vite-specific options. A valid vite plugin is also a valid Rollup plugin.
  1147. * On the contrary, a Rollup plugin may or may NOT be a valid vite universal
  1148. * plugin, since some Rollup features do not make sense in an unbundled
  1149. * dev server context. That said, as long as a rollup plugin doesn't have strong
  1150. * coupling between its bundle phase and output phase hooks then it should
  1151. * just work (that means, most of them).
  1152. *
  1153. * By default, the plugins are run during both serve and build. When a plugin
  1154. * is applied during serve, it will only run **non output plugin hooks** (see
  1155. * rollup type definition of {@link rollup#PluginHooks}). You can think of the
  1156. * dev server as only running `const bundle = rollup.rollup()` but never calling
  1157. * `bundle.generate()`.
  1158. *
  1159. * A plugin that expects to have different behavior depending on serve/build can
  1160. * export a factory function that receives the command being run via options.
  1161. *
  1162. * If a plugin should be applied only for server or build, a function format
  1163. * config file can be used to conditional determine the plugins to use.
  1164. */
  1165. export declare interface Plugin extends Plugin_2 {
  1166. /**
  1167. * Enforce plugin invocation tier similar to webpack loaders.
  1168. *
  1169. * Plugin invocation order:
  1170. * - alias resolution
  1171. * - `enforce: 'pre'` plugins
  1172. * - vite core plugins
  1173. * - normal plugins
  1174. * - vite build plugins
  1175. * - `enforce: 'post'` plugins
  1176. * - vite build post plugins
  1177. */
  1178. enforce?: 'pre' | 'post';
  1179. /**
  1180. * Apply the plugin only for serve or build, or on certain conditions.
  1181. */
  1182. apply?: 'serve' | 'build' | ((config: UserConfig, env: ConfigEnv) => boolean);
  1183. /**
  1184. * Modify vite config before it's resolved. The hook can either mutate the
  1185. * passed-in config directly, or return a partial config object that will be
  1186. * deeply merged into existing config.
  1187. *
  1188. * Note: User plugins are resolved before running this hook so injecting other
  1189. * plugins inside the `config` hook will have no effect.
  1190. */
  1191. config?: (config: UserConfig, env: ConfigEnv) => UserConfig | null | void | Promise<UserConfig | null | void>;
  1192. /**
  1193. * Use this hook to read and store the final resolved vite config.
  1194. */
  1195. configResolved?: (config: ResolvedConfig) => void | Promise<void>;
  1196. /**
  1197. * Configure the vite server. The hook receives the {@link ViteDevServer}
  1198. * instance. This can also be used to store a reference to the server
  1199. * for use in other hooks.
  1200. *
  1201. * The hooks will be called before internal middlewares are applied. A hook
  1202. * can return a post hook that will be called after internal middlewares
  1203. * are applied. Hook can be async functions and will be called in series.
  1204. */
  1205. configureServer?: ServerHook;
  1206. /**
  1207. * Transform index.html.
  1208. * The hook receives the following arguments:
  1209. *
  1210. * - html: string
  1211. * - ctx?: vite.ServerContext (only present during serve)
  1212. * - bundle?: rollup.OutputBundle (only present during build)
  1213. *
  1214. * It can either return a transformed string, or a list of html tag
  1215. * descriptors that will be injected into the <head> or <body>.
  1216. *
  1217. * By default the transform is applied **after** vite's internal html
  1218. * transform. If you need to apply the transform before vite, use an object:
  1219. * `{ enforce: 'pre', transform: hook }`
  1220. */
  1221. transformIndexHtml?: IndexHtmlTransform;
  1222. /**
  1223. * Perform custom handling of HMR updates.
  1224. * The handler receives a context containing changed filename, timestamp, a
  1225. * list of modules affected by the file change, and the dev server instance.
  1226. *
  1227. * - The hook can return a filtered list of modules to narrow down the update.
  1228. * e.g. for a Vue SFC, we can narrow down the part to update by comparing
  1229. * the descriptors.
  1230. *
  1231. * - The hook can also return an empty array and then perform custom updates
  1232. * by sending a custom hmr payload via server.ws.send().
  1233. *
  1234. * - If the hook doesn't return a value, the hmr update will be performed as
  1235. * normal.
  1236. */
  1237. handleHotUpdate?(ctx: HmrContext): Array<ModuleNode> | void | Promise<Array<ModuleNode> | void>;
  1238. /**
  1239. * extend hooks with ssr flag
  1240. */
  1241. resolveId?(this: PluginContext, source: string, importer: string | undefined, options: {
  1242. custom?: CustomPluginOptions;
  1243. ssr?: boolean;
  1244. /* Excluded from this release type: scan */
  1245. }): Promise<ResolveIdResult> | ResolveIdResult;
  1246. load?(this: PluginContext, id: string, options?: {
  1247. ssr?: boolean;
  1248. }): Promise<LoadResult> | LoadResult;
  1249. transform?(this: TransformPluginContext, code: string, id: string, options?: {
  1250. ssr?: boolean;
  1251. }): Promise<TransformResult_3> | TransformResult_3;
  1252. }
  1253. export declare interface PluginContainer {
  1254. options: InputOptions;
  1255. getModuleInfo(id: string): ModuleInfo | null;
  1256. buildStart(options: InputOptions): Promise<void>;
  1257. resolveId(id: string, importer?: string, options?: {
  1258. skip?: Set<Plugin>;
  1259. ssr?: boolean;
  1260. /* Excluded from this release type: scan */
  1261. }): Promise<PartialResolvedId | null>;
  1262. transform(code: string, id: string, options?: {
  1263. inMap?: SourceDescription['map'];
  1264. ssr?: boolean;
  1265. }): Promise<SourceDescription | null>;
  1266. load(id: string, options?: {
  1267. ssr?: boolean;
  1268. }): Promise<LoadResult | null>;
  1269. close(): Promise<void>;
  1270. }
  1271. export declare type PluginOption = Plugin | false | null | undefined | PluginOption[];
  1272. /**
  1273. * Starts the Vite server in preview mode, to simulate a production deployment
  1274. * @experimental
  1275. */
  1276. export declare function preview(inlineConfig: InlineConfig): Promise<PreviewServer>;
  1277. export declare interface PreviewOptions extends CommonServerOptions {
  1278. }
  1279. export declare interface PreviewServer {
  1280. /**
  1281. * The resolved vite config object
  1282. */
  1283. config: ResolvedConfig;
  1284. /**
  1285. * native Node http server instance
  1286. */
  1287. httpServer: Server;
  1288. /**
  1289. * Print server urls
  1290. */
  1291. printUrls: () => void;
  1292. }
  1293. /**
  1294. * @deprecated Use `server.printUrls()` instead
  1295. */
  1296. export declare function printHttpServerUrls(server: Server_3, config: ResolvedConfig): void;
  1297. export declare interface ProxyOptions extends HttpProxy.ServerOptions {
  1298. /**
  1299. * rewrite path
  1300. */
  1301. rewrite?: (path: string) => string;
  1302. /**
  1303. * configure the proxy server (e.g. listen to events)
  1304. */
  1305. configure?: (proxy: HttpProxy.Server, options: ProxyOptions) => void;
  1306. /**
  1307. * webpack-dev-server style bypass function
  1308. */
  1309. bypass?: (req: http.IncomingMessage, res: http.ServerResponse, options: ProxyOptions) => void | null | undefined | false | string;
  1310. }
  1311. export declare interface PrunePayload {
  1312. type: 'prune'
  1313. paths: string[]
  1314. }
  1315. export declare function resolveConfig(inlineConfig: InlineConfig, command: 'build' | 'serve', defaultMode?: string): Promise<ResolvedConfig>;
  1316. export declare type ResolvedBuildOptions = Required<Omit<BuildOptions, 'base' | 'cleanCssOptions' | 'polyfillDynamicImport' | 'brotliSize'>>;
  1317. export declare type ResolvedConfig = Readonly<Omit<UserConfig, 'plugins' | 'alias' | 'dedupe' | 'assetsInclude' | 'optimizeDeps' | 'worker'> & {
  1318. configFile: string | undefined;
  1319. configFileDependencies: string[];
  1320. inlineConfig: InlineConfig;
  1321. root: string;
  1322. base: string;
  1323. publicDir: string;
  1324. cacheDir: string;
  1325. command: 'build' | 'serve';
  1326. mode: string;
  1327. isWorker: boolean;
  1328. isProduction: boolean;
  1329. env: Record<string, any>;
  1330. resolve: ResolveOptions & {
  1331. alias: Alias[];
  1332. };
  1333. plugins: readonly Plugin[];
  1334. server: ResolvedServerOptions;
  1335. build: ResolvedBuildOptions;
  1336. preview: ResolvedPreviewOptions;
  1337. assetsInclude: (file: string) => boolean;
  1338. logger: Logger;
  1339. createResolver: (options?: Partial<InternalResolveOptions>) => ResolveFn;
  1340. optimizeDeps: Omit<DepOptimizationOptions, 'keepNames'>;
  1341. /* Excluded from this release type: packageCache */
  1342. worker: ResolveWorkerOptions;
  1343. }>;
  1344. export declare interface ResolvedPreviewOptions extends PreviewOptions {
  1345. }
  1346. export declare interface ResolvedServerOptions extends ServerOptions {
  1347. fs: Required<FileSystemServeOptions>;
  1348. }
  1349. export declare type ResolvedUrl = [
  1350. url: string,
  1351. resolvedId: string,
  1352. meta: object | null | undefined
  1353. ];
  1354. export declare function resolveEnvPrefix({ envPrefix }: UserConfig): string[];
  1355. export declare type ResolveFn = (id: string, importer?: string, aliasOnly?: boolean, ssr?: boolean) => Promise<string | undefined>;
  1356. export declare interface ResolveOptions {
  1357. mainFields?: string[];
  1358. conditions?: string[];
  1359. extensions?: string[];
  1360. dedupe?: string[];
  1361. preserveSymlinks?: boolean;
  1362. }
  1363. export declare function resolvePackageData(id: string, basedir: string, preserveSymlinks?: boolean, packageCache?: PackageCache): PackageData | null;
  1364. export declare function resolvePackageEntry(id: string, { dir, data, setResolvedCache, getResolvedCache }: PackageData, targetWeb: boolean, options: InternalResolveOptions): string | undefined;
  1365. export declare type ResolverFunction = PluginHooks['resolveId']
  1366. export declare interface ResolverObject {
  1367. buildStart?: PluginHooks['buildStart']
  1368. resolveId: ResolverFunction
  1369. }
  1370. export declare interface ResolveWorkerOptions {
  1371. format: 'es' | 'iife';
  1372. plugins: Plugin[];
  1373. rollupOptions: RollupOptions;
  1374. }
  1375. /**
  1376. * https://github.com/rollup/plugins/blob/master/packages/commonjs/types/index.d.ts
  1377. *
  1378. * This source code is licensed under the MIT license found in the
  1379. * LICENSE file at
  1380. * https://github.com/rollup/plugins/blob/master/LICENSE
  1381. */
  1382. export declare interface RollupCommonJSOptions {
  1383. /**
  1384. * A picomatch pattern, or array of patterns, which specifies the files in
  1385. * the build the plugin should operate on. By default, all files with
  1386. * extension `".cjs"` or those in `extensions` are included, but you can narrow
  1387. * this list by only including specific files. These files will be analyzed
  1388. * and transpiled if either the analysis does not find ES module specific
  1389. * statements or `transformMixedEsModules` is `true`.
  1390. * @default undefined
  1391. */
  1392. include?: string | RegExp | readonly (string | RegExp)[]
  1393. /**
  1394. * A picomatch pattern, or array of patterns, which specifies the files in
  1395. * the build the plugin should _ignore_. By default, all files with
  1396. * extensions other than those in `extensions` or `".cjs"` are ignored, but you
  1397. * can exclude additional files. See also the `include` option.
  1398. * @default undefined
  1399. */
  1400. exclude?: string | RegExp | readonly (string | RegExp)[]
  1401. /**
  1402. * For extensionless imports, search for extensions other than .js in the
  1403. * order specified. Note that you need to make sure that non-JavaScript files
  1404. * are transpiled by another plugin first.
  1405. * @default [ '.js' ]
  1406. */
  1407. extensions?: ReadonlyArray<string>
  1408. /**
  1409. * If true then uses of `global` won't be dealt with by this plugin
  1410. * @default false
  1411. */
  1412. ignoreGlobal?: boolean
  1413. /**
  1414. * If false, skips source map generation for CommonJS modules. This will improve performance.
  1415. * @default true
  1416. */
  1417. sourceMap?: boolean
  1418. /**
  1419. * Some `require` calls cannot be resolved statically to be translated to
  1420. * imports.
  1421. * When this option is set to `false`, the generated code will either
  1422. * directly throw an error when such a call is encountered or, when
  1423. * `dynamicRequireTargets` is used, when such a call cannot be resolved with a
  1424. * configured dynamic require target.
  1425. * Setting this option to `true` will instead leave the `require` call in the
  1426. * code or use it as a fallback for `dynamicRequireTargets`.
  1427. * @default false
  1428. */
  1429. ignoreDynamicRequires?: boolean
  1430. /**
  1431. * Instructs the plugin whether to enable mixed module transformations. This
  1432. * is useful in scenarios with modules that contain a mix of ES `import`
  1433. * statements and CommonJS `require` expressions. Set to `true` if `require`
  1434. * calls should be transformed to imports in mixed modules, or `false` if the
  1435. * `require` expressions should survive the transformation. The latter can be
  1436. * important if the code contains environment detection, or you are coding
  1437. * for an environment with special treatment for `require` calls such as
  1438. * ElectronJS. See also the `ignore` option.
  1439. * @default false
  1440. */
  1441. transformMixedEsModules?: boolean
  1442. /**
  1443. * Sometimes you have to leave require statements unconverted. Pass an array
  1444. * containing the IDs or a `id => boolean` function.
  1445. * @default []
  1446. */
  1447. ignore?: ReadonlyArray<string> | ((id: string) => boolean)
  1448. /**
  1449. * In most cases, where `require` calls are inside a `try-catch` clause,
  1450. * they should be left unconverted as it requires an optional dependency
  1451. * that may or may not be installed beside the rolled up package.
  1452. * Due to the conversion of `require` to a static `import` - the call is hoisted
  1453. * to the top of the file, outside of the `try-catch` clause.
  1454. *
  1455. * - `true`: All `require` calls inside a `try` will be left unconverted.
  1456. * - `false`: All `require` calls inside a `try` will be converted as if the `try-catch` clause is not there.
  1457. * - `remove`: Remove all `require` calls from inside any `try` block.
  1458. * - `string[]`: Pass an array containing the IDs to left unconverted.
  1459. * - `((id: string) => boolean|'remove')`: Pass a function that control individual IDs.
  1460. *
  1461. * @default false
  1462. */
  1463. ignoreTryCatch?:
  1464. | boolean
  1465. | 'remove'
  1466. | ReadonlyArray<string>
  1467. | ((id: string) => boolean | 'remove')
  1468. /**
  1469. * Controls how to render imports from external dependencies. By default,
  1470. * this plugin assumes that all external dependencies are CommonJS. This
  1471. * means they are rendered as default imports to be compatible with e.g.
  1472. * NodeJS where ES modules can only import a default export from a CommonJS
  1473. * dependency.
  1474. *
  1475. * If you set `esmExternals` to `true`, this plugins assumes that all
  1476. * external dependencies are ES modules and respect the
  1477. * `requireReturnsDefault` option. If that option is not set, they will be
  1478. * rendered as namespace imports.
  1479. *
  1480. * You can also supply an array of ids to be treated as ES modules, or a
  1481. * function that will be passed each external id to determine if it is an ES
  1482. * module.
  1483. * @default false
  1484. */
  1485. esmExternals?: boolean | ReadonlyArray<string> | ((id: string) => boolean)
  1486. /**
  1487. * Controls what is returned when requiring an ES module from a CommonJS file.
  1488. * When using the `esmExternals` option, this will also apply to external
  1489. * modules. By default, this plugin will render those imports as namespace
  1490. * imports i.e.
  1491. *
  1492. * ```js
  1493. * // input
  1494. * const foo = require('foo');
  1495. *
  1496. * // output
  1497. * import * as foo from 'foo';
  1498. * ```
  1499. *
  1500. * However there are some situations where this may not be desired.
  1501. * For these situations, you can change Rollup's behaviour either globally or
  1502. * per module. To change it globally, set the `requireReturnsDefault` option
  1503. * to one of the following values:
  1504. *
  1505. * - `false`: This is the default, requiring an ES module returns its
  1506. * namespace. This is the only option that will also add a marker
  1507. * `__esModule: true` to the namespace to support interop patterns in
  1508. * CommonJS modules that are transpiled ES modules.
  1509. * - `"namespace"`: Like `false`, requiring an ES module returns its
  1510. * namespace, but the plugin does not add the `__esModule` marker and thus
  1511. * creates more efficient code. For external dependencies when using
  1512. * `esmExternals: true`, no additional interop code is generated.
  1513. * - `"auto"`: This is complementary to how `output.exports: "auto"` works in
  1514. * Rollup: If a module has a default export and no named exports, requiring
  1515. * that module returns the default export. In all other cases, the namespace
  1516. * is returned. For external dependencies when using `esmExternals: true`, a
  1517. * corresponding interop helper is added.
  1518. * - `"preferred"`: If a module has a default export, requiring that module
  1519. * always returns the default export, no matter whether additional named
  1520. * exports exist. This is similar to how previous versions of this plugin
  1521. * worked. Again for external dependencies when using `esmExternals: true`,
  1522. * an interop helper is added.
  1523. * - `true`: This will always try to return the default export on require
  1524. * without checking if it actually exists. This can throw at build time if
  1525. * there is no default export. This is how external dependencies are handled
  1526. * when `esmExternals` is not used. The advantage over the other options is
  1527. * that, like `false`, this does not add an interop helper for external
  1528. * dependencies, keeping the code lean.
  1529. *
  1530. * To change this for individual modules, you can supply a function for
  1531. * `requireReturnsDefault` instead. This function will then be called once for
  1532. * each required ES module or external dependency with the corresponding id
  1533. * and allows you to return different values for different modules.
  1534. * @default false
  1535. */
  1536. requireReturnsDefault?:
  1537. | boolean
  1538. | 'auto'
  1539. | 'preferred'
  1540. | 'namespace'
  1541. | ((id: string) => boolean | 'auto' | 'preferred' | 'namespace')
  1542. /**
  1543. * Some modules contain dynamic `require` calls, or require modules that
  1544. * contain circular dependencies, which are not handled well by static
  1545. * imports. Including those modules as `dynamicRequireTargets` will simulate a
  1546. * CommonJS (NodeJS-like) environment for them with support for dynamic and
  1547. * circular dependencies.
  1548. *
  1549. * Note: In extreme cases, this feature may result in some paths being
  1550. * rendered as absolute in the final bundle. The plugin tries to avoid
  1551. * exposing paths from the local machine, but if you are `dynamicRequirePaths`
  1552. * with paths that are far away from your project's folder, that may require
  1553. * replacing strings like `"/Users/John/Desktop/foo-project/"` -\> `"/"`.
  1554. */
  1555. dynamicRequireTargets?: string | ReadonlyArray<string>
  1556. }
  1557. export declare interface RollupDynamicImportVarsOptions {
  1558. /**
  1559. * Files to include in this plugin (default all).
  1560. * @default []
  1561. */
  1562. include?: string | RegExp | (string | RegExp)[]
  1563. /**
  1564. * Files to exclude in this plugin (default none).
  1565. * @default []
  1566. */
  1567. exclude?: string | RegExp | (string | RegExp)[]
  1568. /**
  1569. * 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.
  1570. * @default false
  1571. */
  1572. warnOnError?: boolean
  1573. }
  1574. /**
  1575. * Search up for the nearest workspace root
  1576. */
  1577. export declare function searchForWorkspaceRoot(current: string, root?: string): string;
  1578. export declare function send(req: IncomingMessage, res: ServerResponse, content: string | Buffer, type: string, options: SendOptions): void;
  1579. export declare interface SendOptions {
  1580. etag?: string;
  1581. cacheControl?: string;
  1582. headers?: OutgoingHttpHeaders;
  1583. map?: SourceMap | null;
  1584. }
  1585. export declare type ServerHook = (server: ViteDevServer) => (() => void) | void | Promise<(() => void) | void>;
  1586. export declare interface ServerOptions extends CommonServerOptions {
  1587. /**
  1588. * Force dep pre-optimization regardless of whether deps have changed.
  1589. */
  1590. force?: boolean;
  1591. /**
  1592. * Configure HMR-specific options (port, host, path & protocol)
  1593. */
  1594. hmr?: HmrOptions | boolean;
  1595. /**
  1596. * chokidar watch options
  1597. * https://github.com/paulmillr/chokidar#api
  1598. */
  1599. watch?: WatchOptions;
  1600. /**
  1601. * Create Vite dev server to be used as a middleware in an existing server
  1602. */
  1603. middlewareMode?: boolean | 'html' | 'ssr';
  1604. /**
  1605. * Prepend this folder to http requests, for use when proxying vite as a subfolder
  1606. * Should start and end with the `/` character
  1607. */
  1608. base?: string;
  1609. /**
  1610. * Options for files served via '/\@fs/'.
  1611. */
  1612. fs?: FileSystemServeOptions;
  1613. /**
  1614. * Origin for the generated asset URLs.
  1615. *
  1616. * @example `http://127.0.0.1:8080`
  1617. */
  1618. origin?: string;
  1619. /**
  1620. * Pre-transform known direct imports
  1621. *
  1622. * @experimental this option is experimental and might be changed in the future
  1623. * @default true
  1624. */
  1625. preTransformRequests?: boolean;
  1626. }
  1627. export declare function sortUserPlugins(plugins: (Plugin | Plugin[])[] | undefined): [Plugin[], Plugin[], Plugin[]];
  1628. export declare function splitVendorChunk(options?: {
  1629. cache?: SplitVendorChunkCache;
  1630. }): GetManualChunk;
  1631. export declare class SplitVendorChunkCache {
  1632. cache: Map<string, boolean>;
  1633. constructor();
  1634. reset(): void;
  1635. }
  1636. export declare function splitVendorChunkPlugin(): Plugin;
  1637. export declare interface SSROptions {
  1638. external?: string[];
  1639. noExternal?: string | RegExp | (string | RegExp)[] | true;
  1640. /**
  1641. * Define the target for the ssr build. The browser field in package.json
  1642. * is ignored for node but used if webworker is the target
  1643. * Default: 'node'
  1644. */
  1645. target?: SSRTarget;
  1646. }
  1647. export declare type SSRTarget = 'node' | 'webworker';
  1648. export declare namespace Terser {
  1649. export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020
  1650. export interface ParseOptions {
  1651. bare_returns?: boolean
  1652. ecma?: ECMA
  1653. html5_comments?: boolean
  1654. shebang?: boolean
  1655. }
  1656. export interface CompressOptions {
  1657. arguments?: boolean
  1658. arrows?: boolean
  1659. booleans_as_integers?: boolean
  1660. booleans?: boolean
  1661. collapse_vars?: boolean
  1662. comparisons?: boolean
  1663. computed_props?: boolean
  1664. conditionals?: boolean
  1665. dead_code?: boolean
  1666. defaults?: boolean
  1667. directives?: boolean
  1668. drop_console?: boolean
  1669. drop_debugger?: boolean
  1670. ecma?: ECMA
  1671. evaluate?: boolean
  1672. expression?: boolean
  1673. global_defs?: object
  1674. hoist_funs?: boolean
  1675. hoist_props?: boolean
  1676. hoist_vars?: boolean
  1677. ie8?: boolean
  1678. if_return?: boolean
  1679. inline?: boolean | InlineFunctions
  1680. join_vars?: boolean
  1681. keep_classnames?: boolean | RegExp
  1682. keep_fargs?: boolean
  1683. keep_fnames?: boolean | RegExp
  1684. keep_infinity?: boolean
  1685. loops?: boolean
  1686. module?: boolean
  1687. negate_iife?: boolean
  1688. passes?: number
  1689. properties?: boolean
  1690. pure_funcs?: string[]
  1691. pure_getters?: boolean | 'strict'
  1692. reduce_funcs?: boolean
  1693. reduce_vars?: boolean
  1694. sequences?: boolean | number
  1695. side_effects?: boolean
  1696. switches?: boolean
  1697. toplevel?: boolean
  1698. top_retain?: null | string | string[] | RegExp
  1699. typeofs?: boolean
  1700. unsafe_arrows?: boolean
  1701. unsafe?: boolean
  1702. unsafe_comps?: boolean
  1703. unsafe_Function?: boolean
  1704. unsafe_math?: boolean
  1705. unsafe_symbols?: boolean
  1706. unsafe_methods?: boolean
  1707. unsafe_proto?: boolean
  1708. unsafe_regexp?: boolean
  1709. unsafe_undefined?: boolean
  1710. unused?: boolean
  1711. }
  1712. export enum InlineFunctions {
  1713. Disabled = 0,
  1714. SimpleFunctions = 1,
  1715. WithArguments = 2,
  1716. WithArgumentsAndVariables = 3
  1717. }
  1718. export interface MangleOptions {
  1719. eval?: boolean
  1720. keep_classnames?: boolean | RegExp
  1721. keep_fnames?: boolean | RegExp
  1722. module?: boolean
  1723. properties?: boolean | ManglePropertiesOptions
  1724. reserved?: string[]
  1725. safari10?: boolean
  1726. toplevel?: boolean
  1727. }
  1728. export interface ManglePropertiesOptions {
  1729. builtins?: boolean
  1730. debug?: boolean
  1731. keep_quoted?: boolean | 'strict'
  1732. regex?: RegExp | string
  1733. reserved?: string[]
  1734. }
  1735. export interface FormatOptions {
  1736. ascii_only?: boolean
  1737. beautify?: boolean
  1738. braces?: boolean
  1739. comments?:
  1740. | boolean
  1741. | 'all'
  1742. | 'some'
  1743. | RegExp
  1744. | ((
  1745. node: any,
  1746. comment: {
  1747. value: string
  1748. type: 'comment1' | 'comment2' | 'comment3' | 'comment4'
  1749. pos: number
  1750. line: number
  1751. col: number
  1752. }
  1753. ) => boolean)
  1754. ecma?: ECMA
  1755. ie8?: boolean
  1756. indent_level?: number
  1757. indent_start?: number
  1758. inline_script?: boolean
  1759. keep_quoted_props?: boolean
  1760. max_line_len?: number | false
  1761. preamble?: string
  1762. preserve_annotations?: boolean
  1763. quote_keys?: boolean
  1764. quote_style?: OutputQuoteStyle
  1765. safari10?: boolean
  1766. semicolons?: boolean
  1767. shebang?: boolean
  1768. shorthand?: boolean
  1769. source_map?: SourceMapOptions
  1770. webkit?: boolean
  1771. width?: number
  1772. wrap_iife?: boolean
  1773. wrap_func_args?: boolean
  1774. }
  1775. export enum OutputQuoteStyle {
  1776. PreferDouble = 0,
  1777. AlwaysSingle = 1,
  1778. AlwaysDouble = 2,
  1779. AlwaysOriginal = 3
  1780. }
  1781. export interface MinifyOptions {
  1782. compress?: boolean | CompressOptions
  1783. ecma?: ECMA
  1784. ie8?: boolean
  1785. keep_classnames?: boolean | RegExp
  1786. keep_fnames?: boolean | RegExp
  1787. mangle?: boolean | MangleOptions
  1788. module?: boolean
  1789. nameCache?: object
  1790. format?: FormatOptions
  1791. /** @deprecated use format instead */
  1792. output?: FormatOptions
  1793. parse?: ParseOptions
  1794. safari10?: boolean
  1795. sourceMap?: boolean | SourceMapOptions
  1796. toplevel?: boolean
  1797. }
  1798. export interface MinifyOutput {
  1799. code?: string
  1800. map?: object | string
  1801. }
  1802. export interface SourceMapOptions {
  1803. /** Source map object, 'inline' or source map file content */
  1804. content?: object | string
  1805. includeSources?: boolean
  1806. filename?: string
  1807. root?: string
  1808. url?: string | 'inline'
  1809. }
  1810. }
  1811. export declare interface TransformOptions {
  1812. ssr?: boolean;
  1813. html?: boolean;
  1814. }
  1815. export declare interface TransformResult {
  1816. code: string;
  1817. map: SourceMap | null;
  1818. etag?: string;
  1819. deps?: string[];
  1820. dynamicDeps?: string[];
  1821. }
  1822. export declare function transformWithEsbuild(code: string, filename: string, options?: EsbuildTransformOptions, inMap?: object): Promise<ESBuildTransformResult>;
  1823. export declare interface Update {
  1824. type: 'js-update' | 'css-update'
  1825. path: string
  1826. acceptedPath: string
  1827. timestamp: number
  1828. }
  1829. export declare interface UpdatePayload {
  1830. type: 'update'
  1831. updates: Update[]
  1832. }
  1833. export declare interface UserConfig {
  1834. /**
  1835. * Project root directory. Can be an absolute path, or a path relative from
  1836. * the location of the config file itself.
  1837. * @default process.cwd()
  1838. */
  1839. root?: string;
  1840. /**
  1841. * Base public path when served in development or production.
  1842. * @default '/'
  1843. */
  1844. base?: string;
  1845. /**
  1846. * Directory to serve as plain static assets. Files in this directory are
  1847. * served and copied to build dist dir as-is without transform. The value
  1848. * can be either an absolute file system path or a path relative to <root>.
  1849. *
  1850. * Set to `false` or an empty string to disable copied static assets to build dist dir.
  1851. * @default 'public'
  1852. */
  1853. publicDir?: string | false;
  1854. /**
  1855. * Directory to save cache files. Files in this directory are pre-bundled
  1856. * deps or some other cache files that generated by vite, which can improve
  1857. * the performance. You can use `--force` flag or manually delete the directory
  1858. * to regenerate the cache files. The value can be either an absolute file
  1859. * system path or a path relative to <root>.
  1860. * Default to `.vite` when no `package.json` is detected.
  1861. * @default 'node_modules/.vite'
  1862. */
  1863. cacheDir?: string;
  1864. /**
  1865. * Explicitly set a mode to run in. This will override the default mode for
  1866. * each command, and can be overridden by the command line --mode option.
  1867. */
  1868. mode?: string;
  1869. /**
  1870. * Define global variable replacements.
  1871. * Entries will be defined on `window` during dev and replaced during build.
  1872. */
  1873. define?: Record<string, any>;
  1874. /**
  1875. * Array of vite plugins to use.
  1876. */
  1877. plugins?: PluginOption[];
  1878. /**
  1879. * Configure resolver
  1880. */
  1881. resolve?: ResolveOptions & {
  1882. alias?: AliasOptions;
  1883. };
  1884. /**
  1885. * CSS related options (preprocessors and CSS modules)
  1886. */
  1887. css?: CSSOptions;
  1888. /**
  1889. * JSON loading options
  1890. */
  1891. json?: JsonOptions;
  1892. /**
  1893. * Transform options to pass to esbuild.
  1894. * Or set to `false` to disable esbuild.
  1895. */
  1896. esbuild?: ESBuildOptions | false;
  1897. /**
  1898. * Specify additional picomatch patterns to be treated as static assets.
  1899. */
  1900. assetsInclude?: string | RegExp | (string | RegExp)[];
  1901. /**
  1902. * Server specific options, e.g. host, port, https...
  1903. */
  1904. server?: ServerOptions;
  1905. /**
  1906. * Build specific options
  1907. */
  1908. build?: BuildOptions;
  1909. /**
  1910. * Preview specific options, e.g. host, port, https...
  1911. */
  1912. preview?: PreviewOptions;
  1913. /**
  1914. * Dep optimization options
  1915. */
  1916. optimizeDeps?: DepOptimizationOptions;
  1917. /* Excluded from this release type: ssr */
  1918. /**
  1919. * Log level.
  1920. * Default: 'info'
  1921. */
  1922. logLevel?: LogLevel;
  1923. /**
  1924. * Custom logger.
  1925. */
  1926. customLogger?: Logger;
  1927. /**
  1928. * Default: true
  1929. */
  1930. clearScreen?: boolean;
  1931. /**
  1932. * Environment files directory. Can be an absolute path, or a path relative from
  1933. * the location of the config file itself.
  1934. * @default root
  1935. */
  1936. envDir?: string;
  1937. /**
  1938. * Env variables starts with `envPrefix` will be exposed to your client source code via import.meta.env.
  1939. * @default 'VITE_'
  1940. */
  1941. envPrefix?: string | string[];
  1942. /**
  1943. * Import aliases
  1944. * @deprecated use `resolve.alias` instead
  1945. */
  1946. alias?: AliasOptions;
  1947. /**
  1948. * Force Vite to always resolve listed dependencies to the same copy (from
  1949. * project root).
  1950. * @deprecated use `resolve.dedupe` instead
  1951. */
  1952. dedupe?: string[];
  1953. /**
  1954. * Worker bundle options
  1955. */
  1956. worker?: {
  1957. /**
  1958. * Output format for worker bundle
  1959. * @default 'iife'
  1960. */
  1961. format?: 'es' | 'iife';
  1962. /**
  1963. * Vite plugins that apply to worker bundle
  1964. */
  1965. plugins?: PluginOption[];
  1966. /**
  1967. * Rollup options to build worker bundle
  1968. */
  1969. rollupOptions?: Omit<RollupOptions, 'plugins' | 'input' | 'onwarn' | 'preserveEntrySignatures'>;
  1970. };
  1971. }
  1972. export declare type UserConfigExport = UserConfig | Promise<UserConfig> | UserConfigFn;
  1973. export declare type UserConfigFn = (env: ConfigEnv) => UserConfig | Promise<UserConfig>;
  1974. export declare interface ViteDevServer {
  1975. /**
  1976. * The resolved vite config object
  1977. */
  1978. config: ResolvedConfig;
  1979. /**
  1980. * A connect app instance.
  1981. * - Can be used to attach custom middlewares to the dev server.
  1982. * - Can also be used as the handler function of a custom http server
  1983. * or as a middleware in any connect-style Node.js frameworks
  1984. *
  1985. * https://github.com/senchalabs/connect#use-middleware
  1986. */
  1987. middlewares: Connect.Server;
  1988. /**
  1989. * @deprecated use `server.middlewares` instead
  1990. */
  1991. app: Connect.Server;
  1992. /**
  1993. * native Node http server instance
  1994. * will be null in middleware mode
  1995. */
  1996. httpServer: http.Server | null;
  1997. /**
  1998. * chokidar watcher instance
  1999. * https://github.com/paulmillr/chokidar#api
  2000. */
  2001. watcher: FSWatcher;
  2002. /**
  2003. * web socket server with `send(payload)` method
  2004. */
  2005. ws: WebSocketServer;
  2006. /**
  2007. * Rollup plugin container that can run plugin hooks on a given file
  2008. */
  2009. pluginContainer: PluginContainer;
  2010. /**
  2011. * Module graph that tracks the import relationships, url to file mapping
  2012. * and hmr state.
  2013. */
  2014. moduleGraph: ModuleGraph;
  2015. /**
  2016. * Programmatically resolve, load and transform a URL and get the result
  2017. * without going through the http request pipeline.
  2018. */
  2019. transformRequest(url: string, options?: TransformOptions): Promise<TransformResult | null>;
  2020. /**
  2021. * Apply vite built-in HTML transforms and any plugin HTML transforms.
  2022. */
  2023. transformIndexHtml(url: string, html: string, originalUrl?: string): Promise<string>;
  2024. /**
  2025. * Util for transforming a file with esbuild.
  2026. * Can be useful for certain plugins.
  2027. *
  2028. * @deprecated import `transformWithEsbuild` from `vite` instead
  2029. */
  2030. transformWithEsbuild(code: string, filename: string, options?: EsbuildTransformOptions, inMap?: object): Promise<ESBuildTransformResult>;
  2031. /**
  2032. * Transform module code into SSR format.
  2033. * @experimental
  2034. */
  2035. ssrTransform(code: string, inMap: SourceMap | null, url: string): Promise<TransformResult | null>;
  2036. /**
  2037. * Load a given URL as an instantiated module for SSR.
  2038. */
  2039. ssrLoadModule(url: string, opts?: {
  2040. fixStacktrace?: boolean;
  2041. }): Promise<Record<string, any>>;
  2042. /**
  2043. * Returns a fixed version of the given stack
  2044. */
  2045. ssrRewriteStacktrace(stack: string): string;
  2046. /**
  2047. * Mutates the given SSR error by rewriting the stacktrace
  2048. */
  2049. ssrFixStacktrace(e: Error): void;
  2050. /**
  2051. * Start the server.
  2052. */
  2053. listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>;
  2054. /**
  2055. * Stop the server.
  2056. */
  2057. close(): Promise<void>;
  2058. /**
  2059. * Print server urls
  2060. */
  2061. printUrls(): void;
  2062. /**
  2063. * Restart the server.
  2064. *
  2065. * @param forceOptimize - force the optimizer to re-bundle, same as --force cli flag
  2066. */
  2067. restart(forceOptimize?: boolean): Promise<void>;
  2068. /* Excluded from this release type: _optimizedDeps */
  2069. /* Excluded from this release type: _ssrExternals */
  2070. /* Excluded from this release type: _globImporters */
  2071. /* Excluded from this release type: _restartPromise */
  2072. /* Excluded from this release type: _forceOptimizeOnRestart */
  2073. /* Excluded from this release type: _pendingRequests */
  2074. }
  2075. export declare interface WatchOptions {
  2076. /**
  2077. * Indicates whether the process should continue to run as long as files are being watched. If
  2078. * set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`,
  2079. * even if the process continues to run.
  2080. */
  2081. persistent?: boolean
  2082. /**
  2083. * ([anymatch](https://github.com/micromatch/anymatch)-compatible definition) Defines files/paths to
  2084. * be ignored. The whole relative or absolute path is tested, not just filename. If a function
  2085. * with two arguments is provided, it gets called twice per path - once with a single argument
  2086. * (the path), second time with two arguments (the path and the
  2087. * [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path).
  2088. */
  2089. ignored?: Matcher
  2090. /**
  2091. * If set to `false` then `add`/`addDir` events are also emitted for matching paths while
  2092. * instantiating the watching as chokidar discovers these file paths (before the `ready` event).
  2093. */
  2094. ignoreInitial?: boolean
  2095. /**
  2096. * When `false`, only the symlinks themselves will be watched for changes instead of following
  2097. * the link references and bubbling events through the link's path.
  2098. */
  2099. followSymlinks?: boolean
  2100. /**
  2101. * The base directory from which watch `paths` are to be derived. Paths emitted with events will
  2102. * be relative to this.
  2103. */
  2104. cwd?: string
  2105. /**
  2106. * If set to true then the strings passed to .watch() and .add() are treated as literal path
  2107. * names, even if they look like globs. Default: false.
  2108. */
  2109. disableGlobbing?: boolean
  2110. /**
  2111. * Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU
  2112. * utilization, consider setting this to `false`. It is typically necessary to **set this to
  2113. * `true` to successfully watch files over a network**, and it may be necessary to successfully
  2114. * watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides
  2115. * the `useFsEvents` default.
  2116. */
  2117. usePolling?: boolean
  2118. /**
  2119. * Whether to use the `fsevents` watching interface if available. When set to `true` explicitly
  2120. * and `fsevents` is available this supercedes the `usePolling` setting. When set to `false` on
  2121. * OS X, `usePolling: true` becomes the default.
  2122. */
  2123. useFsEvents?: boolean
  2124. /**
  2125. * If relying upon the [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object that
  2126. * may get passed with `add`, `addDir`, and `change` events, set this to `true` to ensure it is
  2127. * provided even in cases where it wasn't already available from the underlying watch events.
  2128. */
  2129. alwaysStat?: boolean
  2130. /**
  2131. * If set, limits how many levels of subdirectories will be traversed.
  2132. */
  2133. depth?: number
  2134. /**
  2135. * Interval of file system polling.
  2136. */
  2137. interval?: number
  2138. /**
  2139. * Interval of file system polling for binary files. ([see list of binary extensions](https://gi
  2140. * thub.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))
  2141. */
  2142. binaryInterval?: number
  2143. /**
  2144. * Indicates whether to watch files that don't have read permissions if possible. If watching
  2145. * fails due to `EPERM` or `EACCES` with this set to `true`, the errors will be suppressed
  2146. * silently.
  2147. */
  2148. ignorePermissionErrors?: boolean
  2149. /**
  2150. * `true` if `useFsEvents` and `usePolling` are `false`). Automatically filters out artifacts
  2151. * that occur when using editors that use "atomic writes" instead of writing directly to the
  2152. * source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a `change`
  2153. * event rather than `unlink` then `add`. If the default of 100 ms does not work well for you,
  2154. * you can override it by setting `atomic` to a custom value, in milliseconds.
  2155. */
  2156. atomic?: boolean | number
  2157. /**
  2158. * can be set to an object in order to adjust timing params:
  2159. */
  2160. awaitWriteFinish?: AwaitWriteFinishOptions | boolean
  2161. }
  2162. export declare class WebSocket extends EventEmitter {
  2163. /** The connection is not yet open. */
  2164. static readonly CONNECTING: 0
  2165. /** The connection is open and ready to communicate. */
  2166. static readonly OPEN: 1
  2167. /** The connection is in the process of closing. */
  2168. static readonly CLOSING: 2
  2169. /** The connection is closed. */
  2170. static readonly CLOSED: 3
  2171. binaryType: 'nodebuffer' | 'arraybuffer' | 'fragments'
  2172. readonly bufferedAmount: number
  2173. readonly extensions: string
  2174. /** Indicates whether the websocket is paused */
  2175. readonly isPaused: boolean
  2176. readonly protocol: string
  2177. /** The current state of the connection */
  2178. readonly readyState:
  2179. | typeof WebSocket.CONNECTING
  2180. | typeof WebSocket.OPEN
  2181. | typeof WebSocket.CLOSING
  2182. | typeof WebSocket.CLOSED
  2183. readonly url: string
  2184. /** The connection is not yet open. */
  2185. readonly CONNECTING: 0
  2186. /** The connection is open and ready to communicate. */
  2187. readonly OPEN: 1
  2188. /** The connection is in the process of closing. */
  2189. readonly CLOSING: 2
  2190. /** The connection is closed. */
  2191. readonly CLOSED: 3
  2192. onopen: ((event: WebSocket.Event) => void) | null
  2193. onerror: ((event: WebSocket.ErrorEvent) => void) | null
  2194. onclose: ((event: WebSocket.CloseEvent) => void) | null
  2195. onmessage: ((event: WebSocket.MessageEvent) => void) | null
  2196. constructor(address: null)
  2197. constructor(
  2198. address: string | URL_2,
  2199. options?: WebSocket.ClientOptions | ClientRequestArgs
  2200. )
  2201. constructor(
  2202. address: string | URL_2,
  2203. protocols?: string | string[],
  2204. options?: WebSocket.ClientOptions | ClientRequestArgs
  2205. )
  2206. close(code?: number, data?: string | Buffer): void
  2207. ping(data?: any, mask?: boolean, cb?: (err: Error) => void): void
  2208. pong(data?: any, mask?: boolean, cb?: (err: Error) => void): void
  2209. send(data: any, cb?: (err?: Error) => void): void
  2210. send(
  2211. data: any,
  2212. options: {
  2213. mask?: boolean | undefined
  2214. binary?: boolean | undefined
  2215. compress?: boolean | undefined
  2216. fin?: boolean | undefined
  2217. },
  2218. cb?: (err?: Error) => void
  2219. ): void
  2220. terminate(): void
  2221. /**
  2222. * Pause the websocket causing it to stop emitting events. Some events can still be
  2223. * emitted after this is called, until all buffered data is consumed. This method
  2224. * is a noop if the ready state is `CONNECTING` or `CLOSED`.
  2225. */
  2226. pause(): void
  2227. /**
  2228. * Make a paused socket resume emitting events. This method is a noop if the ready
  2229. * state is `CONNECTING` or `CLOSED`.
  2230. */
  2231. resume(): void
  2232. // HTML5 WebSocket events
  2233. addEventListener(
  2234. method: 'message',
  2235. cb: (event: WebSocket.MessageEvent) => void,
  2236. options?: WebSocket.EventListenerOptions
  2237. ): void
  2238. addEventListener(
  2239. method: 'close',
  2240. cb: (event: WebSocket.CloseEvent) => void,
  2241. options?: WebSocket.EventListenerOptions
  2242. ): void
  2243. addEventListener(
  2244. method: 'error',
  2245. cb: (event: WebSocket.ErrorEvent) => void,
  2246. options?: WebSocket.EventListenerOptions
  2247. ): void
  2248. addEventListener(
  2249. method: 'open',
  2250. cb: (event: WebSocket.Event) => void,
  2251. options?: WebSocket.EventListenerOptions
  2252. ): void
  2253. removeEventListener(
  2254. method: 'message',
  2255. cb: (event: WebSocket.MessageEvent) => void
  2256. ): void
  2257. removeEventListener(
  2258. method: 'close',
  2259. cb: (event: WebSocket.CloseEvent) => void
  2260. ): void
  2261. removeEventListener(
  2262. method: 'error',
  2263. cb: (event: WebSocket.ErrorEvent) => void
  2264. ): void
  2265. removeEventListener(
  2266. method: 'open',
  2267. cb: (event: WebSocket.Event) => void
  2268. ): void
  2269. // Events
  2270. on(
  2271. event: 'close',
  2272. listener: (this: WebSocket, code: number, reason: Buffer) => void
  2273. ): this
  2274. on(event: 'error', listener: (this: WebSocket, err: Error) => void): this
  2275. on(
  2276. event: 'upgrade',
  2277. listener: (this: WebSocket, request: IncomingMessage) => void
  2278. ): this
  2279. on(
  2280. event: 'message',
  2281. listener: (
  2282. this: WebSocket,
  2283. data: WebSocket.RawData,
  2284. isBinary: boolean
  2285. ) => void
  2286. ): this
  2287. on(event: 'open', listener: (this: WebSocket) => void): this
  2288. on(
  2289. event: 'ping' | 'pong',
  2290. listener: (this: WebSocket, data: Buffer) => void
  2291. ): this
  2292. on(
  2293. event: 'unexpected-response',
  2294. listener: (
  2295. this: WebSocket,
  2296. request: ClientRequest,
  2297. response: IncomingMessage
  2298. ) => void
  2299. ): this
  2300. on(
  2301. event: string | symbol,
  2302. listener: (this: WebSocket, ...args: any[]) => void
  2303. ): this
  2304. once(
  2305. event: 'close',
  2306. listener: (this: WebSocket, code: number, reason: Buffer) => void
  2307. ): this
  2308. once(event: 'error', listener: (this: WebSocket, err: Error) => void): this
  2309. once(
  2310. event: 'upgrade',
  2311. listener: (this: WebSocket, request: IncomingMessage) => void
  2312. ): this
  2313. once(
  2314. event: 'message',
  2315. listener: (
  2316. this: WebSocket,
  2317. data: WebSocket.RawData,
  2318. isBinary: boolean
  2319. ) => void
  2320. ): this
  2321. once(event: 'open', listener: (this: WebSocket) => void): this
  2322. once(
  2323. event: 'ping' | 'pong',
  2324. listener: (this: WebSocket, data: Buffer) => void
  2325. ): this
  2326. once(
  2327. event: 'unexpected-response',
  2328. listener: (
  2329. this: WebSocket,
  2330. request: ClientRequest,
  2331. response: IncomingMessage
  2332. ) => void
  2333. ): this
  2334. once(
  2335. event: string | symbol,
  2336. listener: (this: WebSocket, ...args: any[]) => void
  2337. ): this
  2338. off(
  2339. event: 'close',
  2340. listener: (this: WebSocket, code: number, reason: Buffer) => void
  2341. ): this
  2342. off(event: 'error', listener: (this: WebSocket, err: Error) => void): this
  2343. off(
  2344. event: 'upgrade',
  2345. listener: (this: WebSocket, request: IncomingMessage) => void
  2346. ): this
  2347. off(
  2348. event: 'message',
  2349. listener: (
  2350. this: WebSocket,
  2351. data: WebSocket.RawData,
  2352. isBinary: boolean
  2353. ) => void
  2354. ): this
  2355. off(event: 'open', listener: (this: WebSocket) => void): this
  2356. off(
  2357. event: 'ping' | 'pong',
  2358. listener: (this: WebSocket, data: Buffer) => void
  2359. ): this
  2360. off(
  2361. event: 'unexpected-response',
  2362. listener: (
  2363. this: WebSocket,
  2364. request: ClientRequest,
  2365. response: IncomingMessage
  2366. ) => void
  2367. ): this
  2368. off(
  2369. event: string | symbol,
  2370. listener: (this: WebSocket, ...args: any[]) => void
  2371. ): this
  2372. addListener(
  2373. event: 'close',
  2374. listener: (code: number, reason: Buffer) => void
  2375. ): this
  2376. addListener(event: 'error', listener: (err: Error) => void): this
  2377. addListener(
  2378. event: 'upgrade',
  2379. listener: (request: IncomingMessage) => void
  2380. ): this
  2381. addListener(
  2382. event: 'message',
  2383. listener: (data: WebSocket.RawData, isBinary: boolean) => void
  2384. ): this
  2385. addListener(event: 'open', listener: () => void): this
  2386. addListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
  2387. addListener(
  2388. event: 'unexpected-response',
  2389. listener: (request: ClientRequest, response: IncomingMessage) => void
  2390. ): this
  2391. addListener(event: string | symbol, listener: (...args: any[]) => void): this
  2392. removeListener(
  2393. event: 'close',
  2394. listener: (code: number, reason: Buffer) => void
  2395. ): this
  2396. removeListener(event: 'error', listener: (err: Error) => void): this
  2397. removeListener(
  2398. event: 'upgrade',
  2399. listener: (request: IncomingMessage) => void
  2400. ): this
  2401. removeListener(
  2402. event: 'message',
  2403. listener: (data: WebSocket.RawData, isBinary: boolean) => void
  2404. ): this
  2405. removeListener(event: 'open', listener: () => void): this
  2406. removeListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
  2407. removeListener(
  2408. event: 'unexpected-response',
  2409. listener: (request: ClientRequest, response: IncomingMessage) => void
  2410. ): this
  2411. removeListener(
  2412. event: string | symbol,
  2413. listener: (...args: any[]) => void
  2414. ): this
  2415. }
  2416. export declare namespace WebSocket {
  2417. /**
  2418. * Data represents the raw message payload received over the WebSocket.
  2419. */
  2420. export type RawData = Buffer | ArrayBuffer | Buffer[]
  2421. /**
  2422. * Data represents the message payload received over the WebSocket.
  2423. */
  2424. export type Data = string | Buffer | ArrayBuffer | Buffer[]
  2425. /**
  2426. * CertMeta represents the accepted types for certificate & key data.
  2427. */
  2428. export type CertMeta = string | string[] | Buffer | Buffer[]
  2429. /**
  2430. * VerifyClientCallbackSync is a synchronous callback used to inspect the
  2431. * incoming message. The return value (boolean) of the function determines
  2432. * whether or not to accept the handshake.
  2433. */
  2434. export type VerifyClientCallbackSync = (info: {
  2435. origin: string
  2436. secure: boolean
  2437. req: IncomingMessage
  2438. }) => boolean
  2439. /**
  2440. * VerifyClientCallbackAsync is an asynchronous callback used to inspect the
  2441. * incoming message. The return value (boolean) of the function determines
  2442. * whether or not to accept the handshake.
  2443. */
  2444. export type VerifyClientCallbackAsync = (
  2445. info: { origin: string; secure: boolean; req: IncomingMessage },
  2446. callback: (
  2447. res: boolean,
  2448. code?: number,
  2449. message?: string,
  2450. headers?: OutgoingHttpHeaders
  2451. ) => void
  2452. ) => void
  2453. export interface ClientOptions extends SecureContextOptions {
  2454. protocol?: string | undefined
  2455. followRedirects?: boolean | undefined
  2456. generateMask?(mask: Buffer): void
  2457. handshakeTimeout?: number | undefined
  2458. maxRedirects?: number | undefined
  2459. perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
  2460. localAddress?: string | undefined
  2461. protocolVersion?: number | undefined
  2462. headers?: { [key: string]: string } | undefined
  2463. origin?: string | undefined
  2464. agent?: Agent | undefined
  2465. host?: string | undefined
  2466. family?: number | undefined
  2467. checkServerIdentity?(servername: string, cert: CertMeta): boolean
  2468. rejectUnauthorized?: boolean | undefined
  2469. maxPayload?: number | undefined
  2470. skipUTF8Validation?: boolean | undefined
  2471. }
  2472. export interface PerMessageDeflateOptions {
  2473. serverNoContextTakeover?: boolean | undefined
  2474. clientNoContextTakeover?: boolean | undefined
  2475. serverMaxWindowBits?: number | undefined
  2476. clientMaxWindowBits?: number | undefined
  2477. zlibDeflateOptions?:
  2478. | {
  2479. flush?: number | undefined
  2480. finishFlush?: number | undefined
  2481. chunkSize?: number | undefined
  2482. windowBits?: number | undefined
  2483. level?: number | undefined
  2484. memLevel?: number | undefined
  2485. strategy?: number | undefined
  2486. dictionary?: Buffer | Buffer[] | DataView | undefined
  2487. info?: boolean | undefined
  2488. }
  2489. | undefined
  2490. zlibInflateOptions?: ZlibOptions | undefined
  2491. threshold?: number | undefined
  2492. concurrencyLimit?: number | undefined
  2493. }
  2494. export interface Event {
  2495. type: string
  2496. target: WebSocket
  2497. }
  2498. export interface ErrorEvent {
  2499. error: any
  2500. message: string
  2501. type: string
  2502. target: WebSocket
  2503. }
  2504. export interface CloseEvent {
  2505. wasClean: boolean
  2506. code: number
  2507. reason: string
  2508. type: string
  2509. target: WebSocket
  2510. }
  2511. export interface MessageEvent {
  2512. data: Data
  2513. type: string
  2514. target: WebSocket
  2515. }
  2516. export interface EventListenerOptions {
  2517. once?: boolean | undefined
  2518. }
  2519. export interface ServerOptions {
  2520. host?: string | undefined
  2521. port?: number | undefined
  2522. backlog?: number | undefined
  2523. server?: Server | Server_2 | undefined
  2524. verifyClient?:
  2525. | VerifyClientCallbackAsync
  2526. | VerifyClientCallbackSync
  2527. | undefined
  2528. handleProtocols?: (
  2529. protocols: Set<string>,
  2530. request: IncomingMessage
  2531. ) => string | false
  2532. path?: string | undefined
  2533. noServer?: boolean | undefined
  2534. clientTracking?: boolean | undefined
  2535. perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
  2536. maxPayload?: number | undefined
  2537. skipUTF8Validation?: boolean | undefined
  2538. WebSocket?: typeof WebSocket.WebSocket | undefined
  2539. }
  2540. export interface AddressInfo {
  2541. address: string
  2542. family: string
  2543. port: number
  2544. }
  2545. // WebSocket Server
  2546. export class Server<T extends WebSocket = WebSocket> extends EventEmitter {
  2547. options: ServerOptions
  2548. path: string
  2549. clients: Set<T>
  2550. constructor(options?: ServerOptions, callback?: () => void)
  2551. address(): AddressInfo | string
  2552. close(cb?: (err?: Error) => void): void
  2553. handleUpgrade(
  2554. request: IncomingMessage,
  2555. socket: Duplex,
  2556. upgradeHead: Buffer,
  2557. callback: (client: T, request: IncomingMessage) => void
  2558. ): void
  2559. shouldHandle(request: IncomingMessage): boolean | Promise<boolean>
  2560. // Events
  2561. on(
  2562. event: 'connection',
  2563. cb: (this: Server<T>, socket: T, request: IncomingMessage) => void
  2564. ): this
  2565. on(event: 'error', cb: (this: Server<T>, error: Error) => void): this
  2566. on(
  2567. event: 'headers',
  2568. cb: (this: Server<T>, headers: string[], request: IncomingMessage) => void
  2569. ): this
  2570. on(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
  2571. on(
  2572. event: string | symbol,
  2573. listener: (this: Server<T>, ...args: any[]) => void
  2574. ): this
  2575. once(
  2576. event: 'connection',
  2577. cb: (this: Server<T>, socket: T, request: IncomingMessage) => void
  2578. ): this
  2579. once(event: 'error', cb: (this: Server<T>, error: Error) => void): this
  2580. once(
  2581. event: 'headers',
  2582. cb: (this: Server<T>, headers: string[], request: IncomingMessage) => void
  2583. ): this
  2584. once(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
  2585. once(
  2586. event: string | symbol,
  2587. listener: (this: Server<T>, ...args: any[]) => void
  2588. ): this
  2589. off(
  2590. event: 'connection',
  2591. cb: (this: Server<T>, socket: T, request: IncomingMessage) => void
  2592. ): this
  2593. off(event: 'error', cb: (this: Server<T>, error: Error) => void): this
  2594. off(
  2595. event: 'headers',
  2596. cb: (this: Server<T>, headers: string[], request: IncomingMessage) => void
  2597. ): this
  2598. off(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
  2599. off(
  2600. event: string | symbol,
  2601. listener: (this: Server<T>, ...args: any[]) => void
  2602. ): this
  2603. addListener(
  2604. event: 'connection',
  2605. cb: (client: T, request: IncomingMessage) => void
  2606. ): this
  2607. addListener(event: 'error', cb: (err: Error) => void): this
  2608. addListener(
  2609. event: 'headers',
  2610. cb: (headers: string[], request: IncomingMessage) => void
  2611. ): this
  2612. addListener(event: 'close' | 'listening', cb: () => void): this
  2613. addListener(
  2614. event: string | symbol,
  2615. listener: (...args: any[]) => void
  2616. ): this
  2617. removeListener(event: 'connection', cb: (client: T) => void): this
  2618. removeListener(event: 'error', cb: (err: Error) => void): this
  2619. removeListener(
  2620. event: 'headers',
  2621. cb: (headers: string[], request: IncomingMessage) => void
  2622. ): this
  2623. removeListener(event: 'close' | 'listening', cb: () => void): this
  2624. removeListener(
  2625. event: string | symbol,
  2626. listener: (...args: any[]) => void
  2627. ): this
  2628. }
  2629. const WebSocketServer: typeof Server
  2630. export interface WebSocketServer extends Server {} // tslint:disable-line no-empty-interface
  2631. const WebSocket: typeof WebSocketAlias
  2632. export interface WebSocket extends WebSocketAlias {} // tslint:disable-line no-empty-interface
  2633. // WebSocket stream
  2634. export function createWebSocketStream(
  2635. websocket: WebSocket,
  2636. options?: DuplexOptions
  2637. ): Duplex
  2638. }
  2639. export declare const WebSocketAlias: typeof WebSocket;
  2640. export declare interface WebSocketAlias extends WebSocket {}
  2641. export declare interface WebSocketClient {
  2642. /**
  2643. * Send event to the client
  2644. */
  2645. send(payload: HMRPayload): void;
  2646. /**
  2647. * Send custom event
  2648. */
  2649. send(event: string, payload?: CustomPayload['data']): void;
  2650. /**
  2651. * The raw WebSocket instance
  2652. * @advanced
  2653. */
  2654. socket: WebSocket;
  2655. }
  2656. export declare type WebSocketCustomListener<T> = (data: T, client: WebSocketClient) => void;
  2657. export declare interface WebSocketServer {
  2658. /**
  2659. * Get all connected clients.
  2660. */
  2661. clients: Set<WebSocketClient>;
  2662. /**
  2663. * Boardcast events to all clients
  2664. */
  2665. send(payload: HMRPayload): void;
  2666. /**
  2667. * Send custom event
  2668. */
  2669. send<T extends string>(event: T, payload?: InferCustomEventPayload<T>): void;
  2670. /**
  2671. * Disconnect all clients and terminate the server.
  2672. */
  2673. close(): Promise<void>;
  2674. /**
  2675. * Handle custom event emitted by `import.meta.hot.send`
  2676. */
  2677. on: WebSocket.Server['on'] & {
  2678. <T extends string>(event: T, listener: WebSocketCustomListener<InferCustomEventPayload<T>>): void;
  2679. };
  2680. /**
  2681. * Unregister event listener.
  2682. */
  2683. off: WebSocket.Server['off'] & {
  2684. (event: string, listener: Function): void;
  2685. };
  2686. }
  2687. export { }