vite 6.0.0-alpha.14 → 6.0.0-alpha.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
1
  /// <reference types="node" />
2
- import { PluginHooks, RollupError, InputOptions, CustomPluginOptions, PartialResolvedId, SourceDescription, SourceMap, LoadResult, ModuleInfo, RollupOptions, WatcherOptions, InputOption, ModuleFormat, RollupOutput, RollupWatcher, SourceMapInput, ExistingRawSourceMap, OutputBundle, OutputChunk, ObjectHook, ResolveIdResult, GetManualChunk } from 'rollup';
2
+ import { PluginHooks, RollupError, SourceMap, ModuleInfo, PartialResolvedId, RollupOptions, WatcherOptions, InputOption, ModuleFormat, RollupOutput, RollupWatcher, InputOptions, CustomPluginOptions, SourceDescription, LoadResult, SourceMapInput, ExistingRawSourceMap, OutputBundle, OutputChunk, ObjectHook, ResolveIdResult, GetManualChunk } from 'rollup';
3
3
  import * as rollup from 'rollup';
4
4
  export { rollup as Rollup };
5
5
  export { parseAst, parseAstAsync } from 'rollup/parseAst';
6
6
  import * as http from 'node:http';
7
- import { OutgoingHttpHeaders, ClientRequestArgs, IncomingMessage, ClientRequest, Agent, Server, ServerResponse } from 'node:http';
7
+ import { OutgoingHttpHeaders, Server, ClientRequestArgs, IncomingMessage, ClientRequest, Agent, ServerResponse } from 'node:http';
8
8
  import { Http2SecureServer } from 'node:http2';
9
9
  import * as fs from 'node:fs';
10
10
  import * as events from 'node:events';
@@ -15,16 +15,16 @@ import * as url from 'node:url';
15
15
  import { URL } from 'node:url';
16
16
  import * as stream from 'node:stream';
17
17
  import { Duplex, DuplexOptions } from 'node:stream';
18
- import { SecureContextOptions } from 'node:tls';
19
- import { ZlibOptions } from 'node:zlib';
20
- import { HMRPayload, CustomPayload } from '../../types/hmrPayload.js';
21
- export { ConnectedPayload, CustomPayload, ErrorPayload, FullReloadPayload, HMRPayload, PrunePayload, Update, UpdatePayload } from '../../types/hmrPayload.js';
22
- import { InferCustomEventPayload } from '../../types/customEvent.js';
23
- export { CustomEventMap, InferCustomEventPayload, InvalidatePayload } from '../../types/customEvent.js';
24
18
  import { FetchResult, ModuleRunnerOptions, ModuleRunnerHMRConnection, ModuleRunnerHmr, ModuleEvaluator, ModuleRunner } from 'vite/module-runner';
25
19
  export { FetchFunction, FetchResult } from 'vite/module-runner';
26
20
  import { BuildOptions as esbuild_BuildOptions, TransformOptions as esbuild_TransformOptions, TransformResult as esbuild_TransformResult } from 'esbuild';
27
21
  export { TransformOptions as EsbuildTransformOptions, version as esbuildVersion } from 'esbuild';
22
+ import { HMRPayload, CustomPayload } from '../../types/hmrPayload.js';
23
+ export { ConnectedPayload, CustomPayload, ErrorPayload, FullReloadPayload, HMRPayload, PrunePayload, Update, UpdatePayload } from '../../types/hmrPayload.js';
24
+ import { InferCustomEventPayload } from '../../types/customEvent.js';
25
+ export { CustomEventMap, InferCustomEventPayload, InvalidatePayload } from '../../types/customEvent.js';
26
+ import { SecureContextOptions } from 'node:tls';
27
+ import { ZlibOptions } from 'node:zlib';
28
28
  import * as PostCSS from 'postcss';
29
29
  export { GeneralImportGlobOptions, ImportGlobFunction, ImportGlobOptions, KnownAsTypeMap } from '../../types/importGlob.js';
30
30
  export { ChunkMetadata } from '../../types/metadata.js';
@@ -783,835 +783,207 @@ type CLIShortcut<Server = ViteDevServer | PreviewServer> = {
783
783
  action?(server: Server): void | Promise<void>;
784
784
  };
785
785
 
786
+ declare class PartialEnvironment {
787
+ name: string;
788
+ config: ResolvedConfig;
789
+ options: ResolvedEnvironmentOptions;
790
+ logger: Logger;
791
+ constructor(name: string, config: ResolvedConfig, options?: ResolvedEnvironmentOptions);
792
+ }
793
+ declare class BaseEnvironment extends PartialEnvironment {
794
+ get plugins(): Plugin[];
795
+ constructor(name: string, config: ResolvedConfig, options?: ResolvedEnvironmentOptions);
796
+ }
786
797
  /**
787
- * This file is refactored into TypeScript based on
788
- * https://github.com/preactjs/wmr/blob/main/packages/wmr/src/lib/rollup-plugin-container.js
798
+ * This is used both to avoid users to hardcode conditions like
799
+ * !scan && !build => dev
789
800
  */
801
+ declare class FutureCompatEnvironment extends BaseEnvironment {
802
+ mode: "futureCompat";
803
+ }
790
804
 
791
- interface EnvironmentPluginContainer {
792
- options: InputOptions;
793
- buildStart(options: InputOptions): Promise<void>;
794
- resolveId(id: string, importer: string | undefined, options?: {
795
- attributes?: Record<string, string>;
796
- custom?: CustomPluginOptions;
797
- skip?: Set<Plugin>;
798
- isEntry?: boolean;
799
- }): Promise<PartialResolvedId | null>;
800
- transform(code: string, id: string, options?: {
801
- inMap?: SourceDescription['map'];
802
- }): Promise<{
803
- code: string;
804
- map: SourceMap | {
805
- mappings: '';
806
- } | null;
807
- }>;
808
- load(id: string, options?: {}): Promise<LoadResult | null>;
809
- watchChange(id: string, change: {
810
- event: 'create' | 'update' | 'delete';
811
- }): Promise<void>;
812
- close(): Promise<void>;
805
+ interface FetchModuleOptions {
806
+ inlineSourceMap?: boolean;
807
+ processSourceMap?<T extends NonNullable<TransformResult['map']>>(map: T): T;
813
808
  }
814
- interface PluginContainer {
815
- options: InputOptions;
816
- buildStart(options: InputOptions): Promise<void>;
817
- resolveId(id: string, importer?: string, options?: {
818
- attributes?: Record<string, string>;
819
- custom?: CustomPluginOptions;
820
- skip?: Set<Plugin>;
821
- ssr?: boolean;
822
- environment?: PluginEnvironment;
823
- isEntry?: boolean;
824
- }): Promise<PartialResolvedId | null>;
825
- transform(code: string, id: string, options?: {
826
- inMap?: SourceDescription['map'];
827
- ssr?: boolean;
828
- environment?: PluginEnvironment;
829
- }): Promise<{
830
- code: string;
831
- map: SourceMap | {
832
- mappings: '';
833
- } | null;
834
- }>;
835
- load(id: string, options?: {
836
- ssr?: boolean;
837
- environment?: PluginEnvironment;
838
- }): Promise<LoadResult | null>;
839
- watchChange(id: string, change: {
840
- event: 'create' | 'update' | 'delete';
841
- }): Promise<void>;
842
- close(): Promise<void>;
809
+ /**
810
+ * Fetch module information for Vite runner.
811
+ * @experimental
812
+ */
813
+ declare function fetchModule(environment: DevEnvironment, url: string, importer?: string, options?: FetchModuleOptions): Promise<FetchResult>;
814
+
815
+ declare class ScanEnvironment extends BaseEnvironment {
816
+ mode: "scan";
817
+ get pluginContainer(): EnvironmentPluginContainer;
818
+ init(): Promise<void>;
843
819
  }
844
820
 
845
- // Modified and inlined to avoid extra dependency
846
- // Source: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/ws/index.d.ts
847
-
848
- declare const WebSocketAlias: typeof WebSocket
849
- interface WebSocketAlias extends WebSocket {}
850
- // WebSocket socket.
851
- declare class WebSocket extends EventEmitter {
852
- /** The connection is not yet open. */
853
- static readonly CONNECTING: 0
854
- /** The connection is open and ready to communicate. */
855
- static readonly OPEN: 1
856
- /** The connection is in the process of closing. */
857
- static readonly CLOSING: 2
858
- /** The connection is closed. */
859
- static readonly CLOSED: 3
860
-
861
- binaryType: 'nodebuffer' | 'arraybuffer' | 'fragments'
862
- readonly bufferedAmount: number
863
- readonly extensions: string
864
- /** Indicates whether the websocket is paused */
865
- readonly isPaused: boolean
866
- readonly protocol: string
867
- /** The current state of the connection */
868
- readonly readyState:
869
- | typeof WebSocket.CONNECTING
870
- | typeof WebSocket.OPEN
871
- | typeof WebSocket.CLOSING
872
- | typeof WebSocket.CLOSED
873
- readonly url: string
874
-
875
- /** The connection is not yet open. */
876
- readonly CONNECTING: 0
877
- /** The connection is open and ready to communicate. */
878
- readonly OPEN: 1
879
- /** The connection is in the process of closing. */
880
- readonly CLOSING: 2
881
- /** The connection is closed. */
882
- readonly CLOSED: 3
883
-
884
- onopen: ((event: WebSocket.Event) => void) | null
885
- onerror: ((event: WebSocket.ErrorEvent) => void) | null
886
- onclose: ((event: WebSocket.CloseEvent) => void) | null
887
- onmessage: ((event: WebSocket.MessageEvent) => void) | null
888
-
889
- constructor(address: null)
890
- constructor(
891
- address: string | URL,
892
- options?: WebSocket.ClientOptions | ClientRequestArgs,
893
- )
894
- constructor(
895
- address: string | URL,
896
- protocols?: string | string[],
897
- options?: WebSocket.ClientOptions | ClientRequestArgs,
898
- )
899
-
900
- close(code?: number, data?: string | Buffer): void
901
- ping(data?: any, mask?: boolean, cb?: (err: Error) => void): void
902
- pong(data?: any, mask?: boolean, cb?: (err: Error) => void): void
903
- send(data: any, cb?: (err?: Error) => void): void
904
- send(
905
- data: any,
906
- options: {
907
- mask?: boolean | undefined
908
- binary?: boolean | undefined
909
- compress?: boolean | undefined
910
- fin?: boolean | undefined
911
- },
912
- cb?: (err?: Error) => void,
913
- ): void
914
- terminate(): void
915
-
916
- /**
917
- * Pause the websocket causing it to stop emitting events. Some events can still be
918
- * emitted after this is called, until all buffered data is consumed. This method
919
- * is a noop if the ready state is `CONNECTING` or `CLOSED`.
920
- */
921
- pause(): void
922
- /**
923
- * Make a paused socket resume emitting events. This method is a noop if the ready
924
- * state is `CONNECTING` or `CLOSED`.
925
- */
926
- resume(): void
927
-
928
- // HTML5 WebSocket events
929
- addEventListener(
930
- method: 'message',
931
- cb: (event: WebSocket.MessageEvent) => void,
932
- options?: WebSocket.EventListenerOptions,
933
- ): void
934
- addEventListener(
935
- method: 'close',
936
- cb: (event: WebSocket.CloseEvent) => void,
937
- options?: WebSocket.EventListenerOptions,
938
- ): void
939
- addEventListener(
940
- method: 'error',
941
- cb: (event: WebSocket.ErrorEvent) => void,
942
- options?: WebSocket.EventListenerOptions,
943
- ): void
944
- addEventListener(
945
- method: 'open',
946
- cb: (event: WebSocket.Event) => void,
947
- options?: WebSocket.EventListenerOptions,
948
- ): void
949
-
950
- removeEventListener(
951
- method: 'message',
952
- cb: (event: WebSocket.MessageEvent) => void,
953
- ): void
954
- removeEventListener(
955
- method: 'close',
956
- cb: (event: WebSocket.CloseEvent) => void,
957
- ): void
958
- removeEventListener(
959
- method: 'error',
960
- cb: (event: WebSocket.ErrorEvent) => void,
961
- ): void
962
- removeEventListener(
963
- method: 'open',
964
- cb: (event: WebSocket.Event) => void,
965
- ): void
966
-
967
- // Events
968
- on(
969
- event: 'close',
970
- listener: (this: WebSocket, code: number, reason: Buffer) => void,
971
- ): this
972
- on(event: 'error', listener: (this: WebSocket, err: Error) => void): this
973
- on(
974
- event: 'upgrade',
975
- listener: (this: WebSocket, request: IncomingMessage) => void,
976
- ): this
977
- on(
978
- event: 'message',
979
- listener: (
980
- this: WebSocket,
981
- data: WebSocket.RawData,
982
- isBinary: boolean,
983
- ) => void,
984
- ): this
985
- on(event: 'open', listener: (this: WebSocket) => void): this
986
- on(
987
- event: 'ping' | 'pong',
988
- listener: (this: WebSocket, data: Buffer) => void,
989
- ): this
990
- on(
991
- event: 'unexpected-response',
992
- listener: (
993
- this: WebSocket,
994
- request: ClientRequest,
995
- response: IncomingMessage,
996
- ) => void,
997
- ): this
998
- on(
999
- event: string | symbol,
1000
- listener: (this: WebSocket, ...args: any[]) => void,
1001
- ): this
1002
-
1003
- once(
1004
- event: 'close',
1005
- listener: (this: WebSocket, code: number, reason: Buffer) => void,
1006
- ): this
1007
- once(event: 'error', listener: (this: WebSocket, err: Error) => void): this
1008
- once(
1009
- event: 'upgrade',
1010
- listener: (this: WebSocket, request: IncomingMessage) => void,
1011
- ): this
1012
- once(
1013
- event: 'message',
1014
- listener: (
1015
- this: WebSocket,
1016
- data: WebSocket.RawData,
1017
- isBinary: boolean,
1018
- ) => void,
1019
- ): this
1020
- once(event: 'open', listener: (this: WebSocket) => void): this
1021
- once(
1022
- event: 'ping' | 'pong',
1023
- listener: (this: WebSocket, data: Buffer) => void,
1024
- ): this
1025
- once(
1026
- event: 'unexpected-response',
1027
- listener: (
1028
- this: WebSocket,
1029
- request: ClientRequest,
1030
- response: IncomingMessage,
1031
- ) => void,
1032
- ): this
1033
- once(
1034
- event: string | symbol,
1035
- listener: (this: WebSocket, ...args: any[]) => void,
1036
- ): this
1037
-
1038
- off(
1039
- event: 'close',
1040
- listener: (this: WebSocket, code: number, reason: Buffer) => void,
1041
- ): this
1042
- off(event: 'error', listener: (this: WebSocket, err: Error) => void): this
1043
- off(
1044
- event: 'upgrade',
1045
- listener: (this: WebSocket, request: IncomingMessage) => void,
1046
- ): this
1047
- off(
1048
- event: 'message',
1049
- listener: (
1050
- this: WebSocket,
1051
- data: WebSocket.RawData,
1052
- isBinary: boolean,
1053
- ) => void,
1054
- ): this
1055
- off(event: 'open', listener: (this: WebSocket) => void): this
1056
- off(
1057
- event: 'ping' | 'pong',
1058
- listener: (this: WebSocket, data: Buffer) => void,
1059
- ): this
1060
- off(
1061
- event: 'unexpected-response',
1062
- listener: (
1063
- this: WebSocket,
1064
- request: ClientRequest,
1065
- response: IncomingMessage,
1066
- ) => void,
1067
- ): this
1068
- off(
1069
- event: string | symbol,
1070
- listener: (this: WebSocket, ...args: any[]) => void,
1071
- ): this
1072
-
1073
- addListener(
1074
- event: 'close',
1075
- listener: (code: number, reason: Buffer) => void,
1076
- ): this
1077
- addListener(event: 'error', listener: (err: Error) => void): this
1078
- addListener(
1079
- event: 'upgrade',
1080
- listener: (request: IncomingMessage) => void,
1081
- ): this
1082
- addListener(
1083
- event: 'message',
1084
- listener: (data: WebSocket.RawData, isBinary: boolean) => void,
1085
- ): this
1086
- addListener(event: 'open', listener: () => void): this
1087
- addListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
1088
- addListener(
1089
- event: 'unexpected-response',
1090
- listener: (request: ClientRequest, response: IncomingMessage) => void,
1091
- ): this
1092
- addListener(event: string | symbol, listener: (...args: any[]) => void): this
1093
-
1094
- removeListener(
1095
- event: 'close',
1096
- listener: (code: number, reason: Buffer) => void,
1097
- ): this
1098
- removeListener(event: 'error', listener: (err: Error) => void): this
1099
- removeListener(
1100
- event: 'upgrade',
1101
- listener: (request: IncomingMessage) => void,
1102
- ): this
1103
- removeListener(
1104
- event: 'message',
1105
- listener: (data: WebSocket.RawData, isBinary: boolean) => void,
1106
- ): this
1107
- removeListener(event: 'open', listener: () => void): this
1108
- removeListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
1109
- removeListener(
1110
- event: 'unexpected-response',
1111
- listener: (request: ClientRequest, response: IncomingMessage) => void,
1112
- ): this
1113
- removeListener(
1114
- event: string | symbol,
1115
- listener: (...args: any[]) => void,
1116
- ): this
1117
- }
1118
- // tslint:disable-line no-empty-interface
1119
-
1120
- declare namespace WebSocket {
1121
- /**
1122
- * Data represents the raw message payload received over the WebSocket.
1123
- */
1124
- type RawData = Buffer | ArrayBuffer | Buffer[]
1125
-
1126
- /**
1127
- * Data represents the message payload received over the WebSocket.
1128
- */
1129
- type Data = string | Buffer | ArrayBuffer | Buffer[]
1130
-
1131
- /**
1132
- * CertMeta represents the accepted types for certificate & key data.
1133
- */
1134
- type CertMeta = string | string[] | Buffer | Buffer[]
1135
-
1136
- /**
1137
- * VerifyClientCallbackSync is a synchronous callback used to inspect the
1138
- * incoming message. The return value (boolean) of the function determines
1139
- * whether or not to accept the handshake.
1140
- */
1141
- type VerifyClientCallbackSync = (info: {
1142
- origin: string
1143
- secure: boolean
1144
- req: IncomingMessage
1145
- }) => boolean
1146
-
1147
- /**
1148
- * VerifyClientCallbackAsync is an asynchronous callback used to inspect the
1149
- * incoming message. The return value (boolean) of the function determines
1150
- * whether or not to accept the handshake.
1151
- */
1152
- type VerifyClientCallbackAsync = (
1153
- info: { origin: string; secure: boolean; req: IncomingMessage },
1154
- callback: (
1155
- res: boolean,
1156
- code?: number,
1157
- message?: string,
1158
- headers?: OutgoingHttpHeaders,
1159
- ) => void,
1160
- ) => void
1161
-
1162
- interface ClientOptions extends SecureContextOptions {
1163
- protocol?: string | undefined
1164
- followRedirects?: boolean | undefined
1165
- generateMask?(mask: Buffer): void
1166
- handshakeTimeout?: number | undefined
1167
- maxRedirects?: number | undefined
1168
- perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
1169
- localAddress?: string | undefined
1170
- protocolVersion?: number | undefined
1171
- headers?: { [key: string]: string } | undefined
1172
- origin?: string | undefined
1173
- agent?: Agent | undefined
1174
- host?: string | undefined
1175
- family?: number | undefined
1176
- checkServerIdentity?(servername: string, cert: CertMeta): boolean
1177
- rejectUnauthorized?: boolean | undefined
1178
- maxPayload?: number | undefined
1179
- skipUTF8Validation?: boolean | undefined
1180
- }
1181
-
1182
- interface PerMessageDeflateOptions {
1183
- serverNoContextTakeover?: boolean | undefined
1184
- clientNoContextTakeover?: boolean | undefined
1185
- serverMaxWindowBits?: number | undefined
1186
- clientMaxWindowBits?: number | undefined
1187
- zlibDeflateOptions?:
1188
- | {
1189
- flush?: number | undefined
1190
- finishFlush?: number | undefined
1191
- chunkSize?: number | undefined
1192
- windowBits?: number | undefined
1193
- level?: number | undefined
1194
- memLevel?: number | undefined
1195
- strategy?: number | undefined
1196
- dictionary?: Buffer | Buffer[] | DataView | undefined
1197
- info?: boolean | undefined
1198
- }
1199
- | undefined
1200
- zlibInflateOptions?: ZlibOptions | undefined
1201
- threshold?: number | undefined
1202
- concurrencyLimit?: number | undefined
1203
- }
1204
-
1205
- interface Event {
1206
- type: string
1207
- target: WebSocket
1208
- }
1209
-
1210
- interface ErrorEvent {
1211
- error: any
1212
- message: string
1213
- type: string
1214
- target: WebSocket
1215
- }
1216
-
1217
- interface CloseEvent {
1218
- wasClean: boolean
1219
- code: number
1220
- reason: string
1221
- type: string
1222
- target: WebSocket
1223
- }
1224
-
1225
- interface MessageEvent {
1226
- data: Data
1227
- type: string
1228
- target: WebSocket
1229
- }
1230
-
1231
- interface EventListenerOptions {
1232
- once?: boolean | undefined
1233
- }
1234
-
1235
- interface ServerOptions {
1236
- host?: string | undefined
1237
- port?: number | undefined
1238
- backlog?: number | undefined
1239
- server?: Server | HttpsServer | undefined
1240
- verifyClient?:
1241
- | VerifyClientCallbackAsync
1242
- | VerifyClientCallbackSync
1243
- | undefined
1244
- handleProtocols?: (
1245
- protocols: Set<string>,
1246
- request: IncomingMessage,
1247
- ) => string | false
1248
- path?: string | undefined
1249
- noServer?: boolean | undefined
1250
- clientTracking?: boolean | undefined
1251
- perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
1252
- maxPayload?: number | undefined
1253
- skipUTF8Validation?: boolean | undefined
1254
- WebSocket?: typeof WebSocket.WebSocket | undefined
1255
- }
1256
-
1257
- interface AddressInfo {
1258
- address: string
1259
- family: string
1260
- port: number
1261
- }
1262
-
1263
- // WebSocket Server
1264
- class Server<T extends WebSocket = WebSocket> extends EventEmitter {
1265
- options: ServerOptions
1266
- path: string
1267
- clients: Set<T>
1268
-
1269
- constructor(options?: ServerOptions, callback?: () => void)
1270
-
1271
- address(): AddressInfo | string
1272
- close(cb?: (err?: Error) => void): void
1273
- handleUpgrade(
1274
- request: IncomingMessage,
1275
- socket: Duplex,
1276
- upgradeHead: Buffer,
1277
- callback: (client: T, request: IncomingMessage) => void,
1278
- ): void
1279
- shouldHandle(request: IncomingMessage): boolean | Promise<boolean>
1280
-
1281
- // Events
1282
- on(
1283
- event: 'connection',
1284
- cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
1285
- ): this
1286
- on(event: 'error', cb: (this: Server<T>, error: Error) => void): this
1287
- on(
1288
- event: 'headers',
1289
- cb: (
1290
- this: Server<T>,
1291
- headers: string[],
1292
- request: IncomingMessage,
1293
- ) => void,
1294
- ): this
1295
- on(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
1296
- on(
1297
- event: string | symbol,
1298
- listener: (this: Server<T>, ...args: any[]) => void,
1299
- ): this
1300
-
1301
- once(
1302
- event: 'connection',
1303
- cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
1304
- ): this
1305
- once(event: 'error', cb: (this: Server<T>, error: Error) => void): this
1306
- once(
1307
- event: 'headers',
1308
- cb: (
1309
- this: Server<T>,
1310
- headers: string[],
1311
- request: IncomingMessage,
1312
- ) => void,
1313
- ): this
1314
- once(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
1315
- once(
1316
- event: string | symbol,
1317
- listener: (this: Server<T>, ...args: any[]) => void,
1318
- ): this
1319
-
1320
- off(
1321
- event: 'connection',
1322
- cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
1323
- ): this
1324
- off(event: 'error', cb: (this: Server<T>, error: Error) => void): this
1325
- off(
1326
- event: 'headers',
1327
- cb: (
1328
- this: Server<T>,
1329
- headers: string[],
1330
- request: IncomingMessage,
1331
- ) => void,
1332
- ): this
1333
- off(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
1334
- off(
1335
- event: string | symbol,
1336
- listener: (this: Server<T>, ...args: any[]) => void,
1337
- ): this
1338
-
1339
- addListener(
1340
- event: 'connection',
1341
- cb: (client: T, request: IncomingMessage) => void,
1342
- ): this
1343
- addListener(event: 'error', cb: (err: Error) => void): this
1344
- addListener(
1345
- event: 'headers',
1346
- cb: (headers: string[], request: IncomingMessage) => void,
1347
- ): this
1348
- addListener(event: 'close' | 'listening', cb: () => void): this
1349
- addListener(
1350
- event: string | symbol,
1351
- listener: (...args: any[]) => void,
1352
- ): this
1353
-
1354
- removeListener(event: 'connection', cb: (client: T) => void): this
1355
- removeListener(event: 'error', cb: (err: Error) => void): this
1356
- removeListener(
1357
- event: 'headers',
1358
- cb: (headers: string[], request: IncomingMessage) => void,
1359
- ): this
1360
- removeListener(event: 'close' | 'listening', cb: () => void): this
1361
- removeListener(
1362
- event: string | symbol,
1363
- listener: (...args: any[]) => void,
1364
- ): this
1365
- }
1366
-
1367
- const WebSocketServer: typeof Server
1368
- interface WebSocketServer extends Server {} // tslint:disable-line no-empty-interface
1369
- const WebSocket: typeof WebSocketAlias
1370
- interface WebSocket extends WebSocketAlias {} // tslint:disable-line no-empty-interface
1371
-
1372
- // WebSocket stream
1373
- function createWebSocketStream(
1374
- websocket: WebSocket,
1375
- options?: DuplexOptions,
1376
- ): Duplex
1377
- }
1378
-
1379
- declare class Environment {
1380
- #private;
1381
- name: string;
1382
- config: ResolvedConfig;
1383
- options: ResolvedEnvironmentOptions;
1384
- get plugins(): EnvironmentPlugin[];
1385
- get logger(): Logger;
1386
- constructor(name: string, config: ResolvedConfig, options?: ResolvedEnvironmentOptions);
1387
- }
1388
-
1389
- interface FetchModuleOptions {
1390
- inlineSourceMap?: boolean;
1391
- processSourceMap?<T extends NonNullable<TransformResult['map']>>(map: T): T;
1392
- }
1393
- /**
1394
- * Fetch module information for Vite runner.
1395
- * @experimental
1396
- */
1397
- declare function fetchModule(environment: DevEnvironment, url: string, importer?: string, options?: FetchModuleOptions): Promise<FetchResult>;
1398
-
1399
- declare class ScanEnvironment extends Environment {
1400
- mode: "scan";
1401
- get pluginContainer(): EnvironmentPluginContainer;
1402
- init(): Promise<void>;
1403
- }
1404
-
1405
- type ExportsData = {
1406
- hasModuleSyntax: boolean;
1407
- exports: readonly string[];
1408
- jsxLoader?: boolean;
1409
- };
1410
- interface DepsOptimizer {
1411
- init: () => Promise<void>;
1412
- metadata: DepOptimizationMetadata;
1413
- scanProcessing?: Promise<void>;
1414
- registerMissingImport: (id: string, resolved: string) => OptimizedDepInfo;
1415
- run: () => void;
1416
- isOptimizedDepFile: (id: string) => boolean;
1417
- isOptimizedDepUrl: (url: string) => boolean;
1418
- getOptimizedDepId: (depInfo: OptimizedDepInfo) => string;
1419
- close: () => Promise<void>;
1420
- options: DepOptimizationOptions;
1421
- }
1422
- interface DepOptimizationConfig {
1423
- /**
1424
- * Force optimize listed dependencies (must be resolvable import paths,
1425
- * cannot be globs).
1426
- */
1427
- include?: string[];
1428
- /**
1429
- * Do not optimize these dependencies (must be resolvable import paths,
1430
- * cannot be globs).
1431
- */
1432
- exclude?: string[];
1433
- /**
1434
- * Forces ESM interop when importing these dependencies. Some legacy
1435
- * packages advertise themselves as ESM but use `require` internally
1436
- * @experimental
1437
- */
1438
- needsInterop?: string[];
1439
- /**
1440
- * Options to pass to esbuild during the dep scanning and optimization
1441
- *
1442
- * Certain options are omitted since changing them would not be compatible
1443
- * with Vite's dep optimization.
1444
- *
1445
- * - `external` is also omitted, use Vite's `optimizeDeps.exclude` option
1446
- * - `plugins` are merged with Vite's dep plugin
1447
- *
1448
- * https://esbuild.github.io/api
1449
- */
1450
- esbuildOptions?: Omit<esbuild_BuildOptions, 'bundle' | 'entryPoints' | 'external' | 'write' | 'watch' | 'outdir' | 'outfile' | 'outbase' | 'outExtension' | 'metafile'>;
1451
- /**
1452
- * List of file extensions that can be optimized. A corresponding esbuild
1453
- * plugin must exist to handle the specific extension.
1454
- *
1455
- * By default, Vite can optimize `.mjs`, `.js`, `.ts`, and `.mts` files. This option
1456
- * allows specifying additional extensions.
1457
- *
1458
- * @experimental
1459
- */
1460
- extensions?: string[];
1461
- /**
1462
- * Deps optimization during build was removed in Vite 5.1. This option is
1463
- * now redundant and will be removed in a future version. Switch to using
1464
- * `optimizeDeps.noDiscovery` and an empty or undefined `optimizeDeps.include`.
1465
- * true or 'dev' disables the optimizer, false or 'build' leaves it enabled.
1466
- * @default 'build'
1467
- * @deprecated
1468
- * @experimental
1469
- */
1470
- disabled?: boolean | 'build' | 'dev';
1471
- /**
1472
- * Automatic dependency discovery. When `noDiscovery` is true, only dependencies
1473
- * listed in `include` will be optimized. The scanner isn't run for cold start
1474
- * in this case. CJS-only dependencies must be present in `include` during dev.
1475
- * @default false
1476
- * @experimental
1477
- */
1478
- noDiscovery?: boolean;
1479
- /**
1480
- * When enabled, it will hold the first optimized deps results until all static
1481
- * imports are crawled on cold start. This avoids the need for full-page reloads
1482
- * when new dependencies are discovered and they trigger the generation of new
1483
- * common chunks. If all dependencies are found by the scanner plus the explicitely
1484
- * defined ones in `include`, it is better to disable this option to let the
1485
- * browser process more requests in parallel.
1486
- * @default true
1487
- * @experimental
1488
- */
1489
- holdUntilCrawlEnd?: boolean;
1490
- }
1491
- type DepOptimizationOptions = DepOptimizationConfig & {
1492
- /**
1493
- * By default, Vite will crawl your `index.html` to detect dependencies that
1494
- * need to be pre-bundled. If `build.rollupOptions.input` is specified, Vite
1495
- * will crawl those entry points instead.
1496
- *
1497
- * If neither of these fit your needs, you can specify custom entries using
1498
- * this option - the value should be a fast-glob pattern or array of patterns
1499
- * (https://github.com/mrmlnc/fast-glob#basic-syntax) that are relative from
1500
- * vite project root. This will overwrite default entries inference.
1501
- */
1502
- entries?: string | string[];
1503
- /**
1504
- * Force dep pre-optimization regardless of whether deps have changed.
1505
- * @experimental
1506
- */
1507
- force?: boolean;
1508
- };
1509
- interface OptimizedDepInfo {
1510
- id: string;
1511
- file: string;
1512
- src?: string;
1513
- needsInterop?: boolean;
1514
- browserHash?: string;
1515
- fileHash?: string;
1516
- /**
1517
- * During optimization, ids can still be resolved to their final location
1518
- * but the bundles may not yet be saved to disk
1519
- */
1520
- processing?: Promise<void>;
1521
- /**
1522
- * ExportData cache, discovered deps will parse the src entry to get exports
1523
- * data used both to define if interop is needed and when pre-bundling
1524
- */
1525
- exportsData?: Promise<ExportsData>;
1526
- }
1527
- interface DepOptimizationMetadata {
1528
- /**
1529
- * The main hash is determined by user config and dependency lockfiles.
1530
- * This is checked on server startup to avoid unnecessary re-bundles.
1531
- */
1532
- hash: string;
1533
- /**
1534
- * This hash is determined by dependency lockfiles.
1535
- * This is checked on server startup to avoid unnecessary re-bundles.
1536
- */
1537
- lockfileHash: string;
1538
- /**
1539
- * This hash is determined by user config.
1540
- * This is checked on server startup to avoid unnecessary re-bundles.
1541
- */
1542
- configHash: string;
1543
- /**
1544
- * The browser hash is determined by the main hash plus additional dependencies
1545
- * discovered at runtime. This is used to invalidate browser requests to
1546
- * optimized deps.
1547
- */
1548
- browserHash: string;
1549
- /**
1550
- * Metadata for each already optimized dependency
1551
- */
1552
- optimized: Record<string, OptimizedDepInfo>;
1553
- /**
1554
- * Metadata for non-entry optimized chunks and dynamic imports
1555
- */
1556
- chunks: Record<string, OptimizedDepInfo>;
1557
- /**
1558
- * Metadata for each newly discovered dependency after processing
1559
- */
1560
- discovered: Record<string, OptimizedDepInfo>;
1561
- /**
1562
- * OptimizedDepInfo list
1563
- */
1564
- depInfoList: OptimizedDepInfo[];
1565
- }
1566
-
1567
- declare class RemoteEnvironmentTransport {
1568
- private readonly options;
1569
- constructor(options: {
1570
- send: (data: any) => void;
1571
- onMessage: (handler: (data: any) => void) => void;
1572
- });
1573
- register(environment: DevEnvironment): void;
1574
- }
1575
-
1576
- interface DevEnvironmentSetup {
1577
- hot?: false | HMRChannel;
1578
- watcher?: FSWatcher;
1579
- options?: EnvironmentOptions;
1580
- runner?: FetchModuleOptions & {
1581
- transport?: RemoteEnvironmentTransport;
1582
- };
1583
- depsOptimizer?: DepsOptimizer;
1584
- }
1585
- declare class DevEnvironment extends Environment {
1586
- mode: "dev";
1587
- moduleGraph: EnvironmentModuleGraph;
1588
- watcher?: FSWatcher;
1589
- depsOptimizer?: DepsOptimizer;
1590
- get pluginContainer(): EnvironmentPluginContainer;
1591
- /**
1592
- * HMR channel for this environment. If not provided or disabled,
1593
- * it will be a noop channel that does nothing.
1594
- *
1595
- * @example
1596
- * environment.hot.send({ type: 'full-reload' })
1597
- */
1598
- hot: HMRChannel;
1599
- constructor(name: string, config: ResolvedConfig, setup?: DevEnvironmentSetup);
1600
- init(): Promise<void>;
1601
- fetchModule(id: string, importer?: string): Promise<FetchResult>;
1602
- transformRequest(url: string): Promise<TransformResult | null>;
1603
- warmupRequest(url: string): Promise<void>;
1604
- close(): Promise<void>;
1605
- /**
1606
- * Calling `await environment.waitForRequestsIdle(id)` will wait until all static imports
1607
- * are processed after the first transformRequest call. If called from a load or transform
1608
- * plugin hook, the id needs to be passed as a parameter to avoid deadlocks.
1609
- * Calling this function after the first static imports section of the module graph has been
1610
- * processed will resolve immediately.
1611
- * @experimental
1612
- */
1613
- waitForRequestsIdle(ignoredId?: string): Promise<void>;
1614
- }
821
+ type ExportsData = {
822
+ hasModuleSyntax: boolean;
823
+ exports: readonly string[];
824
+ jsxLoader?: boolean;
825
+ };
826
+ interface DepsOptimizer {
827
+ init: () => Promise<void>;
828
+ metadata: DepOptimizationMetadata;
829
+ scanProcessing?: Promise<void>;
830
+ registerMissingImport: (id: string, resolved: string) => OptimizedDepInfo;
831
+ run: () => void;
832
+ isOptimizedDepFile: (id: string) => boolean;
833
+ isOptimizedDepUrl: (url: string) => boolean;
834
+ getOptimizedDepId: (depInfo: OptimizedDepInfo) => string;
835
+ close: () => Promise<void>;
836
+ options: DepOptimizationOptions;
837
+ }
838
+ interface DepOptimizationConfig {
839
+ /**
840
+ * Force optimize listed dependencies (must be resolvable import paths,
841
+ * cannot be globs).
842
+ */
843
+ include?: string[];
844
+ /**
845
+ * Do not optimize these dependencies (must be resolvable import paths,
846
+ * cannot be globs).
847
+ */
848
+ exclude?: string[];
849
+ /**
850
+ * Forces ESM interop when importing these dependencies. Some legacy
851
+ * packages advertise themselves as ESM but use `require` internally
852
+ * @experimental
853
+ */
854
+ needsInterop?: string[];
855
+ /**
856
+ * Options to pass to esbuild during the dep scanning and optimization
857
+ *
858
+ * Certain options are omitted since changing them would not be compatible
859
+ * with Vite's dep optimization.
860
+ *
861
+ * - `external` is also omitted, use Vite's `optimizeDeps.exclude` option
862
+ * - `plugins` are merged with Vite's dep plugin
863
+ *
864
+ * https://esbuild.github.io/api
865
+ */
866
+ esbuildOptions?: Omit<esbuild_BuildOptions, 'bundle' | 'entryPoints' | 'external' | 'write' | 'watch' | 'outdir' | 'outfile' | 'outbase' | 'outExtension' | 'metafile'>;
867
+ /**
868
+ * List of file extensions that can be optimized. A corresponding esbuild
869
+ * plugin must exist to handle the specific extension.
870
+ *
871
+ * By default, Vite can optimize `.mjs`, `.js`, `.ts`, and `.mts` files. This option
872
+ * allows specifying additional extensions.
873
+ *
874
+ * @experimental
875
+ */
876
+ extensions?: string[];
877
+ /**
878
+ * Deps optimization during build was removed in Vite 5.1. This option is
879
+ * now redundant and will be removed in a future version. Switch to using
880
+ * `optimizeDeps.noDiscovery` and an empty or undefined `optimizeDeps.include`.
881
+ * true or 'dev' disables the optimizer, false or 'build' leaves it enabled.
882
+ * @default 'build'
883
+ * @deprecated
884
+ * @experimental
885
+ */
886
+ disabled?: boolean | 'build' | 'dev';
887
+ /**
888
+ * Automatic dependency discovery. When `noDiscovery` is true, only dependencies
889
+ * listed in `include` will be optimized. The scanner isn't run for cold start
890
+ * in this case. CJS-only dependencies must be present in `include` during dev.
891
+ * @default false
892
+ * @experimental
893
+ */
894
+ noDiscovery?: boolean;
895
+ /**
896
+ * When enabled, it will hold the first optimized deps results until all static
897
+ * imports are crawled on cold start. This avoids the need for full-page reloads
898
+ * when new dependencies are discovered and they trigger the generation of new
899
+ * common chunks. If all dependencies are found by the scanner plus the explicitely
900
+ * defined ones in `include`, it is better to disable this option to let the
901
+ * browser process more requests in parallel.
902
+ * @default true
903
+ * @experimental
904
+ */
905
+ holdUntilCrawlEnd?: boolean;
906
+ }
907
+ type DepOptimizationOptions = DepOptimizationConfig & {
908
+ /**
909
+ * By default, Vite will crawl your `index.html` to detect dependencies that
910
+ * need to be pre-bundled. If `build.rollupOptions.input` is specified, Vite
911
+ * will crawl those entry points instead.
912
+ *
913
+ * If neither of these fit your needs, you can specify custom entries using
914
+ * this option - the value should be a fast-glob pattern or array of patterns
915
+ * (https://github.com/mrmlnc/fast-glob#basic-syntax) that are relative from
916
+ * vite project root. This will overwrite default entries inference.
917
+ */
918
+ entries?: string | string[];
919
+ /**
920
+ * Force dep pre-optimization regardless of whether deps have changed.
921
+ * @experimental
922
+ */
923
+ force?: boolean;
924
+ };
925
+ interface OptimizedDepInfo {
926
+ id: string;
927
+ file: string;
928
+ src?: string;
929
+ needsInterop?: boolean;
930
+ browserHash?: string;
931
+ fileHash?: string;
932
+ /**
933
+ * During optimization, ids can still be resolved to their final location
934
+ * but the bundles may not yet be saved to disk
935
+ */
936
+ processing?: Promise<void>;
937
+ /**
938
+ * ExportData cache, discovered deps will parse the src entry to get exports
939
+ * data used both to define if interop is needed and when pre-bundling
940
+ */
941
+ exportsData?: Promise<ExportsData>;
942
+ }
943
+ interface DepOptimizationMetadata {
944
+ /**
945
+ * The main hash is determined by user config and dependency lockfiles.
946
+ * This is checked on server startup to avoid unnecessary re-bundles.
947
+ */
948
+ hash: string;
949
+ /**
950
+ * This hash is determined by dependency lockfiles.
951
+ * This is checked on server startup to avoid unnecessary re-bundles.
952
+ */
953
+ lockfileHash: string;
954
+ /**
955
+ * This hash is determined by user config.
956
+ * This is checked on server startup to avoid unnecessary re-bundles.
957
+ */
958
+ configHash: string;
959
+ /**
960
+ * The browser hash is determined by the main hash plus additional dependencies
961
+ * discovered at runtime. This is used to invalidate browser requests to
962
+ * optimized deps.
963
+ */
964
+ browserHash: string;
965
+ /**
966
+ * Metadata for each already optimized dependency
967
+ */
968
+ optimized: Record<string, OptimizedDepInfo>;
969
+ /**
970
+ * Metadata for non-entry optimized chunks and dynamic imports
971
+ */
972
+ chunks: Record<string, OptimizedDepInfo>;
973
+ /**
974
+ * Metadata for each newly discovered dependency after processing
975
+ */
976
+ discovered: Record<string, OptimizedDepInfo>;
977
+ /**
978
+ * OptimizedDepInfo list
979
+ */
980
+ depInfoList: OptimizedDepInfo[];
981
+ }
982
+ /**
983
+ * Scan and optimize dependencies within a project.
984
+ * Used by Vite CLI when running `vite optimize`.
985
+ */
986
+ declare function optimizeDeps(config: ResolvedConfig, force?: boolean | undefined, asCommand?: boolean): Promise<DepOptimizationMetadata>;
1615
987
 
1616
988
  interface TransformResult {
1617
989
  code: string;
@@ -1685,1269 +1057,1913 @@ declare class EnvironmentModuleGraph {
1685
1057
  ): void;
1686
1058
  invalidateAll(): void;
1687
1059
  /**
1688
- * Update the module graph based on a module's updated imports information
1689
- * If there are dependencies that no longer have any importers, they are
1690
- * returned as a Set.
1060
+ * Update the module graph based on a module's updated imports information
1061
+ * If there are dependencies that no longer have any importers, they are
1062
+ * returned as a Set.
1063
+ *
1064
+ * @param staticImportedUrls Subset of `importedModules` where they're statically imported in code.
1065
+ * This is only used for soft invalidations so `undefined` is fine but may cause more runtime processing.
1066
+ */
1067
+ updateModuleInfo(mod: EnvironmentModuleNode, importedModules: Set<string | EnvironmentModuleNode>, importedBindings: Map<string, Set<string>> | null, acceptedModules: Set<string | EnvironmentModuleNode>, acceptedExports: Set<string> | null, isSelfAccepting: boolean,
1068
+ ): Promise<Set<EnvironmentModuleNode> | undefined>;
1069
+ ensureEntryFromUrl(rawUrl: string, setIsSelfAccepting?: boolean): Promise<EnvironmentModuleNode>;
1070
+ createFileOnlyEntry(file: string): EnvironmentModuleNode;
1071
+ resolveUrl(url: string): Promise<ResolvedUrl>;
1072
+ updateModuleTransformResult(mod: EnvironmentModuleNode, result: TransformResult | null): void;
1073
+ getModuleByEtag(etag: string): EnvironmentModuleNode | undefined;
1074
+ }
1075
+
1076
+ /**
1077
+ * Backward compatible ModuleNode and ModuleGraph with mixed nodes from both the client and ssr enviornments
1078
+ * It would be good to take the types names for the new EnvironmentModuleNode and EnvironmentModuleGraph but we can't
1079
+ * do that at this point without breaking to much code in the ecosystem.
1080
+ * We are going to deprecate these types and we can try to use them back in the future.
1081
+ */
1082
+ declare class ModuleNode {
1083
+ _moduleGraph: ModuleGraph;
1084
+ _clientModule: EnvironmentModuleNode | undefined;
1085
+ _ssrModule: EnvironmentModuleNode | undefined;
1086
+ constructor(moduleGraph: ModuleGraph, clientModule?: EnvironmentModuleNode, ssrModule?: EnvironmentModuleNode);
1087
+ _get<T extends keyof EnvironmentModuleNode>(prop: T): EnvironmentModuleNode[T];
1088
+ _wrapModuleSet(prop: ModuleSetNames, module: EnvironmentModuleNode | undefined): Set<ModuleNode>;
1089
+ _getModuleSetUnion(prop: 'importedModules' | 'importers'): Set<ModuleNode>;
1090
+ get url(): string;
1091
+ get id(): string | null;
1092
+ get file(): string | null;
1093
+ get type(): 'js' | 'css';
1094
+ get info(): ModuleInfo | undefined;
1095
+ get meta(): Record<string, any> | undefined;
1096
+ get importers(): Set<ModuleNode>;
1097
+ get clientImportedModules(): Set<ModuleNode>;
1098
+ get ssrImportedModules(): Set<ModuleNode>;
1099
+ get importedModules(): Set<ModuleNode>;
1100
+ get acceptedHmrDeps(): Set<ModuleNode>;
1101
+ get acceptedHmrExports(): Set<string> | null;
1102
+ get importedBindings(): Map<string, Set<string>> | null;
1103
+ get isSelfAccepting(): boolean | undefined;
1104
+ get transformResult(): TransformResult | null;
1105
+ set transformResult(value: TransformResult | null);
1106
+ get ssrTransformResult(): TransformResult | null;
1107
+ set ssrTransformResult(value: TransformResult | null);
1108
+ get ssrModule(): Record<string, any> | null;
1109
+ get ssrError(): Error | null;
1110
+ get lastHMRTimestamp(): number;
1111
+ set lastHMRTimestamp(value: number);
1112
+ get lastInvalidationTimestamp(): number;
1113
+ get invalidationState(): TransformResult | 'HARD_INVALIDATED' | undefined;
1114
+ get ssrInvalidationState(): TransformResult | 'HARD_INVALIDATED' | undefined;
1115
+ }
1116
+ declare class ModuleGraph {
1117
+ urlToModuleMap: Map<string, ModuleNode>;
1118
+ idToModuleMap: Map<string, ModuleNode>;
1119
+ etagToModuleMap: Map<string, ModuleNode>;
1120
+ fileToModulesMap: Map<string, Set<ModuleNode>>;
1121
+ constructor(moduleGraphs: {
1122
+ client: () => EnvironmentModuleGraph;
1123
+ ssr: () => EnvironmentModuleGraph;
1124
+ });
1125
+ /** @deprecated */
1126
+ getModuleById(id: string): ModuleNode | undefined;
1127
+ /** @deprecated */
1128
+ getModuleByUrl(url: string, ssr?: boolean): Promise<ModuleNode | undefined>;
1129
+ /** @deprecated */
1130
+ getModulesByFile(file: string): Set<ModuleNode> | undefined;
1131
+ /** @deprecated */
1132
+ onFileChange(file: string): void;
1133
+ /** @deprecated */
1134
+ onFileDelete(file: string): void;
1135
+ /** @deprecated */
1136
+ invalidateModule(mod: ModuleNode, seen?: Set<ModuleNode>, timestamp?: number, isHmr?: boolean,
1137
+ ): void;
1138
+ /** @deprecated */
1139
+ invalidateAll(): void;
1140
+ /** @deprecated */
1141
+ ensureEntryFromUrl(rawUrl: string, ssr?: boolean, setIsSelfAccepting?: boolean): Promise<ModuleNode>;
1142
+ /** @deprecated */
1143
+ createFileOnlyEntry(file: string): ModuleNode;
1144
+ /** @deprecated */
1145
+ resolveUrl(url: string, ssr?: boolean): Promise<ResolvedUrl>;
1146
+ /** @deprecated */
1147
+ updateModuleTransformResult(mod: ModuleNode, result: TransformResult | null, ssr?: boolean): void;
1148
+ /** @deprecated */
1149
+ getModuleByEtag(etag: string): ModuleNode | undefined;
1150
+ getBackwardCompatibleBrowserModuleNode(clientModule: EnvironmentModuleNode): ModuleNode;
1151
+ getBackwardCompatibleServerModuleNode(ssrModule: EnvironmentModuleNode): ModuleNode;
1152
+ getBackwardCompatibleModuleNode(mod: EnvironmentModuleNode): ModuleNode;
1153
+ getBackwardCompatibleModuleNodeDual(clientModule?: EnvironmentModuleNode, ssrModule?: EnvironmentModuleNode): ModuleNode;
1154
+ }
1155
+ type ModuleSetNames = 'acceptedHmrDeps' | 'importedModules';
1156
+
1157
+ interface HmrOptions {
1158
+ protocol?: string;
1159
+ host?: string;
1160
+ port?: number;
1161
+ clientPort?: number;
1162
+ path?: string;
1163
+ timeout?: number;
1164
+ overlay?: boolean;
1165
+ server?: Server;
1166
+ }
1167
+ interface HotUpdateContext {
1168
+ type: 'create' | 'update' | 'delete';
1169
+ file: string;
1170
+ timestamp: number;
1171
+ modules: Array<EnvironmentModuleNode>;
1172
+ read: () => string | Promise<string>;
1173
+ server: ViteDevServer;
1174
+ environment: DevEnvironment;
1175
+ }
1176
+ /**
1177
+ * @deprecated
1178
+ * Used by handleHotUpdate for backward compatibility with mixed client and ssr moduleGraph
1179
+ **/
1180
+ interface HmrContext {
1181
+ file: string;
1182
+ timestamp: number;
1183
+ modules: Array<ModuleNode>;
1184
+ read: () => string | Promise<string>;
1185
+ server: ViteDevServer;
1186
+ }
1187
+ interface HMRBroadcasterClient {
1188
+ /**
1189
+ * Send event to the client
1190
+ */
1191
+ send(payload: HMRPayload): void;
1192
+ /**
1193
+ * Send custom event
1194
+ */
1195
+ send(event: string, payload?: CustomPayload['data']): void;
1196
+ }
1197
+ interface HMRChannel {
1198
+ /**
1199
+ * Unique channel name
1200
+ */
1201
+ name: string;
1202
+ /**
1203
+ * Broadcast events to all clients
1204
+ */
1205
+ send(payload: HMRPayload): void;
1206
+ /**
1207
+ * Send custom event
1208
+ */
1209
+ send<T extends string>(event: T, payload?: InferCustomEventPayload<T>): void;
1210
+ /**
1211
+ * Handle custom event emitted by `import.meta.hot.send`
1212
+ */
1213
+ on<T extends string>(event: T, listener: (data: InferCustomEventPayload<T>, client: HMRBroadcasterClient, ...args: any[]) => void): void;
1214
+ on(event: 'connection', listener: () => void): void;
1215
+ /**
1216
+ * Unregister event listener
1217
+ */
1218
+ off(event: string, listener: Function): void;
1219
+ /**
1220
+ * Start listening for messages
1221
+ */
1222
+ listen(): void;
1223
+ /**
1224
+ * Disconnect all clients, called when server is closed or restarted.
1225
+ */
1226
+ close(): void;
1227
+ }
1228
+ interface HMRBroadcaster extends Omit<HMRChannel, 'close' | 'name'> {
1229
+ /**
1230
+ * All registered channels. Always has websocket channel.
1231
+ */
1232
+ readonly channels: HMRChannel[];
1233
+ /**
1234
+ * Add a new third-party channel.
1235
+ */
1236
+ addChannel(connection: HMRChannel): HMRBroadcaster;
1237
+ close(): Promise<unknown[]>;
1238
+ }
1239
+ interface ServerHMRChannel extends HMRChannel {
1240
+ api: {
1241
+ innerEmitter: EventEmitter;
1242
+ outsideEmitter: EventEmitter;
1243
+ };
1244
+ }
1245
+
1246
+ declare class RemoteEnvironmentTransport {
1247
+ private readonly options;
1248
+ constructor(options: {
1249
+ send: (data: any) => void;
1250
+ onMessage: (handler: (data: any) => void) => void;
1251
+ });
1252
+ register(environment: DevEnvironment): void;
1253
+ }
1254
+
1255
+ interface DevEnvironmentSetup {
1256
+ hot?: false | HMRChannel;
1257
+ watcher?: FSWatcher;
1258
+ options?: EnvironmentOptions;
1259
+ runner?: FetchModuleOptions & {
1260
+ transport?: RemoteEnvironmentTransport;
1261
+ };
1262
+ depsOptimizer?: DepsOptimizer;
1263
+ }
1264
+ declare class DevEnvironment extends BaseEnvironment {
1265
+ mode: "dev";
1266
+ moduleGraph: EnvironmentModuleGraph;
1267
+ watcher?: FSWatcher;
1268
+ depsOptimizer?: DepsOptimizer;
1269
+ get pluginContainer(): EnvironmentPluginContainer;
1270
+ /**
1271
+ * HMR channel for this environment. If not provided or disabled,
1272
+ * it will be a noop channel that does nothing.
1691
1273
  *
1692
- * @param staticImportedUrls Subset of `importedModules` where they're statically imported in code.
1693
- * This is only used for soft invalidations so `undefined` is fine but may cause more runtime processing.
1274
+ * @example
1275
+ * environment.hot.send({ type: 'full-reload' })
1694
1276
  */
1695
- updateModuleInfo(mod: EnvironmentModuleNode, importedModules: Set<string | EnvironmentModuleNode>, importedBindings: Map<string, Set<string>> | null, acceptedModules: Set<string | EnvironmentModuleNode>, acceptedExports: Set<string> | null, isSelfAccepting: boolean,
1696
- ): Promise<Set<EnvironmentModuleNode> | undefined>;
1697
- ensureEntryFromUrl(rawUrl: string, setIsSelfAccepting?: boolean): Promise<EnvironmentModuleNode>;
1698
- createFileOnlyEntry(file: string): EnvironmentModuleNode;
1699
- resolveUrl(url: string): Promise<ResolvedUrl>;
1700
- updateModuleTransformResult(mod: EnvironmentModuleNode, result: TransformResult | null): void;
1701
- getModuleByEtag(etag: string): EnvironmentModuleNode | undefined;
1277
+ hot: HMRChannel;
1278
+ constructor(name: string, config: ResolvedConfig, setup?: DevEnvironmentSetup);
1279
+ init(): Promise<void>;
1280
+ fetchModule(id: string, importer?: string): Promise<FetchResult>;
1281
+ transformRequest(url: string): Promise<TransformResult | null>;
1282
+ warmupRequest(url: string): Promise<void>;
1283
+ close(): Promise<void>;
1284
+ /**
1285
+ * Calling `await environment.waitForRequestsIdle(id)` will wait until all static imports
1286
+ * are processed after the first transformRequest call. If called from a load or transform
1287
+ * plugin hook, the id needs to be passed as a parameter to avoid deadlocks.
1288
+ * Calling this function after the first static imports section of the module graph has been
1289
+ * processed will resolve immediately.
1290
+ * @experimental
1291
+ */
1292
+ waitForRequestsIdle(ignoredId?: string): Promise<void>;
1293
+ }
1294
+
1295
+ interface RollupCommonJSOptions {
1296
+ /**
1297
+ * A minimatch pattern, or array of patterns, which specifies the files in
1298
+ * the build the plugin should operate on. By default, all files with
1299
+ * extension `".cjs"` or those in `extensions` are included, but you can
1300
+ * narrow this list by only including specific files. These files will be
1301
+ * analyzed and transpiled if either the analysis does not find ES module
1302
+ * specific statements or `transformMixedEsModules` is `true`.
1303
+ * @default undefined
1304
+ */
1305
+ include?: string | RegExp | readonly (string | RegExp)[]
1306
+ /**
1307
+ * A minimatch pattern, or array of patterns, which specifies the files in
1308
+ * the build the plugin should _ignore_. By default, all files with
1309
+ * extensions other than those in `extensions` or `".cjs"` are ignored, but you
1310
+ * can exclude additional files. See also the `include` option.
1311
+ * @default undefined
1312
+ */
1313
+ exclude?: string | RegExp | readonly (string | RegExp)[]
1314
+ /**
1315
+ * For extensionless imports, search for extensions other than .js in the
1316
+ * order specified. Note that you need to make sure that non-JavaScript files
1317
+ * are transpiled by another plugin first.
1318
+ * @default [ '.js' ]
1319
+ */
1320
+ extensions?: ReadonlyArray<string>
1321
+ /**
1322
+ * If true then uses of `global` won't be dealt with by this plugin
1323
+ * @default false
1324
+ */
1325
+ ignoreGlobal?: boolean
1326
+ /**
1327
+ * If false, skips source map generation for CommonJS modules. This will
1328
+ * improve performance.
1329
+ * @default true
1330
+ */
1331
+ sourceMap?: boolean
1332
+ /**
1333
+ * Some `require` calls cannot be resolved statically to be translated to
1334
+ * imports.
1335
+ * When this option is set to `false`, the generated code will either
1336
+ * directly throw an error when such a call is encountered or, when
1337
+ * `dynamicRequireTargets` is used, when such a call cannot be resolved with a
1338
+ * configured dynamic require target.
1339
+ * Setting this option to `true` will instead leave the `require` call in the
1340
+ * code or use it as a fallback for `dynamicRequireTargets`.
1341
+ * @default false
1342
+ */
1343
+ ignoreDynamicRequires?: boolean
1344
+ /**
1345
+ * Instructs the plugin whether to enable mixed module transformations. This
1346
+ * is useful in scenarios with modules that contain a mix of ES `import`
1347
+ * statements and CommonJS `require` expressions. Set to `true` if `require`
1348
+ * calls should be transformed to imports in mixed modules, or `false` if the
1349
+ * `require` expressions should survive the transformation. The latter can be
1350
+ * important if the code contains environment detection, or you are coding
1351
+ * for an environment with special treatment for `require` calls such as
1352
+ * ElectronJS. See also the `ignore` option.
1353
+ * @default false
1354
+ */
1355
+ transformMixedEsModules?: boolean
1356
+ /**
1357
+ * By default, this plugin will try to hoist `require` statements as imports
1358
+ * to the top of each file. While this works well for many code bases and
1359
+ * allows for very efficient ESM output, it does not perfectly capture
1360
+ * CommonJS semantics as the order of side effects like log statements may
1361
+ * change. But it is especially problematic when there are circular `require`
1362
+ * calls between CommonJS modules as those often rely on the lazy execution of
1363
+ * nested `require` calls.
1364
+ *
1365
+ * Setting this option to `true` will wrap all CommonJS files in functions
1366
+ * which are executed when they are required for the first time, preserving
1367
+ * NodeJS semantics. Note that this can have an impact on the size and
1368
+ * performance of the generated code.
1369
+ *
1370
+ * The default value of `"auto"` will only wrap CommonJS files when they are
1371
+ * part of a CommonJS dependency cycle, e.g. an index file that is required by
1372
+ * many of its dependencies. All other CommonJS files are hoisted. This is the
1373
+ * recommended setting for most code bases.
1374
+ *
1375
+ * `false` will entirely prevent wrapping and hoist all files. This may still
1376
+ * work depending on the nature of cyclic dependencies but will often cause
1377
+ * problems.
1378
+ *
1379
+ * You can also provide a minimatch pattern, or array of patterns, to only
1380
+ * specify a subset of files which should be wrapped in functions for proper
1381
+ * `require` semantics.
1382
+ *
1383
+ * `"debug"` works like `"auto"` but after bundling, it will display a warning
1384
+ * containing a list of ids that have been wrapped which can be used as
1385
+ * minimatch pattern for fine-tuning.
1386
+ * @default "auto"
1387
+ */
1388
+ strictRequires?: boolean | string | RegExp | readonly (string | RegExp)[]
1389
+ /**
1390
+ * Sometimes you have to leave require statements unconverted. Pass an array
1391
+ * containing the IDs or a `id => boolean` function.
1392
+ * @default []
1393
+ */
1394
+ ignore?: ReadonlyArray<string> | ((id: string) => boolean)
1395
+ /**
1396
+ * In most cases, where `require` calls are inside a `try-catch` clause,
1397
+ * they should be left unconverted as it requires an optional dependency
1398
+ * that may or may not be installed beside the rolled up package.
1399
+ * Due to the conversion of `require` to a static `import` - the call is
1400
+ * hoisted to the top of the file, outside the `try-catch` clause.
1401
+ *
1402
+ * - `true`: Default. All `require` calls inside a `try` will be left unconverted.
1403
+ * - `false`: All `require` calls inside a `try` will be converted as if the
1404
+ * `try-catch` clause is not there.
1405
+ * - `remove`: Remove all `require` calls from inside any `try` block.
1406
+ * - `string[]`: Pass an array containing the IDs to left unconverted.
1407
+ * - `((id: string) => boolean|'remove')`: Pass a function that controls
1408
+ * individual IDs.
1409
+ *
1410
+ * @default true
1411
+ */
1412
+ ignoreTryCatch?:
1413
+ | boolean
1414
+ | 'remove'
1415
+ | ReadonlyArray<string>
1416
+ | ((id: string) => boolean | 'remove')
1417
+ /**
1418
+ * Controls how to render imports from external dependencies. By default,
1419
+ * this plugin assumes that all external dependencies are CommonJS. This
1420
+ * means they are rendered as default imports to be compatible with e.g.
1421
+ * NodeJS where ES modules can only import a default export from a CommonJS
1422
+ * dependency.
1423
+ *
1424
+ * If you set `esmExternals` to `true`, this plugin assumes that all
1425
+ * external dependencies are ES modules and respect the
1426
+ * `requireReturnsDefault` option. If that option is not set, they will be
1427
+ * rendered as namespace imports.
1428
+ *
1429
+ * You can also supply an array of ids to be treated as ES modules, or a
1430
+ * function that will be passed each external id to determine whether it is
1431
+ * an ES module.
1432
+ * @default false
1433
+ */
1434
+ esmExternals?: boolean | ReadonlyArray<string> | ((id: string) => boolean)
1435
+ /**
1436
+ * Controls what is returned when requiring an ES module from a CommonJS file.
1437
+ * When using the `esmExternals` option, this will also apply to external
1438
+ * modules. By default, this plugin will render those imports as namespace
1439
+ * imports i.e.
1440
+ *
1441
+ * ```js
1442
+ * // input
1443
+ * const foo = require('foo');
1444
+ *
1445
+ * // output
1446
+ * import * as foo from 'foo';
1447
+ * ```
1448
+ *
1449
+ * However, there are some situations where this may not be desired.
1450
+ * For these situations, you can change Rollup's behaviour either globally or
1451
+ * per module. To change it globally, set the `requireReturnsDefault` option
1452
+ * to one of the following values:
1453
+ *
1454
+ * - `false`: This is the default, requiring an ES module returns its
1455
+ * namespace. This is the only option that will also add a marker
1456
+ * `__esModule: true` to the namespace to support interop patterns in
1457
+ * CommonJS modules that are transpiled ES modules.
1458
+ * - `"namespace"`: Like `false`, requiring an ES module returns its
1459
+ * namespace, but the plugin does not add the `__esModule` marker and thus
1460
+ * creates more efficient code. For external dependencies when using
1461
+ * `esmExternals: true`, no additional interop code is generated.
1462
+ * - `"auto"`: This is complementary to how `output.exports: "auto"` works in
1463
+ * Rollup: If a module has a default export and no named exports, requiring
1464
+ * that module returns the default export. In all other cases, the namespace
1465
+ * is returned. For external dependencies when using `esmExternals: true`, a
1466
+ * corresponding interop helper is added.
1467
+ * - `"preferred"`: If a module has a default export, requiring that module
1468
+ * always returns the default export, no matter whether additional named
1469
+ * exports exist. This is similar to how previous versions of this plugin
1470
+ * worked. Again for external dependencies when using `esmExternals: true`,
1471
+ * an interop helper is added.
1472
+ * - `true`: This will always try to return the default export on require
1473
+ * without checking if it actually exists. This can throw at build time if
1474
+ * there is no default export. This is how external dependencies are handled
1475
+ * when `esmExternals` is not used. The advantage over the other options is
1476
+ * that, like `false`, this does not add an interop helper for external
1477
+ * dependencies, keeping the code lean.
1478
+ *
1479
+ * To change this for individual modules, you can supply a function for
1480
+ * `requireReturnsDefault` instead. This function will then be called once for
1481
+ * each required ES module or external dependency with the corresponding id
1482
+ * and allows you to return different values for different modules.
1483
+ * @default false
1484
+ */
1485
+ requireReturnsDefault?:
1486
+ | boolean
1487
+ | 'auto'
1488
+ | 'preferred'
1489
+ | 'namespace'
1490
+ | ((id: string) => boolean | 'auto' | 'preferred' | 'namespace')
1491
+
1492
+ /**
1493
+ * @default "auto"
1494
+ */
1495
+ defaultIsModuleExports?: boolean | 'auto' | ((id: string) => boolean | 'auto')
1496
+ /**
1497
+ * Some modules contain dynamic `require` calls, or require modules that
1498
+ * contain circular dependencies, which are not handled well by static
1499
+ * imports. Including those modules as `dynamicRequireTargets` will simulate a
1500
+ * CommonJS (NodeJS-like) environment for them with support for dynamic
1501
+ * dependencies. It also enables `strictRequires` for those modules.
1502
+ *
1503
+ * Note: In extreme cases, this feature may result in some paths being
1504
+ * rendered as absolute in the final bundle. The plugin tries to avoid
1505
+ * exposing paths from the local machine, but if you are `dynamicRequirePaths`
1506
+ * with paths that are far away from your project's folder, that may require
1507
+ * replacing strings like `"/Users/John/Desktop/foo-project/"` -\> `"/"`.
1508
+ */
1509
+ dynamicRequireTargets?: string | ReadonlyArray<string>
1510
+ /**
1511
+ * To avoid long paths when using the `dynamicRequireTargets` option, you can use this option to specify a directory
1512
+ * that is a common parent for all files that use dynamic require statements. Using a directory higher up such as `/`
1513
+ * may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your
1514
+ * home directory name. By default, it uses the current working directory.
1515
+ */
1516
+ dynamicRequireRoot?: string
1702
1517
  }
1703
1518
 
1704
- /**
1705
- * Backward compatible ModuleNode and ModuleGraph with mixed nodes from both the client and ssr enviornments
1706
- * It would be good to take the types names for the new EnvironmentModuleNode and EnvironmentModuleGraph but we can't
1707
- * do that at this point without breaking to much code in the ecosystem.
1708
- * We are going to deprecate these types and we can try to use them back in the future.
1709
- */
1710
- declare class ModuleNode {
1711
- _moduleGraph: ModuleGraph;
1712
- _clientModule: EnvironmentModuleNode | undefined;
1713
- _ssrModule: EnvironmentModuleNode | undefined;
1714
- constructor(moduleGraph: ModuleGraph, clientModule?: EnvironmentModuleNode, ssrModule?: EnvironmentModuleNode);
1715
- _get<T extends keyof EnvironmentModuleNode>(prop: T): EnvironmentModuleNode[T];
1716
- _wrapModuleSet(prop: ModuleSetNames, module: EnvironmentModuleNode | undefined): Set<ModuleNode>;
1717
- _getModuleSetUnion(prop: 'importedModules' | 'importers'): Set<ModuleNode>;
1718
- get url(): string;
1719
- get id(): string | null;
1720
- get file(): string | null;
1721
- get type(): 'js' | 'css';
1722
- get info(): ModuleInfo | undefined;
1723
- get meta(): Record<string, any> | undefined;
1724
- get importers(): Set<ModuleNode>;
1725
- get clientImportedModules(): Set<ModuleNode>;
1726
- get ssrImportedModules(): Set<ModuleNode>;
1727
- get importedModules(): Set<ModuleNode>;
1728
- get acceptedHmrDeps(): Set<ModuleNode>;
1729
- get acceptedHmrExports(): Set<string> | null;
1730
- get importedBindings(): Map<string, Set<string>> | null;
1731
- get isSelfAccepting(): boolean | undefined;
1732
- get transformResult(): TransformResult | null;
1733
- set transformResult(value: TransformResult | null);
1734
- get ssrTransformResult(): TransformResult | null;
1735
- set ssrTransformResult(value: TransformResult | null);
1736
- get ssrModule(): Record<string, any> | null;
1737
- get ssrError(): Error | null;
1738
- get lastHMRTimestamp(): number;
1739
- set lastHMRTimestamp(value: number);
1740
- get lastInvalidationTimestamp(): number;
1741
- get invalidationState(): TransformResult | 'HARD_INVALIDATED' | undefined;
1742
- get ssrInvalidationState(): TransformResult | 'HARD_INVALIDATED' | undefined;
1743
- }
1744
- declare class ModuleGraph {
1745
- urlToModuleMap: Map<string, ModuleNode>;
1746
- idToModuleMap: Map<string, ModuleNode>;
1747
- etagToModuleMap: Map<string, ModuleNode>;
1748
- fileToModulesMap: Map<string, Set<ModuleNode>>;
1749
- constructor(moduleGraphs: {
1750
- client: () => EnvironmentModuleGraph;
1751
- ssr: () => EnvironmentModuleGraph;
1752
- });
1753
- /** @deprecated */
1754
- getModuleById(id: string): ModuleNode | undefined;
1755
- /** @deprecated */
1756
- getModuleByUrl(url: string, ssr?: boolean): Promise<ModuleNode | undefined>;
1757
- /** @deprecated */
1758
- getModulesByFile(file: string): Set<ModuleNode> | undefined;
1759
- /** @deprecated */
1760
- onFileChange(file: string): void;
1761
- /** @deprecated */
1762
- onFileDelete(file: string): void;
1763
- /** @deprecated */
1764
- invalidateModule(mod: ModuleNode, seen?: Set<ModuleNode>, timestamp?: number, isHmr?: boolean,
1765
- ): void;
1766
- /** @deprecated */
1767
- invalidateAll(): void;
1768
- /** @deprecated */
1769
- ensureEntryFromUrl(rawUrl: string, ssr?: boolean, setIsSelfAccepting?: boolean): Promise<ModuleNode>;
1770
- /** @deprecated */
1771
- createFileOnlyEntry(file: string): ModuleNode;
1772
- /** @deprecated */
1773
- resolveUrl(url: string, ssr?: boolean): Promise<ResolvedUrl>;
1774
- /** @deprecated */
1775
- updateModuleTransformResult(mod: ModuleNode, result: TransformResult | null, ssr?: boolean): void;
1776
- /** @deprecated */
1777
- getModuleByEtag(etag: string): ModuleNode | undefined;
1778
- getBackwardCompatibleBrowserModuleNode(clientModule: EnvironmentModuleNode): ModuleNode;
1779
- getBackwardCompatibleServerModuleNode(ssrModule: EnvironmentModuleNode): ModuleNode;
1780
- getBackwardCompatibleModuleNode(mod: EnvironmentModuleNode): ModuleNode;
1781
- getBackwardCompatibleModuleNodeDual(clientModule?: EnvironmentModuleNode, ssrModule?: EnvironmentModuleNode): ModuleNode;
1519
+ interface RollupDynamicImportVarsOptions {
1520
+ /**
1521
+ * Files to include in this plugin (default all).
1522
+ * @default []
1523
+ */
1524
+ include?: string | RegExp | (string | RegExp)[]
1525
+ /**
1526
+ * Files to exclude in this plugin (default none).
1527
+ * @default []
1528
+ */
1529
+ exclude?: string | RegExp | (string | RegExp)[]
1530
+ /**
1531
+ * 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.
1532
+ * @default false
1533
+ */
1534
+ warnOnError?: boolean
1782
1535
  }
1783
- type ModuleSetNames = 'acceptedHmrDeps' | 'importedModules';
1784
1536
 
1785
- interface HmrOptions {
1786
- protocol?: string;
1787
- host?: string;
1788
- port?: number;
1789
- clientPort?: number;
1790
- path?: string;
1791
- timeout?: number;
1792
- overlay?: boolean;
1793
- server?: Server;
1794
- }
1795
- interface HotUpdateContext {
1796
- type: 'create' | 'update' | 'delete';
1797
- file: string;
1798
- timestamp: number;
1799
- modules: Array<EnvironmentModuleNode>;
1800
- read: () => string | Promise<string>;
1801
- server: ViteDevServer;
1802
- environment: DevEnvironment;
1803
- }
1804
- /**
1805
- * @deprecated
1806
- * Used by handleHotUpdate for backward compatibility with mixed client and ssr moduleGraph
1807
- **/
1808
- interface HmrContext {
1809
- file: string;
1810
- timestamp: number;
1811
- modules: Array<ModuleNode>;
1812
- read: () => string | Promise<string>;
1813
- server: ViteDevServer;
1814
- }
1815
- interface HMRBroadcasterClient {
1816
- /**
1817
- * Send event to the client
1818
- */
1819
- send(payload: HMRPayload): void;
1820
- /**
1821
- * Send custom event
1822
- */
1823
- send(event: string, payload?: CustomPayload['data']): void;
1824
- }
1825
- interface HMRChannel {
1826
- /**
1827
- * Unique channel name
1828
- */
1829
- name: string;
1830
- /**
1831
- * Broadcast events to all clients
1832
- */
1833
- send(payload: HMRPayload): void;
1834
- /**
1835
- * Send custom event
1836
- */
1837
- send<T extends string>(event: T, payload?: InferCustomEventPayload<T>): void;
1537
+ // Modified and inlined to avoid extra dependency
1538
+ // Source: https://github.com/terser/terser/blob/master/tools/terser.d.ts
1539
+ // BSD Licensed https://github.com/terser/terser/blob/master/LICENSE
1540
+
1541
+ declare namespace Terser {
1542
+ export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020
1543
+
1544
+ export interface ParseOptions {
1545
+ bare_returns?: boolean
1546
+ /** @deprecated legacy option. Currently, all supported EcmaScript is valid to parse. */
1547
+ ecma?: ECMA
1548
+ html5_comments?: boolean
1549
+ shebang?: boolean
1550
+ }
1551
+
1552
+ export interface CompressOptions {
1553
+ arguments?: boolean
1554
+ arrows?: boolean
1555
+ booleans_as_integers?: boolean
1556
+ booleans?: boolean
1557
+ collapse_vars?: boolean
1558
+ comparisons?: boolean
1559
+ computed_props?: boolean
1560
+ conditionals?: boolean
1561
+ dead_code?: boolean
1562
+ defaults?: boolean
1563
+ directives?: boolean
1564
+ drop_console?: boolean
1565
+ drop_debugger?: boolean
1566
+ ecma?: ECMA
1567
+ evaluate?: boolean
1568
+ expression?: boolean
1569
+ global_defs?: object
1570
+ hoist_funs?: boolean
1571
+ hoist_props?: boolean
1572
+ hoist_vars?: boolean
1573
+ ie8?: boolean
1574
+ if_return?: boolean
1575
+ inline?: boolean | InlineFunctions
1576
+ join_vars?: boolean
1577
+ keep_classnames?: boolean | RegExp
1578
+ keep_fargs?: boolean
1579
+ keep_fnames?: boolean | RegExp
1580
+ keep_infinity?: boolean
1581
+ loops?: boolean
1582
+ module?: boolean
1583
+ negate_iife?: boolean
1584
+ passes?: number
1585
+ properties?: boolean
1586
+ pure_funcs?: string[]
1587
+ pure_getters?: boolean | 'strict'
1588
+ reduce_funcs?: boolean
1589
+ reduce_vars?: boolean
1590
+ sequences?: boolean | number
1591
+ side_effects?: boolean
1592
+ switches?: boolean
1593
+ toplevel?: boolean
1594
+ top_retain?: null | string | string[] | RegExp
1595
+ typeofs?: boolean
1596
+ unsafe_arrows?: boolean
1597
+ unsafe?: boolean
1598
+ unsafe_comps?: boolean
1599
+ unsafe_Function?: boolean
1600
+ unsafe_math?: boolean
1601
+ unsafe_symbols?: boolean
1602
+ unsafe_methods?: boolean
1603
+ unsafe_proto?: boolean
1604
+ unsafe_regexp?: boolean
1605
+ unsafe_undefined?: boolean
1606
+ unused?: boolean
1607
+ }
1608
+
1609
+ export enum InlineFunctions {
1610
+ Disabled = 0,
1611
+ SimpleFunctions = 1,
1612
+ WithArguments = 2,
1613
+ WithArgumentsAndVariables = 3,
1614
+ }
1615
+
1616
+ export interface MangleOptions {
1617
+ eval?: boolean
1618
+ keep_classnames?: boolean | RegExp
1619
+ keep_fnames?: boolean | RegExp
1620
+ module?: boolean
1621
+ nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler
1622
+ properties?: boolean | ManglePropertiesOptions
1623
+ reserved?: string[]
1624
+ safari10?: boolean
1625
+ toplevel?: boolean
1626
+ }
1627
+
1628
+ /**
1629
+ * An identifier mangler for which the output is invariant with respect to the source code.
1630
+ */
1631
+ export interface SimpleIdentifierMangler {
1838
1632
  /**
1839
- * Handle custom event emitted by `import.meta.hot.send`
1633
+ * Obtains the nth most favored (usually shortest) identifier to rename a variable to.
1634
+ * The mangler will increment n and retry until the return value is not in use in scope, and is not a reserved word.
1635
+ * This function is expected to be stable; Evaluating get(n) === get(n) should always return true.
1636
+ * @param n - The ordinal of the identifier.
1840
1637
  */
1841
- on<T extends string>(event: T, listener: (data: InferCustomEventPayload<T>, client: HMRBroadcasterClient, ...args: any[]) => void): void;
1842
- on(event: 'connection', listener: () => void): void;
1638
+ get(n: number): string
1639
+ }
1640
+
1641
+ /**
1642
+ * An identifier mangler that leverages character frequency analysis to determine identifier precedence.
1643
+ */
1644
+ export interface WeightedIdentifierMangler extends SimpleIdentifierMangler {
1843
1645
  /**
1844
- * Unregister event listener
1646
+ * Modifies the internal weighting of the input characters by the specified delta.
1647
+ * Will be invoked on the entire printed AST, and then deduct mangleable identifiers.
1648
+ * @param chars - The characters to modify the weighting of.
1649
+ * @param delta - The numeric weight to add to the characters.
1845
1650
  */
1846
- off(event: string, listener: Function): void;
1651
+ consider(chars: string, delta: number): number
1847
1652
  /**
1848
- * Start listening for messages
1653
+ * Resets character weights.
1849
1654
  */
1850
- listen(): void;
1655
+ reset(): void
1851
1656
  /**
1852
- * Disconnect all clients, called when server is closed or restarted.
1657
+ * Sorts identifiers by character frequency, in preparation for calls to get(n).
1853
1658
  */
1854
- close(): void;
1659
+ sort(): void
1660
+ }
1661
+
1662
+ export interface ManglePropertiesOptions {
1663
+ builtins?: boolean
1664
+ debug?: boolean
1665
+ keep_quoted?: boolean | 'strict'
1666
+ nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler
1667
+ regex?: RegExp | string
1668
+ reserved?: string[]
1669
+ }
1670
+
1671
+ export interface FormatOptions {
1672
+ ascii_only?: boolean
1673
+ /** @deprecated Not implemented anymore */
1674
+ beautify?: boolean
1675
+ braces?: boolean
1676
+ comments?:
1677
+ | boolean
1678
+ | 'all'
1679
+ | 'some'
1680
+ | RegExp
1681
+ | ((
1682
+ node: any,
1683
+ comment: {
1684
+ value: string
1685
+ type: 'comment1' | 'comment2' | 'comment3' | 'comment4'
1686
+ pos: number
1687
+ line: number
1688
+ col: number
1689
+ },
1690
+ ) => boolean)
1691
+ ecma?: ECMA
1692
+ ie8?: boolean
1693
+ keep_numbers?: boolean
1694
+ indent_level?: number
1695
+ indent_start?: number
1696
+ inline_script?: boolean
1697
+ keep_quoted_props?: boolean
1698
+ max_line_len?: number | false
1699
+ preamble?: string
1700
+ preserve_annotations?: boolean
1701
+ quote_keys?: boolean
1702
+ quote_style?: OutputQuoteStyle
1703
+ safari10?: boolean
1704
+ semicolons?: boolean
1705
+ shebang?: boolean
1706
+ shorthand?: boolean
1707
+ source_map?: SourceMapOptions
1708
+ webkit?: boolean
1709
+ width?: number
1710
+ wrap_iife?: boolean
1711
+ wrap_func_args?: boolean
1712
+ }
1713
+
1714
+ export enum OutputQuoteStyle {
1715
+ PreferDouble = 0,
1716
+ AlwaysSingle = 1,
1717
+ AlwaysDouble = 2,
1718
+ AlwaysOriginal = 3,
1719
+ }
1720
+
1721
+ export interface MinifyOptions {
1722
+ compress?: boolean | CompressOptions
1723
+ ecma?: ECMA
1724
+ enclose?: boolean | string
1725
+ ie8?: boolean
1726
+ keep_classnames?: boolean | RegExp
1727
+ keep_fnames?: boolean | RegExp
1728
+ mangle?: boolean | MangleOptions
1729
+ module?: boolean
1730
+ nameCache?: object
1731
+ format?: FormatOptions
1732
+ /** @deprecated deprecated */
1733
+ output?: FormatOptions
1734
+ parse?: ParseOptions
1735
+ safari10?: boolean
1736
+ sourceMap?: boolean | SourceMapOptions
1737
+ toplevel?: boolean
1738
+ }
1739
+
1740
+ export interface MinifyOutput {
1741
+ code?: string
1742
+ map?: object | string
1743
+ decoded_map?: object | null
1744
+ }
1745
+
1746
+ export interface SourceMapOptions {
1747
+ /** Source map object, 'inline' or source map file content */
1748
+ content?: object | string
1749
+ includeSources?: boolean
1750
+ filename?: string
1751
+ root?: string
1752
+ url?: string | 'inline'
1753
+ }
1855
1754
  }
1856
- interface HMRBroadcaster extends Omit<HMRChannel, 'close' | 'name'> {
1857
- /**
1858
- * All registered channels. Always has websocket channel.
1859
- */
1860
- readonly channels: HMRChannel[];
1755
+
1756
+ interface TerserOptions extends Terser.MinifyOptions {
1861
1757
  /**
1862
- * Add a new third-party channel.
1758
+ * Vite-specific option to specify the max number of workers to spawn
1759
+ * when minifying files with terser.
1760
+ *
1761
+ * @default number of CPUs minus 1
1863
1762
  */
1864
- addChannel(connection: HMRChannel): HMRBroadcaster;
1865
- close(): Promise<unknown[]>;
1866
- }
1867
- interface ServerHMRChannel extends HMRChannel {
1868
- api: {
1869
- innerEmitter: EventEmitter;
1870
- outsideEmitter: EventEmitter;
1871
- };
1763
+ maxWorkers?: number;
1872
1764
  }
1873
1765
 
1874
- type WebSocketCustomListener<T> = (data: T, client: WebSocketClient) => void;
1875
- interface WebSocketServer extends HMRChannel {
1876
- /**
1877
- * Listen on port and host
1878
- */
1879
- listen(): void;
1880
- /**
1881
- * Get all connected clients.
1882
- */
1883
- clients: Set<WebSocketClient>;
1884
- /**
1885
- * Disconnect all clients and terminate the server.
1886
- */
1887
- close(): Promise<void>;
1888
- /**
1889
- * Handle custom event emitted by `import.meta.hot.send`
1890
- */
1891
- on: WebSocket.Server['on'] & {
1892
- <T extends string>(event: T, listener: WebSocketCustomListener<InferCustomEventPayload<T>>): void;
1893
- };
1894
- /**
1895
- * Unregister event listener.
1896
- */
1897
- off: WebSocket.Server['off'] & {
1898
- (event: string, listener: Function): void;
1766
+ /** Cache for package.json resolution and package.json contents */
1767
+ type PackageCache = Map<string, PackageData>;
1768
+ interface PackageData {
1769
+ dir: string;
1770
+ hasSideEffects: (id: string) => boolean | 'no-treeshake' | null;
1771
+ webResolvedImports: Record<string, string | undefined>;
1772
+ nodeResolvedImports: Record<string, string | undefined>;
1773
+ setResolvedCache: (key: string, entry: string, targetWeb: boolean) => void;
1774
+ getResolvedCache: (key: string, targetWeb: boolean) => string | undefined;
1775
+ data: {
1776
+ [field: string]: any;
1777
+ name: string;
1778
+ type: string;
1779
+ version: string;
1780
+ main: string;
1781
+ module: string;
1782
+ browser: string | Record<string, string | false>;
1783
+ exports: string | Record<string, any> | string[];
1784
+ imports: Record<string, any>;
1785
+ dependencies: Record<string, string>;
1899
1786
  };
1900
1787
  }
1901
- interface WebSocketClient {
1902
- /**
1903
- * Send event to the client
1904
- */
1905
- send(payload: HMRPayload): void;
1906
- /**
1907
- * Send custom event
1908
- */
1909
- send(event: string, payload?: CustomPayload['data']): void;
1910
- /**
1911
- * The raw WebSocket instance
1912
- * @advanced
1913
- */
1914
- socket: WebSocket;
1915
- }
1916
1788
 
1917
- interface ServerOptions extends CommonServerOptions {
1918
- /**
1919
- * Configure HMR-specific options (port, host, path & protocol)
1920
- */
1921
- hmr?: HmrOptions | boolean;
1922
- /**
1923
- * Warm-up files to transform and cache the results in advance. This improves the
1924
- * initial page load during server starts and prevents transform waterfalls.
1925
- * @deprecated use dev.warmup / environment.ssr.dev.warmup
1926
- */
1927
- warmup?: {
1928
- /**
1929
- * The files to be transformed and used on the client-side. Supports glob patterns.
1930
- */
1931
- clientFiles?: string[];
1932
- /**
1933
- * The files to be transformed and used in SSR. Supports glob patterns.
1934
- */
1935
- ssrFiles?: string[];
1936
- };
1937
- /**
1938
- * chokidar watch options or null to disable FS watching
1939
- * https://github.com/paulmillr/chokidar#api
1940
- */
1941
- watch?: WatchOptions | null;
1942
- /**
1943
- * Create Vite dev server to be used as a middleware in an existing server
1944
- * @default false
1945
- */
1946
- middlewareMode?: boolean | {
1947
- /**
1948
- * Parent server instance to attach to
1949
- *
1950
- * This is needed to proxy WebSocket connections to the parent server.
1951
- */
1952
- server: http.Server;
1953
- };
1954
- /**
1955
- * Options for files served via '/\@fs/'.
1956
- */
1957
- fs?: FileSystemServeOptions;
1789
+ interface BuildEnvironmentOptions {
1958
1790
  /**
1959
- * Origin for the generated asset URLs.
1791
+ * Compatibility transform target. The transform is performed with esbuild
1792
+ * and the lowest supported target is es2015/es6. Note this only handles
1793
+ * syntax transformation and does not cover polyfills (except for dynamic
1794
+ * import)
1960
1795
  *
1961
- * @example `http://127.0.0.1:8080`
1796
+ * Default: 'modules' - Similar to `@babel/preset-env`'s targets.esmodules,
1797
+ * transpile targeting browsers that natively support dynamic es module imports.
1798
+ * https://caniuse.com/es6-module-dynamic-import
1799
+ *
1800
+ * Another special value is 'esnext' - which only performs minimal transpiling
1801
+ * (for minification compat) and assumes native dynamic imports support.
1802
+ *
1803
+ * For custom targets, see https://esbuild.github.io/api/#target and
1804
+ * https://esbuild.github.io/content-types/#javascript for more details.
1805
+ * @default 'modules'
1962
1806
  */
1963
- origin?: string;
1807
+ target?: 'modules' | esbuild_TransformOptions['target'] | false;
1964
1808
  /**
1965
- * Pre-transform known direct imports
1809
+ * whether to inject module preload polyfill.
1810
+ * Note: does not apply to library mode.
1966
1811
  * @default true
1967
- * @deprecated use dev.preTransformRequests
1812
+ * @deprecated use `modulePreload.polyfill` instead
1968
1813
  */
1969
- preTransformRequests?: boolean;
1814
+ polyfillModulePreload?: boolean;
1970
1815
  /**
1971
- * Whether or not to ignore-list source files in the dev server sourcemap, used to populate
1972
- * the [`x_google_ignoreList` source map extension](https://developer.chrome.com/blog/devtools-better-angular-debugging/#the-x_google_ignorelist-source-map-extension).
1973
- *
1974
- * By default, it excludes all paths containing `node_modules`. You can pass `false` to
1975
- * disable this behavior, or, for full control, a function that takes the source path and
1976
- * sourcemap path and returns whether to ignore the source path.
1977
- * @deprecated use dev.sourcemapIgnoreList
1816
+ * Configure module preload
1817
+ * Note: does not apply to library mode.
1818
+ * @default true
1978
1819
  */
1979
- sourcemapIgnoreList?: false | ((sourcePath: string, sourcemapPath: string) => boolean);
1820
+ modulePreload?: boolean | ModulePreloadOptions;
1980
1821
  /**
1981
- * Run HMR tasks, by default the HMR propagation is done in parallel for all environments
1982
- * @experimental
1822
+ * Directory relative from `root` where build output will be placed. If the
1823
+ * directory exists, it will be removed before the build.
1824
+ * @default 'dist'
1983
1825
  */
1984
- hotUpdateEnvironments?: (server: ViteDevServer, hmr: (environment: DevEnvironment) => Promise<void>) => Promise<void>;
1985
- }
1986
- interface ResolvedServerOptions extends Omit<ServerOptions, 'fs' | 'middlewareMode' | 'sourcemapIgnoreList'> {
1987
- fs: Required<FileSystemServeOptions>;
1988
- middlewareMode: NonNullable<ServerOptions['middlewareMode']>;
1989
- sourcemapIgnoreList: Exclude<ServerOptions['sourcemapIgnoreList'], false | undefined>;
1990
- }
1991
- interface FileSystemServeOptions {
1826
+ outDir?: string;
1992
1827
  /**
1993
- * Strictly restrict file accessing outside of allowing paths.
1994
- *
1995
- * Set to `false` to disable the warning
1996
- *
1997
- * @default true
1828
+ * Directory relative from `outDir` where the built js/css/image assets will
1829
+ * be placed.
1830
+ * @default 'assets'
1998
1831
  */
1999
- strict?: boolean;
1832
+ assetsDir?: string;
2000
1833
  /**
2001
- * Restrict accessing files outside the allowed directories.
2002
- *
2003
- * Accepts absolute path or a path relative to project root.
2004
- * Will try to search up for workspace root by default.
1834
+ * Static asset files smaller than this number (in bytes) will be inlined as
1835
+ * base64 strings. Default limit is `4096` (4 KiB). Set to `0` to disable.
1836
+ * @default 4096
2005
1837
  */
2006
- allow?: string[];
1838
+ assetsInlineLimit?: number | ((filePath: string, content: Buffer) => boolean | undefined);
2007
1839
  /**
2008
- * Restrict accessing files that matches the patterns.
2009
- *
2010
- * This will have higher priority than `allow`.
2011
- * picomatch patterns are supported.
2012
- *
2013
- * @default ['.env', '.env.*', '*.crt', '*.pem']
1840
+ * Whether to code-split CSS. When enabled, CSS in async chunks will be
1841
+ * inlined as strings in the chunk and inserted via dynamically created
1842
+ * style tags when the chunk is loaded.
1843
+ * @default true
2014
1844
  */
2015
- deny?: string[];
1845
+ cssCodeSplit?: boolean;
2016
1846
  /**
2017
- * Enable caching of fs calls. It is enabled by default if no custom watch ignored patterns are provided.
2018
- *
2019
- * @experimental
2020
- * @default undefined
1847
+ * An optional separate target for CSS minification.
1848
+ * As esbuild only supports configuring targets to mainstream
1849
+ * browsers, users may need this option when they are targeting
1850
+ * a niche browser that comes with most modern JavaScript features
1851
+ * but has poor CSS support, e.g. Android WeChat WebView, which
1852
+ * doesn't support the #RGBA syntax.
1853
+ * @default target
2021
1854
  */
2022
- cachedChecks?: boolean;
2023
- }
2024
- type ServerHook = (this: void, server: ViteDevServer) => (() => void) | void | Promise<(() => void) | void>;
2025
- type HttpServer = http.Server | Http2SecureServer;
2026
- interface ViteDevServer {
1855
+ cssTarget?: esbuild_TransformOptions['target'] | false;
2027
1856
  /**
2028
- * The resolved vite config object
1857
+ * Override CSS minification specifically instead of defaulting to `build.minify`,
1858
+ * so you can configure minification for JS and CSS separately.
1859
+ * @default 'esbuild'
2029
1860
  */
2030
- config: ResolvedConfig;
1861
+ cssMinify?: boolean | 'esbuild' | 'lightningcss';
2031
1862
  /**
2032
- * A connect app instance.
2033
- * - Can be used to attach custom middlewares to the dev server.
2034
- * - Can also be used as the handler function of a custom http server
2035
- * or as a middleware in any connect-style Node.js frameworks
2036
- *
2037
- * https://github.com/senchalabs/connect#use-middleware
1863
+ * If `true`, a separate sourcemap file will be created. If 'inline', the
1864
+ * sourcemap will be appended to the resulting output file as data URI.
1865
+ * 'hidden' works like `true` except that the corresponding sourcemap
1866
+ * comments in the bundled files are suppressed.
1867
+ * @default false
2038
1868
  */
2039
- middlewares: Connect.Server;
1869
+ sourcemap?: boolean | 'inline' | 'hidden';
2040
1870
  /**
2041
- * native Node http server instance
2042
- * will be null in middleware mode
1871
+ * Set to `false` to disable minification, or specify the minifier to use.
1872
+ * Available options are 'terser' or 'esbuild'.
1873
+ * @default 'esbuild'
2043
1874
  */
2044
- httpServer: HttpServer | null;
1875
+ minify?: boolean | 'terser' | 'esbuild';
2045
1876
  /**
2046
- * chokidar watcher instance
2047
- * https://github.com/paulmillr/chokidar#api
1877
+ * Options for terser
1878
+ * https://terser.org/docs/api-reference#minify-options
1879
+ *
1880
+ * In addition, you can also pass a `maxWorkers: number` option to specify the
1881
+ * max number of workers to spawn. Defaults to the number of CPUs minus 1.
2048
1882
  */
2049
- watcher: FSWatcher;
1883
+ terserOptions?: TerserOptions;
2050
1884
  /**
2051
- * web socket server with `send(payload)` method
2052
- * @deprecated use `hot` instead
1885
+ * Will be merged with internal rollup options.
1886
+ * https://rollupjs.org/configuration-options/
2053
1887
  */
2054
- ws: WebSocketServer;
1888
+ rollupOptions?: RollupOptions;
2055
1889
  /**
2056
- * HMR broadcaster that can be used to send custom HMR messages to the client
2057
- *
2058
- * Always sends a message to at least a WebSocket client. Any third party can
2059
- * add a channel to the broadcaster to process messages
2060
- * @deprecated use `environment.hot` instead
1890
+ * Options to pass on to `@rollup/plugin-commonjs`
2061
1891
  */
2062
- hot: HMRBroadcaster;
1892
+ commonjsOptions?: RollupCommonJSOptions;
2063
1893
  /**
2064
- * Rollup plugin container that can run plugin hooks on a given file
2065
- * @deprecated use `environment.pluginContainer` instead
1894
+ * Options to pass on to `@rollup/plugin-dynamic-import-vars`
2066
1895
  */
2067
- pluginContainer: PluginContainer;
1896
+ dynamicImportVarsOptions?: RollupDynamicImportVarsOptions;
2068
1897
  /**
2069
- * Module execution environments attached to the Vite server.
1898
+ * Whether to write bundle to disk
1899
+ * @default true
2070
1900
  */
2071
- environments: Record<'client' | 'ssr' | (string & {}), DevEnvironment>;
1901
+ write?: boolean;
2072
1902
  /**
2073
- * Module graph that tracks the import relationships, url to file mapping
2074
- * and hmr state.
2075
- * @deprecated use `environment.moduleGraph` instead
1903
+ * Empty outDir on write.
1904
+ * @default true when outDir is a sub directory of project root
2076
1905
  */
2077
- moduleGraph: ModuleGraph;
1906
+ emptyOutDir?: boolean | null;
2078
1907
  /**
2079
- * The resolved urls Vite prints on the CLI. null in middleware mode or
2080
- * before `server.listen` is called.
1908
+ * Copy the public directory to outDir on write.
1909
+ * @default true
2081
1910
  */
2082
- resolvedUrls: ResolvedServerUrls | null;
1911
+ copyPublicDir?: boolean;
2083
1912
  /**
2084
- * Programmatically resolve, load and transform a URL and get the result
2085
- * without going through the http request pipeline.
2086
- * @deprecated use environment.transformRequest
1913
+ * Whether to emit a .vite/manifest.json under assets dir to map hash-less filenames
1914
+ * to their hashed versions. Useful when you want to generate your own HTML
1915
+ * instead of using the one generated by Vite.
1916
+ *
1917
+ * Example:
1918
+ *
1919
+ * ```json
1920
+ * {
1921
+ * "main.js": {
1922
+ * "file": "main.68fe3fad.js",
1923
+ * "css": "main.e6b63442.css",
1924
+ * "imports": [...],
1925
+ * "dynamicImports": [...]
1926
+ * }
1927
+ * }
1928
+ * ```
1929
+ * @default false
2087
1930
  */
2088
- transformRequest(url: string, options?: TransformOptions): Promise<TransformResult | null>;
1931
+ manifest?: boolean | string;
2089
1932
  /**
2090
- * Same as `transformRequest` but only warm up the URLs so the next request
2091
- * will already be cached. The function will never throw as it handles and
2092
- * reports errors internally.
2093
- * @deprecated use environment.warmupRequest
1933
+ * Produce SSR oriented build. Note this requires specifying SSR entry via
1934
+ * `rollupOptions.input`.
1935
+ * @default false
2094
1936
  */
2095
- warmupRequest(url: string, options?: TransformOptions): Promise<void>;
1937
+ ssr?: boolean | string;
2096
1938
  /**
2097
- * Apply vite built-in HTML transforms and any plugin HTML transforms.
1939
+ * Generate SSR manifest for determining style links and asset preload
1940
+ * directives in production.
1941
+ * @default false
2098
1942
  */
2099
- transformIndexHtml(url: string, html: string, originalUrl?: string): Promise<string>;
1943
+ ssrManifest?: boolean | string;
2100
1944
  /**
2101
- * Transform module code into SSR format.
2102
- * TODO: expose this to any environment?
1945
+ * Emit assets during SSR.
1946
+ * @default false
1947
+ * @deprecated use emitAssets
2103
1948
  */
2104
- ssrTransform(code: string, inMap: SourceMap | {
2105
- mappings: '';
2106
- } | null, url: string, originalCode?: string): Promise<TransformResult | null>;
1949
+ ssrEmitAssets?: boolean;
2107
1950
  /**
2108
- * Load a given URL as an instantiated module for SSR.
1951
+ * Emit assets during build. Frameworks can set environments.ssr.build.emitAssets
1952
+ * By default, it is true for the client and false for other environments.
1953
+ * TODO: Should this be true for all environments by default? Or should this be
1954
+ * controlled by the builder so so we can avoid emitting duplicated assets.
2109
1955
  */
2110
- ssrLoadModule(url: string, opts?: {
2111
- fixStacktrace?: boolean;
2112
- }): Promise<Record<string, any>>;
1956
+ emitAssets?: boolean;
2113
1957
  /**
2114
- * Returns a fixed version of the given stack
1958
+ * Set to false to disable reporting compressed chunk sizes.
1959
+ * Can slightly improve build speed.
1960
+ * @default true
2115
1961
  */
2116
- ssrRewriteStacktrace(stack: string): string;
1962
+ reportCompressedSize?: boolean;
2117
1963
  /**
2118
- * Mutates the given SSR error by rewriting the stacktrace
1964
+ * Adjust chunk size warning limit (in kB).
1965
+ * @default 500
2119
1966
  */
2120
- ssrFixStacktrace(e: Error): void;
1967
+ chunkSizeWarningLimit?: number;
2121
1968
  /**
2122
- * Triggers HMR for a module in the module graph. You can use the `server.moduleGraph`
2123
- * API to retrieve the module to be reloaded. If `hmr` is false, this is a no-op.
1969
+ * Rollup watch options
1970
+ * https://rollupjs.org/configuration-options/#watch
1971
+ * @default null
2124
1972
  */
2125
- reloadModule(module: ModuleNode): Promise<void>;
1973
+ watch?: WatcherOptions | null;
2126
1974
  /**
2127
- * Triggers HMR for an environment module in the module graph.
2128
- * If `hmr` is false, this is a no-op.
1975
+ * create the Build Environment instance
2129
1976
  */
2130
- reloadEnvironmentModule(module: EnvironmentModuleNode): Promise<void>;
1977
+ createEnvironment?: (name: string, config: ResolvedConfig) => Promise<BuildEnvironment> | BuildEnvironment;
1978
+ }
1979
+ interface BuildOptions extends BuildEnvironmentOptions {
2131
1980
  /**
2132
- * Start the server.
1981
+ * Build in library mode. The value should be the global name of the lib in
1982
+ * UMD mode. This will produce esm + cjs + umd bundle formats with default
1983
+ * configurations that are suitable for distributing libraries.
1984
+ * @default false
2133
1985
  */
2134
- listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>;
1986
+ lib?: LibraryOptions | false;
1987
+ }
1988
+ interface LibraryOptions {
2135
1989
  /**
2136
- * Stop the server.
1990
+ * Path of library entry
2137
1991
  */
2138
- close(): Promise<void>;
1992
+ entry: InputOption;
2139
1993
  /**
2140
- * Print server urls
1994
+ * The name of the exposed global variable. Required when the `formats` option includes
1995
+ * `umd` or `iife`
2141
1996
  */
2142
- printUrls(): void;
1997
+ name?: string;
2143
1998
  /**
2144
- * Bind CLI shortcuts
1999
+ * Output bundle formats
2000
+ * @default ['es', 'umd']
2145
2001
  */
2146
- bindCLIShortcuts(options?: BindCLIShortcutsOptions<ViteDevServer>): void;
2002
+ formats?: LibraryFormats[];
2147
2003
  /**
2148
- * Restart the server.
2149
- *
2150
- * @param forceOptimize - force the optimizer to re-bundle, same as --force cli flag
2004
+ * The name of the package file output. The default file name is the name option
2005
+ * of the project package.json. It can also be defined as a function taking the
2006
+ * format as an argument.
2151
2007
  */
2152
- restart(forceOptimize?: boolean): Promise<void>;
2008
+ fileName?: string | ((format: ModuleFormat, entryName: string) => string);
2009
+ }
2010
+ type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife';
2011
+ interface ModulePreloadOptions {
2153
2012
  /**
2154
- * Open browser
2013
+ * Whether to inject a module preload polyfill.
2014
+ * Note: does not apply to library mode.
2015
+ * @default true
2155
2016
  */
2156
- openBrowser(): void;
2017
+ polyfill?: boolean;
2157
2018
  /**
2158
- * Calling `await server.waitForRequestsIdle(id)` will wait until all static imports
2159
- * are processed. If called from a load or transform plugin hook, the id needs to be
2160
- * passed as a parameter to avoid deadlocks. Calling this function after the first
2161
- * static imports section of the module graph has been processed will resolve immediately.
2019
+ * Resolve the list of dependencies to preload for a given dynamic import
2162
2020
  * @experimental
2163
- * @deprecated use environment.waitForRequestsIdle()
2164
2021
  */
2165
- waitForRequestsIdle: (ignoredId?: string) => Promise<void>;
2022
+ resolveDependencies?: ResolveModulePreloadDependenciesFn;
2166
2023
  }
2167
- interface ResolvedServerUrls {
2168
- local: string[];
2169
- network: string[];
2024
+ interface ResolvedModulePreloadOptions {
2025
+ polyfill: boolean;
2026
+ resolveDependencies?: ResolveModulePreloadDependenciesFn;
2170
2027
  }
2171
- declare function createServer(inlineConfig?: InlineConfig): Promise<ViteDevServer>;
2172
-
2173
- /** Cache for package.json resolution and package.json contents */
2174
- type PackageCache = Map<string, PackageData>;
2175
- interface PackageData {
2176
- dir: string;
2177
- hasSideEffects: (id: string) => boolean | 'no-treeshake' | null;
2178
- webResolvedImports: Record<string, string | undefined>;
2179
- nodeResolvedImports: Record<string, string | undefined>;
2180
- setResolvedCache: (key: string, entry: string, targetWeb: boolean) => void;
2181
- getResolvedCache: (key: string, targetWeb: boolean) => string | undefined;
2182
- data: {
2183
- [field: string]: any;
2184
- name: string;
2185
- type: string;
2186
- version: string;
2187
- main: string;
2188
- module: string;
2189
- browser: string | Record<string, string | false>;
2190
- exports: string | Record<string, any> | string[];
2191
- imports: Record<string, any>;
2192
- dependencies: Record<string, string>;
2193
- };
2028
+ type ResolveModulePreloadDependenciesFn = (filename: string, deps: string[], context: {
2029
+ hostId: string;
2030
+ hostType: 'html' | 'js';
2031
+ }) => string[];
2032
+ interface ResolvedBuildEnvironmentOptions extends Required<Omit<BuildEnvironmentOptions, 'polyfillModulePreload'>> {
2033
+ modulePreload: false | ResolvedModulePreloadOptions;
2034
+ }
2035
+ interface ResolvedBuildOptions extends Required<Omit<BuildOptions, 'polyfillModulePreload'>> {
2036
+ modulePreload: false | ResolvedModulePreloadOptions;
2037
+ }
2038
+ /**
2039
+ * Bundles the app for production.
2040
+ * Returns a Promise containing the build result.
2041
+ */
2042
+ declare function build(inlineConfig?: InlineConfig): Promise<RollupOutput | RollupOutput[] | RollupWatcher>;
2043
+ type RenderBuiltAssetUrl = (filename: string, type: {
2044
+ type: 'asset' | 'public';
2045
+ hostId: string;
2046
+ hostType: 'js' | 'css' | 'html';
2047
+ ssr: boolean;
2048
+ }) => string | {
2049
+ relative?: boolean;
2050
+ runtime?: string;
2051
+ } | undefined;
2052
+ declare class BuildEnvironment extends BaseEnvironment {
2053
+ mode: "build";
2054
+ constructor(name: string, config: ResolvedConfig, setup?: {
2055
+ options?: EnvironmentOptions;
2056
+ });
2057
+ init(): Promise<void>;
2058
+ }
2059
+ interface ViteBuilder {
2060
+ environments: Record<string, BuildEnvironment>;
2061
+ config: ResolvedConfig;
2062
+ buildApp(): Promise<void>;
2063
+ build(environment: BuildEnvironment): Promise<RollupOutput | RollupOutput[] | RollupWatcher>;
2064
+ }
2065
+ interface BuilderOptions {
2066
+ sharedConfigBuild?: boolean;
2067
+ sharedPlugins?: boolean;
2068
+ entireApp?: boolean;
2069
+ buildApp?: (builder: ViteBuilder) => Promise<void>;
2194
2070
  }
2071
+ type ResolvedBuilderOptions = Required<BuilderOptions>;
2072
+ declare function createBuilder(inlineConfig?: InlineConfig): Promise<ViteBuilder>;
2073
+
2074
+ type Environment = DevEnvironment | BuildEnvironment | ScanEnvironment | FutureCompatEnvironment;
2075
+
2076
+ /**
2077
+ * This file is refactored into TypeScript based on
2078
+ * https://github.com/preactjs/wmr/blob/main/packages/wmr/src/lib/rollup-plugin-container.js
2079
+ */
2080
+
2081
+ interface EnvironmentPluginContainer {
2082
+ options: InputOptions;
2083
+ buildStart(options: InputOptions): Promise<void>;
2084
+ resolveId(id: string, importer: string | undefined, options?: {
2085
+ attributes?: Record<string, string>;
2086
+ custom?: CustomPluginOptions;
2087
+ skip?: Set<Plugin>;
2088
+ isEntry?: boolean;
2089
+ }): Promise<PartialResolvedId | null>;
2090
+ transform(code: string, id: string, options?: {
2091
+ inMap?: SourceDescription['map'];
2092
+ }): Promise<{
2093
+ code: string;
2094
+ map: SourceMap | {
2095
+ mappings: '';
2096
+ } | null;
2097
+ }>;
2098
+ load(id: string, options?: {}): Promise<LoadResult | null>;
2099
+ watchChange(id: string, change: {
2100
+ event: 'create' | 'update' | 'delete';
2101
+ }): Promise<void>;
2102
+ close(): Promise<void>;
2103
+ }
2104
+ interface PluginContainer {
2105
+ options: InputOptions;
2106
+ buildStart(options: InputOptions): Promise<void>;
2107
+ resolveId(id: string, importer?: string, options?: {
2108
+ attributes?: Record<string, string>;
2109
+ custom?: CustomPluginOptions;
2110
+ skip?: Set<Plugin>;
2111
+ ssr?: boolean;
2112
+ environment?: Environment;
2113
+ isEntry?: boolean;
2114
+ }): Promise<PartialResolvedId | null>;
2115
+ transform(code: string, id: string, options?: {
2116
+ inMap?: SourceDescription['map'];
2117
+ ssr?: boolean;
2118
+ environment?: Environment;
2119
+ }): Promise<{
2120
+ code: string;
2121
+ map: SourceMap | {
2122
+ mappings: '';
2123
+ } | null;
2124
+ }>;
2125
+ load(id: string, options?: {
2126
+ ssr?: boolean;
2127
+ environment?: Environment;
2128
+ }): Promise<LoadResult | null>;
2129
+ watchChange(id: string, change: {
2130
+ event: 'create' | 'update' | 'delete';
2131
+ }): Promise<void>;
2132
+ close(): Promise<void>;
2133
+ }
2134
+
2135
+ // Modified and inlined to avoid extra dependency
2136
+ // Source: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/ws/index.d.ts
2137
+
2138
+ declare const WebSocketAlias: typeof WebSocket
2139
+ interface WebSocketAlias extends WebSocket {}
2140
+ // WebSocket socket.
2141
+ declare class WebSocket extends EventEmitter {
2142
+ /** The connection is not yet open. */
2143
+ static readonly CONNECTING: 0
2144
+ /** The connection is open and ready to communicate. */
2145
+ static readonly OPEN: 1
2146
+ /** The connection is in the process of closing. */
2147
+ static readonly CLOSING: 2
2148
+ /** The connection is closed. */
2149
+ static readonly CLOSED: 3
2150
+
2151
+ binaryType: 'nodebuffer' | 'arraybuffer' | 'fragments'
2152
+ readonly bufferedAmount: number
2153
+ readonly extensions: string
2154
+ /** Indicates whether the websocket is paused */
2155
+ readonly isPaused: boolean
2156
+ readonly protocol: string
2157
+ /** The current state of the connection */
2158
+ readonly readyState:
2159
+ | typeof WebSocket.CONNECTING
2160
+ | typeof WebSocket.OPEN
2161
+ | typeof WebSocket.CLOSING
2162
+ | typeof WebSocket.CLOSED
2163
+ readonly url: string
2164
+
2165
+ /** The connection is not yet open. */
2166
+ readonly CONNECTING: 0
2167
+ /** The connection is open and ready to communicate. */
2168
+ readonly OPEN: 1
2169
+ /** The connection is in the process of closing. */
2170
+ readonly CLOSING: 2
2171
+ /** The connection is closed. */
2172
+ readonly CLOSED: 3
2173
+
2174
+ onopen: ((event: WebSocket.Event) => void) | null
2175
+ onerror: ((event: WebSocket.ErrorEvent) => void) | null
2176
+ onclose: ((event: WebSocket.CloseEvent) => void) | null
2177
+ onmessage: ((event: WebSocket.MessageEvent) => void) | null
2178
+
2179
+ constructor(address: null)
2180
+ constructor(
2181
+ address: string | URL,
2182
+ options?: WebSocket.ClientOptions | ClientRequestArgs,
2183
+ )
2184
+ constructor(
2185
+ address: string | URL,
2186
+ protocols?: string | string[],
2187
+ options?: WebSocket.ClientOptions | ClientRequestArgs,
2188
+ )
2189
+
2190
+ close(code?: number, data?: string | Buffer): void
2191
+ ping(data?: any, mask?: boolean, cb?: (err: Error) => void): void
2192
+ pong(data?: any, mask?: boolean, cb?: (err: Error) => void): void
2193
+ send(data: any, cb?: (err?: Error) => void): void
2194
+ send(
2195
+ data: any,
2196
+ options: {
2197
+ mask?: boolean | undefined
2198
+ binary?: boolean | undefined
2199
+ compress?: boolean | undefined
2200
+ fin?: boolean | undefined
2201
+ },
2202
+ cb?: (err?: Error) => void,
2203
+ ): void
2204
+ terminate(): void
2195
2205
 
2196
- interface RollupCommonJSOptions {
2197
- /**
2198
- * A minimatch pattern, or array of patterns, which specifies the files in
2199
- * the build the plugin should operate on. By default, all files with
2200
- * extension `".cjs"` or those in `extensions` are included, but you can
2201
- * narrow this list by only including specific files. These files will be
2202
- * analyzed and transpiled if either the analysis does not find ES module
2203
- * specific statements or `transformMixedEsModules` is `true`.
2204
- * @default undefined
2205
- */
2206
- include?: string | RegExp | readonly (string | RegExp)[]
2207
- /**
2208
- * A minimatch pattern, or array of patterns, which specifies the files in
2209
- * the build the plugin should _ignore_. By default, all files with
2210
- * extensions other than those in `extensions` or `".cjs"` are ignored, but you
2211
- * can exclude additional files. See also the `include` option.
2212
- * @default undefined
2213
- */
2214
- exclude?: string | RegExp | readonly (string | RegExp)[]
2215
- /**
2216
- * For extensionless imports, search for extensions other than .js in the
2217
- * order specified. Note that you need to make sure that non-JavaScript files
2218
- * are transpiled by another plugin first.
2219
- * @default [ '.js' ]
2220
- */
2221
- extensions?: ReadonlyArray<string>
2222
- /**
2223
- * If true then uses of `global` won't be dealt with by this plugin
2224
- * @default false
2225
- */
2226
- ignoreGlobal?: boolean
2227
- /**
2228
- * If false, skips source map generation for CommonJS modules. This will
2229
- * improve performance.
2230
- * @default true
2231
- */
2232
- sourceMap?: boolean
2233
- /**
2234
- * Some `require` calls cannot be resolved statically to be translated to
2235
- * imports.
2236
- * When this option is set to `false`, the generated code will either
2237
- * directly throw an error when such a call is encountered or, when
2238
- * `dynamicRequireTargets` is used, when such a call cannot be resolved with a
2239
- * configured dynamic require target.
2240
- * Setting this option to `true` will instead leave the `require` call in the
2241
- * code or use it as a fallback for `dynamicRequireTargets`.
2242
- * @default false
2243
- */
2244
- ignoreDynamicRequires?: boolean
2245
- /**
2246
- * Instructs the plugin whether to enable mixed module transformations. This
2247
- * is useful in scenarios with modules that contain a mix of ES `import`
2248
- * statements and CommonJS `require` expressions. Set to `true` if `require`
2249
- * calls should be transformed to imports in mixed modules, or `false` if the
2250
- * `require` expressions should survive the transformation. The latter can be
2251
- * important if the code contains environment detection, or you are coding
2252
- * for an environment with special treatment for `require` calls such as
2253
- * ElectronJS. See also the `ignore` option.
2254
- * @default false
2255
- */
2256
- transformMixedEsModules?: boolean
2257
- /**
2258
- * By default, this plugin will try to hoist `require` statements as imports
2259
- * to the top of each file. While this works well for many code bases and
2260
- * allows for very efficient ESM output, it does not perfectly capture
2261
- * CommonJS semantics as the order of side effects like log statements may
2262
- * change. But it is especially problematic when there are circular `require`
2263
- * calls between CommonJS modules as those often rely on the lazy execution of
2264
- * nested `require` calls.
2265
- *
2266
- * Setting this option to `true` will wrap all CommonJS files in functions
2267
- * which are executed when they are required for the first time, preserving
2268
- * NodeJS semantics. Note that this can have an impact on the size and
2269
- * performance of the generated code.
2270
- *
2271
- * The default value of `"auto"` will only wrap CommonJS files when they are
2272
- * part of a CommonJS dependency cycle, e.g. an index file that is required by
2273
- * many of its dependencies. All other CommonJS files are hoisted. This is the
2274
- * recommended setting for most code bases.
2275
- *
2276
- * `false` will entirely prevent wrapping and hoist all files. This may still
2277
- * work depending on the nature of cyclic dependencies but will often cause
2278
- * problems.
2279
- *
2280
- * You can also provide a minimatch pattern, or array of patterns, to only
2281
- * specify a subset of files which should be wrapped in functions for proper
2282
- * `require` semantics.
2283
- *
2284
- * `"debug"` works like `"auto"` but after bundling, it will display a warning
2285
- * containing a list of ids that have been wrapped which can be used as
2286
- * minimatch pattern for fine-tuning.
2287
- * @default "auto"
2288
- */
2289
- strictRequires?: boolean | string | RegExp | readonly (string | RegExp)[]
2290
- /**
2291
- * Sometimes you have to leave require statements unconverted. Pass an array
2292
- * containing the IDs or a `id => boolean` function.
2293
- * @default []
2294
- */
2295
- ignore?: ReadonlyArray<string> | ((id: string) => boolean)
2296
- /**
2297
- * In most cases, where `require` calls are inside a `try-catch` clause,
2298
- * they should be left unconverted as it requires an optional dependency
2299
- * that may or may not be installed beside the rolled up package.
2300
- * Due to the conversion of `require` to a static `import` - the call is
2301
- * hoisted to the top of the file, outside the `try-catch` clause.
2302
- *
2303
- * - `true`: Default. All `require` calls inside a `try` will be left unconverted.
2304
- * - `false`: All `require` calls inside a `try` will be converted as if the
2305
- * `try-catch` clause is not there.
2306
- * - `remove`: Remove all `require` calls from inside any `try` block.
2307
- * - `string[]`: Pass an array containing the IDs to left unconverted.
2308
- * - `((id: string) => boolean|'remove')`: Pass a function that controls
2309
- * individual IDs.
2310
- *
2311
- * @default true
2312
- */
2313
- ignoreTryCatch?:
2314
- | boolean
2315
- | 'remove'
2316
- | ReadonlyArray<string>
2317
- | ((id: string) => boolean | 'remove')
2318
2206
  /**
2319
- * Controls how to render imports from external dependencies. By default,
2320
- * this plugin assumes that all external dependencies are CommonJS. This
2321
- * means they are rendered as default imports to be compatible with e.g.
2322
- * NodeJS where ES modules can only import a default export from a CommonJS
2323
- * dependency.
2324
- *
2325
- * If you set `esmExternals` to `true`, this plugin assumes that all
2326
- * external dependencies are ES modules and respect the
2327
- * `requireReturnsDefault` option. If that option is not set, they will be
2328
- * rendered as namespace imports.
2329
- *
2330
- * You can also supply an array of ids to be treated as ES modules, or a
2331
- * function that will be passed each external id to determine whether it is
2332
- * an ES module.
2333
- * @default false
2207
+ * Pause the websocket causing it to stop emitting events. Some events can still be
2208
+ * emitted after this is called, until all buffered data is consumed. This method
2209
+ * is a noop if the ready state is `CONNECTING` or `CLOSED`.
2334
2210
  */
2335
- esmExternals?: boolean | ReadonlyArray<string> | ((id: string) => boolean)
2211
+ pause(): void
2336
2212
  /**
2337
- * Controls what is returned when requiring an ES module from a CommonJS file.
2338
- * When using the `esmExternals` option, this will also apply to external
2339
- * modules. By default, this plugin will render those imports as namespace
2340
- * imports i.e.
2341
- *
2342
- * ```js
2343
- * // input
2344
- * const foo = require('foo');
2345
- *
2346
- * // output
2347
- * import * as foo from 'foo';
2348
- * ```
2349
- *
2350
- * However, there are some situations where this may not be desired.
2351
- * For these situations, you can change Rollup's behaviour either globally or
2352
- * per module. To change it globally, set the `requireReturnsDefault` option
2353
- * to one of the following values:
2354
- *
2355
- * - `false`: This is the default, requiring an ES module returns its
2356
- * namespace. This is the only option that will also add a marker
2357
- * `__esModule: true` to the namespace to support interop patterns in
2358
- * CommonJS modules that are transpiled ES modules.
2359
- * - `"namespace"`: Like `false`, requiring an ES module returns its
2360
- * namespace, but the plugin does not add the `__esModule` marker and thus
2361
- * creates more efficient code. For external dependencies when using
2362
- * `esmExternals: true`, no additional interop code is generated.
2363
- * - `"auto"`: This is complementary to how `output.exports: "auto"` works in
2364
- * Rollup: If a module has a default export and no named exports, requiring
2365
- * that module returns the default export. In all other cases, the namespace
2366
- * is returned. For external dependencies when using `esmExternals: true`, a
2367
- * corresponding interop helper is added.
2368
- * - `"preferred"`: If a module has a default export, requiring that module
2369
- * always returns the default export, no matter whether additional named
2370
- * exports exist. This is similar to how previous versions of this plugin
2371
- * worked. Again for external dependencies when using `esmExternals: true`,
2372
- * an interop helper is added.
2373
- * - `true`: This will always try to return the default export on require
2374
- * without checking if it actually exists. This can throw at build time if
2375
- * there is no default export. This is how external dependencies are handled
2376
- * when `esmExternals` is not used. The advantage over the other options is
2377
- * that, like `false`, this does not add an interop helper for external
2378
- * dependencies, keeping the code lean.
2379
- *
2380
- * To change this for individual modules, you can supply a function for
2381
- * `requireReturnsDefault` instead. This function will then be called once for
2382
- * each required ES module or external dependency with the corresponding id
2383
- * and allows you to return different values for different modules.
2384
- * @default false
2213
+ * Make a paused socket resume emitting events. This method is a noop if the ready
2214
+ * state is `CONNECTING` or `CLOSED`.
2385
2215
  */
2386
- requireReturnsDefault?:
2387
- | boolean
2388
- | 'auto'
2389
- | 'preferred'
2390
- | 'namespace'
2391
- | ((id: string) => boolean | 'auto' | 'preferred' | 'namespace')
2216
+ resume(): void
2217
+
2218
+ // HTML5 WebSocket events
2219
+ addEventListener(
2220
+ method: 'message',
2221
+ cb: (event: WebSocket.MessageEvent) => void,
2222
+ options?: WebSocket.EventListenerOptions,
2223
+ ): void
2224
+ addEventListener(
2225
+ method: 'close',
2226
+ cb: (event: WebSocket.CloseEvent) => void,
2227
+ options?: WebSocket.EventListenerOptions,
2228
+ ): void
2229
+ addEventListener(
2230
+ method: 'error',
2231
+ cb: (event: WebSocket.ErrorEvent) => void,
2232
+ options?: WebSocket.EventListenerOptions,
2233
+ ): void
2234
+ addEventListener(
2235
+ method: 'open',
2236
+ cb: (event: WebSocket.Event) => void,
2237
+ options?: WebSocket.EventListenerOptions,
2238
+ ): void
2239
+
2240
+ removeEventListener(
2241
+ method: 'message',
2242
+ cb: (event: WebSocket.MessageEvent) => void,
2243
+ ): void
2244
+ removeEventListener(
2245
+ method: 'close',
2246
+ cb: (event: WebSocket.CloseEvent) => void,
2247
+ ): void
2248
+ removeEventListener(
2249
+ method: 'error',
2250
+ cb: (event: WebSocket.ErrorEvent) => void,
2251
+ ): void
2252
+ removeEventListener(
2253
+ method: 'open',
2254
+ cb: (event: WebSocket.Event) => void,
2255
+ ): void
2256
+
2257
+ // Events
2258
+ on(
2259
+ event: 'close',
2260
+ listener: (this: WebSocket, code: number, reason: Buffer) => void,
2261
+ ): this
2262
+ on(event: 'error', listener: (this: WebSocket, err: Error) => void): this
2263
+ on(
2264
+ event: 'upgrade',
2265
+ listener: (this: WebSocket, request: IncomingMessage) => void,
2266
+ ): this
2267
+ on(
2268
+ event: 'message',
2269
+ listener: (
2270
+ this: WebSocket,
2271
+ data: WebSocket.RawData,
2272
+ isBinary: boolean,
2273
+ ) => void,
2274
+ ): this
2275
+ on(event: 'open', listener: (this: WebSocket) => void): this
2276
+ on(
2277
+ event: 'ping' | 'pong',
2278
+ listener: (this: WebSocket, data: Buffer) => void,
2279
+ ): this
2280
+ on(
2281
+ event: 'unexpected-response',
2282
+ listener: (
2283
+ this: WebSocket,
2284
+ request: ClientRequest,
2285
+ response: IncomingMessage,
2286
+ ) => void,
2287
+ ): this
2288
+ on(
2289
+ event: string | symbol,
2290
+ listener: (this: WebSocket, ...args: any[]) => void,
2291
+ ): this
2392
2292
 
2293
+ once(
2294
+ event: 'close',
2295
+ listener: (this: WebSocket, code: number, reason: Buffer) => void,
2296
+ ): this
2297
+ once(event: 'error', listener: (this: WebSocket, err: Error) => void): this
2298
+ once(
2299
+ event: 'upgrade',
2300
+ listener: (this: WebSocket, request: IncomingMessage) => void,
2301
+ ): this
2302
+ once(
2303
+ event: 'message',
2304
+ listener: (
2305
+ this: WebSocket,
2306
+ data: WebSocket.RawData,
2307
+ isBinary: boolean,
2308
+ ) => void,
2309
+ ): this
2310
+ once(event: 'open', listener: (this: WebSocket) => void): this
2311
+ once(
2312
+ event: 'ping' | 'pong',
2313
+ listener: (this: WebSocket, data: Buffer) => void,
2314
+ ): this
2315
+ once(
2316
+ event: 'unexpected-response',
2317
+ listener: (
2318
+ this: WebSocket,
2319
+ request: ClientRequest,
2320
+ response: IncomingMessage,
2321
+ ) => void,
2322
+ ): this
2323
+ once(
2324
+ event: string | symbol,
2325
+ listener: (this: WebSocket, ...args: any[]) => void,
2326
+ ): this
2327
+
2328
+ off(
2329
+ event: 'close',
2330
+ listener: (this: WebSocket, code: number, reason: Buffer) => void,
2331
+ ): this
2332
+ off(event: 'error', listener: (this: WebSocket, err: Error) => void): this
2333
+ off(
2334
+ event: 'upgrade',
2335
+ listener: (this: WebSocket, request: IncomingMessage) => void,
2336
+ ): this
2337
+ off(
2338
+ event: 'message',
2339
+ listener: (
2340
+ this: WebSocket,
2341
+ data: WebSocket.RawData,
2342
+ isBinary: boolean,
2343
+ ) => void,
2344
+ ): this
2345
+ off(event: 'open', listener: (this: WebSocket) => void): this
2346
+ off(
2347
+ event: 'ping' | 'pong',
2348
+ listener: (this: WebSocket, data: Buffer) => void,
2349
+ ): this
2350
+ off(
2351
+ event: 'unexpected-response',
2352
+ listener: (
2353
+ this: WebSocket,
2354
+ request: ClientRequest,
2355
+ response: IncomingMessage,
2356
+ ) => void,
2357
+ ): this
2358
+ off(
2359
+ event: string | symbol,
2360
+ listener: (this: WebSocket, ...args: any[]) => void,
2361
+ ): this
2362
+
2363
+ addListener(
2364
+ event: 'close',
2365
+ listener: (code: number, reason: Buffer) => void,
2366
+ ): this
2367
+ addListener(event: 'error', listener: (err: Error) => void): this
2368
+ addListener(
2369
+ event: 'upgrade',
2370
+ listener: (request: IncomingMessage) => void,
2371
+ ): this
2372
+ addListener(
2373
+ event: 'message',
2374
+ listener: (data: WebSocket.RawData, isBinary: boolean) => void,
2375
+ ): this
2376
+ addListener(event: 'open', listener: () => void): this
2377
+ addListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
2378
+ addListener(
2379
+ event: 'unexpected-response',
2380
+ listener: (request: ClientRequest, response: IncomingMessage) => void,
2381
+ ): this
2382
+ addListener(event: string | symbol, listener: (...args: any[]) => void): this
2383
+
2384
+ removeListener(
2385
+ event: 'close',
2386
+ listener: (code: number, reason: Buffer) => void,
2387
+ ): this
2388
+ removeListener(event: 'error', listener: (err: Error) => void): this
2389
+ removeListener(
2390
+ event: 'upgrade',
2391
+ listener: (request: IncomingMessage) => void,
2392
+ ): this
2393
+ removeListener(
2394
+ event: 'message',
2395
+ listener: (data: WebSocket.RawData, isBinary: boolean) => void,
2396
+ ): this
2397
+ removeListener(event: 'open', listener: () => void): this
2398
+ removeListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
2399
+ removeListener(
2400
+ event: 'unexpected-response',
2401
+ listener: (request: ClientRequest, response: IncomingMessage) => void,
2402
+ ): this
2403
+ removeListener(
2404
+ event: string | symbol,
2405
+ listener: (...args: any[]) => void,
2406
+ ): this
2407
+ }
2408
+ // tslint:disable-line no-empty-interface
2409
+
2410
+ declare namespace WebSocket {
2393
2411
  /**
2394
- * @default "auto"
2395
- */
2396
- defaultIsModuleExports?: boolean | 'auto' | ((id: string) => boolean | 'auto')
2397
- /**
2398
- * Some modules contain dynamic `require` calls, or require modules that
2399
- * contain circular dependencies, which are not handled well by static
2400
- * imports. Including those modules as `dynamicRequireTargets` will simulate a
2401
- * CommonJS (NodeJS-like) environment for them with support for dynamic
2402
- * dependencies. It also enables `strictRequires` for those modules.
2403
- *
2404
- * Note: In extreme cases, this feature may result in some paths being
2405
- * rendered as absolute in the final bundle. The plugin tries to avoid
2406
- * exposing paths from the local machine, but if you are `dynamicRequirePaths`
2407
- * with paths that are far away from your project's folder, that may require
2408
- * replacing strings like `"/Users/John/Desktop/foo-project/"` -\> `"/"`.
2412
+ * Data represents the raw message payload received over the WebSocket.
2409
2413
  */
2410
- dynamicRequireTargets?: string | ReadonlyArray<string>
2414
+ type RawData = Buffer | ArrayBuffer | Buffer[]
2415
+
2411
2416
  /**
2412
- * To avoid long paths when using the `dynamicRequireTargets` option, you can use this option to specify a directory
2413
- * that is a common parent for all files that use dynamic require statements. Using a directory higher up such as `/`
2414
- * may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your
2415
- * home directory name. By default, it uses the current working directory.
2417
+ * Data represents the message payload received over the WebSocket.
2416
2418
  */
2417
- dynamicRequireRoot?: string
2418
- }
2419
+ type Data = string | Buffer | ArrayBuffer | Buffer[]
2419
2420
 
2420
- interface RollupDynamicImportVarsOptions {
2421
2421
  /**
2422
- * Files to include in this plugin (default all).
2423
- * @default []
2422
+ * CertMeta represents the accepted types for certificate & key data.
2424
2423
  */
2425
- include?: string | RegExp | (string | RegExp)[]
2424
+ type CertMeta = string | string[] | Buffer | Buffer[]
2425
+
2426
2426
  /**
2427
- * Files to exclude in this plugin (default none).
2428
- * @default []
2427
+ * VerifyClientCallbackSync is a synchronous callback used to inspect the
2428
+ * incoming message. The return value (boolean) of the function determines
2429
+ * whether or not to accept the handshake.
2429
2430
  */
2430
- exclude?: string | RegExp | (string | RegExp)[]
2431
+ type VerifyClientCallbackSync = (info: {
2432
+ origin: string
2433
+ secure: boolean
2434
+ req: IncomingMessage
2435
+ }) => boolean
2436
+
2431
2437
  /**
2432
- * 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.
2433
- * @default false
2438
+ * VerifyClientCallbackAsync is an asynchronous callback used to inspect the
2439
+ * incoming message. The return value (boolean) of the function determines
2440
+ * whether or not to accept the handshake.
2434
2441
  */
2435
- warnOnError?: boolean
2436
- }
2437
-
2438
- // Modified and inlined to avoid extra dependency
2439
- // Source: https://github.com/terser/terser/blob/master/tools/terser.d.ts
2440
- // BSD Licensed https://github.com/terser/terser/blob/master/LICENSE
2441
-
2442
- declare namespace Terser {
2443
- export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020
2444
-
2445
- export interface ParseOptions {
2446
- bare_returns?: boolean
2447
- /** @deprecated legacy option. Currently, all supported EcmaScript is valid to parse. */
2448
- ecma?: ECMA
2449
- html5_comments?: boolean
2450
- shebang?: boolean
2451
- }
2442
+ type VerifyClientCallbackAsync = (
2443
+ info: { origin: string; secure: boolean; req: IncomingMessage },
2444
+ callback: (
2445
+ res: boolean,
2446
+ code?: number,
2447
+ message?: string,
2448
+ headers?: OutgoingHttpHeaders,
2449
+ ) => void,
2450
+ ) => void
2452
2451
 
2453
- export interface CompressOptions {
2454
- arguments?: boolean
2455
- arrows?: boolean
2456
- booleans_as_integers?: boolean
2457
- booleans?: boolean
2458
- collapse_vars?: boolean
2459
- comparisons?: boolean
2460
- computed_props?: boolean
2461
- conditionals?: boolean
2462
- dead_code?: boolean
2463
- defaults?: boolean
2464
- directives?: boolean
2465
- drop_console?: boolean
2466
- drop_debugger?: boolean
2467
- ecma?: ECMA
2468
- evaluate?: boolean
2469
- expression?: boolean
2470
- global_defs?: object
2471
- hoist_funs?: boolean
2472
- hoist_props?: boolean
2473
- hoist_vars?: boolean
2474
- ie8?: boolean
2475
- if_return?: boolean
2476
- inline?: boolean | InlineFunctions
2477
- join_vars?: boolean
2478
- keep_classnames?: boolean | RegExp
2479
- keep_fargs?: boolean
2480
- keep_fnames?: boolean | RegExp
2481
- keep_infinity?: boolean
2482
- loops?: boolean
2483
- module?: boolean
2484
- negate_iife?: boolean
2485
- passes?: number
2486
- properties?: boolean
2487
- pure_funcs?: string[]
2488
- pure_getters?: boolean | 'strict'
2489
- reduce_funcs?: boolean
2490
- reduce_vars?: boolean
2491
- sequences?: boolean | number
2492
- side_effects?: boolean
2493
- switches?: boolean
2494
- toplevel?: boolean
2495
- top_retain?: null | string | string[] | RegExp
2496
- typeofs?: boolean
2497
- unsafe_arrows?: boolean
2498
- unsafe?: boolean
2499
- unsafe_comps?: boolean
2500
- unsafe_Function?: boolean
2501
- unsafe_math?: boolean
2502
- unsafe_symbols?: boolean
2503
- unsafe_methods?: boolean
2504
- unsafe_proto?: boolean
2505
- unsafe_regexp?: boolean
2506
- unsafe_undefined?: boolean
2507
- unused?: boolean
2452
+ interface ClientOptions extends SecureContextOptions {
2453
+ protocol?: string | undefined
2454
+ followRedirects?: boolean | undefined
2455
+ generateMask?(mask: Buffer): void
2456
+ handshakeTimeout?: number | undefined
2457
+ maxRedirects?: number | undefined
2458
+ perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
2459
+ localAddress?: string | undefined
2460
+ protocolVersion?: number | undefined
2461
+ headers?: { [key: string]: string } | undefined
2462
+ origin?: string | undefined
2463
+ agent?: Agent | undefined
2464
+ host?: string | undefined
2465
+ family?: number | undefined
2466
+ checkServerIdentity?(servername: string, cert: CertMeta): boolean
2467
+ rejectUnauthorized?: boolean | undefined
2468
+ maxPayload?: number | undefined
2469
+ skipUTF8Validation?: boolean | undefined
2508
2470
  }
2509
2471
 
2510
- export enum InlineFunctions {
2511
- Disabled = 0,
2512
- SimpleFunctions = 1,
2513
- WithArguments = 2,
2514
- WithArgumentsAndVariables = 3,
2472
+ 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
2515
2493
  }
2516
2494
 
2517
- export interface MangleOptions {
2518
- eval?: boolean
2519
- keep_classnames?: boolean | RegExp
2520
- keep_fnames?: boolean | RegExp
2521
- module?: boolean
2522
- nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler
2523
- properties?: boolean | ManglePropertiesOptions
2524
- reserved?: string[]
2525
- safari10?: boolean
2526
- toplevel?: boolean
2495
+ interface Event {
2496
+ type: string
2497
+ target: WebSocket
2527
2498
  }
2528
2499
 
2529
- /**
2530
- * An identifier mangler for which the output is invariant with respect to the source code.
2531
- */
2532
- export interface SimpleIdentifierMangler {
2533
- /**
2534
- * Obtains the nth most favored (usually shortest) identifier to rename a variable to.
2535
- * The mangler will increment n and retry until the return value is not in use in scope, and is not a reserved word.
2536
- * This function is expected to be stable; Evaluating get(n) === get(n) should always return true.
2537
- * @param n - The ordinal of the identifier.
2538
- */
2539
- get(n: number): string
2500
+ interface ErrorEvent {
2501
+ error: any
2502
+ message: string
2503
+ type: string
2504
+ target: WebSocket
2540
2505
  }
2541
2506
 
2542
- /**
2543
- * An identifier mangler that leverages character frequency analysis to determine identifier precedence.
2544
- */
2545
- export interface WeightedIdentifierMangler extends SimpleIdentifierMangler {
2546
- /**
2547
- * Modifies the internal weighting of the input characters by the specified delta.
2548
- * Will be invoked on the entire printed AST, and then deduct mangleable identifiers.
2549
- * @param chars - The characters to modify the weighting of.
2550
- * @param delta - The numeric weight to add to the characters.
2551
- */
2552
- consider(chars: string, delta: number): number
2553
- /**
2554
- * Resets character weights.
2555
- */
2556
- reset(): void
2557
- /**
2558
- * Sorts identifiers by character frequency, in preparation for calls to get(n).
2559
- */
2560
- sort(): void
2507
+ interface CloseEvent {
2508
+ wasClean: boolean
2509
+ code: number
2510
+ reason: string
2511
+ type: string
2512
+ target: WebSocket
2561
2513
  }
2562
2514
 
2563
- export interface ManglePropertiesOptions {
2564
- builtins?: boolean
2565
- debug?: boolean
2566
- keep_quoted?: boolean | 'strict'
2567
- nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler
2568
- regex?: RegExp | string
2569
- reserved?: string[]
2515
+ interface MessageEvent {
2516
+ data: Data
2517
+ type: string
2518
+ target: WebSocket
2570
2519
  }
2571
2520
 
2572
- export interface FormatOptions {
2573
- ascii_only?: boolean
2574
- /** @deprecated Not implemented anymore */
2575
- beautify?: boolean
2576
- braces?: boolean
2577
- comments?:
2578
- | boolean
2579
- | 'all'
2580
- | 'some'
2581
- | RegExp
2582
- | ((
2583
- node: any,
2584
- comment: {
2585
- value: string
2586
- type: 'comment1' | 'comment2' | 'comment3' | 'comment4'
2587
- pos: number
2588
- line: number
2589
- col: number
2590
- },
2591
- ) => boolean)
2592
- ecma?: ECMA
2593
- ie8?: boolean
2594
- keep_numbers?: boolean
2595
- indent_level?: number
2596
- indent_start?: number
2597
- inline_script?: boolean
2598
- keep_quoted_props?: boolean
2599
- max_line_len?: number | false
2600
- preamble?: string
2601
- preserve_annotations?: boolean
2602
- quote_keys?: boolean
2603
- quote_style?: OutputQuoteStyle
2604
- safari10?: boolean
2605
- semicolons?: boolean
2606
- shebang?: boolean
2607
- shorthand?: boolean
2608
- source_map?: SourceMapOptions
2609
- webkit?: boolean
2610
- width?: number
2611
- wrap_iife?: boolean
2612
- wrap_func_args?: boolean
2521
+ interface EventListenerOptions {
2522
+ once?: boolean | undefined
2613
2523
  }
2614
2524
 
2615
- export enum OutputQuoteStyle {
2616
- PreferDouble = 0,
2617
- AlwaysSingle = 1,
2618
- AlwaysDouble = 2,
2619
- AlwaysOriginal = 3,
2525
+ interface ServerOptions {
2526
+ host?: string | undefined
2527
+ port?: number | undefined
2528
+ backlog?: number | undefined
2529
+ server?: Server | HttpsServer | undefined
2530
+ verifyClient?:
2531
+ | VerifyClientCallbackAsync
2532
+ | VerifyClientCallbackSync
2533
+ | undefined
2534
+ handleProtocols?: (
2535
+ protocols: Set<string>,
2536
+ request: IncomingMessage,
2537
+ ) => string | false
2538
+ path?: string | undefined
2539
+ noServer?: boolean | undefined
2540
+ clientTracking?: boolean | undefined
2541
+ perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
2542
+ maxPayload?: number | undefined
2543
+ skipUTF8Validation?: boolean | undefined
2544
+ WebSocket?: typeof WebSocket.WebSocket | undefined
2545
+ }
2546
+
2547
+ interface AddressInfo {
2548
+ address: string
2549
+ family: string
2550
+ port: number
2620
2551
  }
2621
2552
 
2622
- export interface MinifyOptions {
2623
- compress?: boolean | CompressOptions
2624
- ecma?: ECMA
2625
- enclose?: boolean | string
2626
- ie8?: boolean
2627
- keep_classnames?: boolean | RegExp
2628
- keep_fnames?: boolean | RegExp
2629
- mangle?: boolean | MangleOptions
2630
- module?: boolean
2631
- nameCache?: object
2632
- format?: FormatOptions
2633
- /** @deprecated deprecated */
2634
- output?: FormatOptions
2635
- parse?: ParseOptions
2636
- safari10?: boolean
2637
- sourceMap?: boolean | SourceMapOptions
2638
- toplevel?: boolean
2639
- }
2553
+ // WebSocket Server
2554
+ class Server<T extends WebSocket = WebSocket> extends EventEmitter {
2555
+ options: ServerOptions
2556
+ path: string
2557
+ clients: Set<T>
2558
+
2559
+ constructor(options?: ServerOptions, callback?: () => void)
2560
+
2561
+ address(): AddressInfo | string
2562
+ close(cb?: (err?: Error) => void): void
2563
+ handleUpgrade(
2564
+ request: IncomingMessage,
2565
+ socket: Duplex,
2566
+ upgradeHead: Buffer,
2567
+ callback: (client: T, request: IncomingMessage) => void,
2568
+ ): void
2569
+ shouldHandle(request: IncomingMessage): boolean | Promise<boolean>
2570
+
2571
+ // Events
2572
+ on(
2573
+ event: 'connection',
2574
+ cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
2575
+ ): this
2576
+ on(event: 'error', cb: (this: Server<T>, error: Error) => void): this
2577
+ on(
2578
+ event: 'headers',
2579
+ cb: (
2580
+ this: Server<T>,
2581
+ headers: string[],
2582
+ request: IncomingMessage,
2583
+ ) => void,
2584
+ ): this
2585
+ on(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
2586
+ on(
2587
+ event: string | symbol,
2588
+ listener: (this: Server<T>, ...args: any[]) => void,
2589
+ ): this
2590
+
2591
+ once(
2592
+ event: 'connection',
2593
+ cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
2594
+ ): this
2595
+ once(event: 'error', cb: (this: Server<T>, error: Error) => void): this
2596
+ once(
2597
+ event: 'headers',
2598
+ cb: (
2599
+ this: Server<T>,
2600
+ headers: string[],
2601
+ request: IncomingMessage,
2602
+ ) => void,
2603
+ ): this
2604
+ once(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
2605
+ once(
2606
+ event: string | symbol,
2607
+ listener: (this: Server<T>, ...args: any[]) => void,
2608
+ ): this
2609
+
2610
+ off(
2611
+ event: 'connection',
2612
+ cb: (this: Server<T>, socket: T, request: IncomingMessage) => void,
2613
+ ): this
2614
+ off(event: 'error', cb: (this: Server<T>, error: Error) => void): this
2615
+ off(
2616
+ event: 'headers',
2617
+ cb: (
2618
+ this: Server<T>,
2619
+ headers: string[],
2620
+ request: IncomingMessage,
2621
+ ) => void,
2622
+ ): this
2623
+ off(event: 'close' | 'listening', cb: (this: Server<T>) => void): this
2624
+ off(
2625
+ event: string | symbol,
2626
+ listener: (this: Server<T>, ...args: any[]) => void,
2627
+ ): this
2628
+
2629
+ addListener(
2630
+ event: 'connection',
2631
+ cb: (client: T, request: IncomingMessage) => void,
2632
+ ): this
2633
+ addListener(event: 'error', cb: (err: Error) => void): this
2634
+ addListener(
2635
+ event: 'headers',
2636
+ cb: (headers: string[], request: IncomingMessage) => void,
2637
+ ): this
2638
+ addListener(event: 'close' | 'listening', cb: () => void): this
2639
+ addListener(
2640
+ event: string | symbol,
2641
+ listener: (...args: any[]) => void,
2642
+ ): this
2640
2643
 
2641
- export interface MinifyOutput {
2642
- code?: string
2643
- map?: object | string
2644
- decoded_map?: object | null
2644
+ removeListener(event: 'connection', cb: (client: T) => void): this
2645
+ removeListener(event: 'error', cb: (err: Error) => void): this
2646
+ removeListener(
2647
+ event: 'headers',
2648
+ cb: (headers: string[], request: IncomingMessage) => void,
2649
+ ): this
2650
+ removeListener(event: 'close' | 'listening', cb: () => void): this
2651
+ removeListener(
2652
+ event: string | symbol,
2653
+ listener: (...args: any[]) => void,
2654
+ ): this
2645
2655
  }
2646
2656
 
2647
- export interface SourceMapOptions {
2648
- /** Source map object, 'inline' or source map file content */
2649
- content?: object | string
2650
- includeSources?: boolean
2651
- filename?: string
2652
- root?: string
2653
- url?: string | 'inline'
2654
- }
2657
+ const WebSocketServer: typeof Server
2658
+ interface WebSocketServer extends Server {} // tslint:disable-line no-empty-interface
2659
+ const WebSocket: typeof WebSocketAlias
2660
+ interface WebSocket extends WebSocketAlias {} // tslint:disable-line no-empty-interface
2661
+
2662
+ // WebSocket stream
2663
+ function createWebSocketStream(
2664
+ websocket: WebSocket,
2665
+ options?: DuplexOptions,
2666
+ ): Duplex
2655
2667
  }
2656
2668
 
2657
- interface TerserOptions extends Terser.MinifyOptions {
2669
+ type WebSocketCustomListener<T> = (data: T, client: WebSocketClient) => void;
2670
+ interface WebSocketServer extends HMRChannel {
2658
2671
  /**
2659
- * Vite-specific option to specify the max number of workers to spawn
2660
- * when minifying files with terser.
2661
- *
2662
- * @default number of CPUs minus 1
2672
+ * Listen on port and host
2663
2673
  */
2664
- maxWorkers?: number;
2674
+ listen(): void;
2675
+ /**
2676
+ * Get all connected clients.
2677
+ */
2678
+ clients: Set<WebSocketClient>;
2679
+ /**
2680
+ * Disconnect all clients and terminate the server.
2681
+ */
2682
+ close(): Promise<void>;
2683
+ /**
2684
+ * Handle custom event emitted by `import.meta.hot.send`
2685
+ */
2686
+ on: WebSocket.Server['on'] & {
2687
+ <T extends string>(event: T, listener: WebSocketCustomListener<InferCustomEventPayload<T>>): void;
2688
+ };
2689
+ /**
2690
+ * Unregister event listener.
2691
+ */
2692
+ off: WebSocket.Server['off'] & {
2693
+ (event: string, listener: Function): void;
2694
+ };
2695
+ }
2696
+ interface WebSocketClient {
2697
+ /**
2698
+ * Send event to the client
2699
+ */
2700
+ send(payload: HMRPayload): void;
2701
+ /**
2702
+ * Send custom event
2703
+ */
2704
+ send(event: string, payload?: CustomPayload['data']): void;
2705
+ /**
2706
+ * The raw WebSocket instance
2707
+ * @advanced
2708
+ */
2709
+ socket: WebSocket;
2665
2710
  }
2666
2711
 
2667
- interface BuildEnvironmentOptions {
2712
+ interface ServerOptions extends CommonServerOptions {
2668
2713
  /**
2669
- * Compatibility transform target. The transform is performed with esbuild
2670
- * and the lowest supported target is es2015/es6. Note this only handles
2671
- * syntax transformation and does not cover polyfills (except for dynamic
2672
- * import)
2673
- *
2674
- * Default: 'modules' - Similar to `@babel/preset-env`'s targets.esmodules,
2675
- * transpile targeting browsers that natively support dynamic es module imports.
2676
- * https://caniuse.com/es6-module-dynamic-import
2677
- *
2678
- * Another special value is 'esnext' - which only performs minimal transpiling
2679
- * (for minification compat) and assumes native dynamic imports support.
2714
+ * Configure HMR-specific options (port, host, path & protocol)
2715
+ */
2716
+ hmr?: HmrOptions | boolean;
2717
+ /**
2718
+ * Warm-up files to transform and cache the results in advance. This improves the
2719
+ * initial page load during server starts and prevents transform waterfalls.
2720
+ * @deprecated use dev.warmup / environment.ssr.dev.warmup
2721
+ */
2722
+ warmup?: {
2723
+ /**
2724
+ * The files to be transformed and used on the client-side. Supports glob patterns.
2725
+ */
2726
+ clientFiles?: string[];
2727
+ /**
2728
+ * The files to be transformed and used in SSR. Supports glob patterns.
2729
+ */
2730
+ ssrFiles?: string[];
2731
+ };
2732
+ /**
2733
+ * chokidar watch options or null to disable FS watching
2734
+ * https://github.com/paulmillr/chokidar#api
2735
+ */
2736
+ watch?: WatchOptions | null;
2737
+ /**
2738
+ * Create Vite dev server to be used as a middleware in an existing server
2739
+ * @default false
2740
+ */
2741
+ middlewareMode?: boolean | {
2742
+ /**
2743
+ * Parent server instance to attach to
2744
+ *
2745
+ * This is needed to proxy WebSocket connections to the parent server.
2746
+ */
2747
+ server: http.Server;
2748
+ };
2749
+ /**
2750
+ * Options for files served via '/\@fs/'.
2751
+ */
2752
+ fs?: FileSystemServeOptions;
2753
+ /**
2754
+ * Origin for the generated asset URLs.
2680
2755
  *
2681
- * For custom targets, see https://esbuild.github.io/api/#target and
2682
- * https://esbuild.github.io/content-types/#javascript for more details.
2683
- * @default 'modules'
2756
+ * @example `http://127.0.0.1:8080`
2684
2757
  */
2685
- target?: 'modules' | esbuild_TransformOptions['target'] | false;
2758
+ origin?: string;
2686
2759
  /**
2687
- * whether to inject module preload polyfill.
2688
- * Note: does not apply to library mode.
2760
+ * Pre-transform known direct imports
2689
2761
  * @default true
2690
- * @deprecated use `modulePreload.polyfill` instead
2762
+ * @deprecated use dev.preTransformRequests
2691
2763
  */
2692
- polyfillModulePreload?: boolean;
2764
+ preTransformRequests?: boolean;
2693
2765
  /**
2694
- * Configure module preload
2695
- * Note: does not apply to library mode.
2696
- * @default true
2766
+ * Whether or not to ignore-list source files in the dev server sourcemap, used to populate
2767
+ * the [`x_google_ignoreList` source map extension](https://developer.chrome.com/blog/devtools-better-angular-debugging/#the-x_google_ignorelist-source-map-extension).
2768
+ *
2769
+ * By default, it excludes all paths containing `node_modules`. You can pass `false` to
2770
+ * disable this behavior, or, for full control, a function that takes the source path and
2771
+ * sourcemap path and returns whether to ignore the source path.
2772
+ * @deprecated use dev.sourcemapIgnoreList
2697
2773
  */
2698
- modulePreload?: boolean | ModulePreloadOptions;
2774
+ sourcemapIgnoreList?: false | ((sourcePath: string, sourcemapPath: string) => boolean);
2699
2775
  /**
2700
- * Directory relative from `root` where build output will be placed. If the
2701
- * directory exists, it will be removed before the build.
2702
- * @default 'dist'
2776
+ * Run HMR tasks, by default the HMR propagation is done in parallel for all environments
2777
+ * @experimental
2703
2778
  */
2704
- outDir?: string;
2779
+ hotUpdateEnvironments?: (server: ViteDevServer, hmr: (environment: DevEnvironment) => Promise<void>) => Promise<void>;
2780
+ }
2781
+ interface ResolvedServerOptions extends Omit<ServerOptions, 'fs' | 'middlewareMode' | 'sourcemapIgnoreList'> {
2782
+ fs: Required<FileSystemServeOptions>;
2783
+ middlewareMode: NonNullable<ServerOptions['middlewareMode']>;
2784
+ sourcemapIgnoreList: Exclude<ServerOptions['sourcemapIgnoreList'], false | undefined>;
2785
+ }
2786
+ interface FileSystemServeOptions {
2705
2787
  /**
2706
- * Directory relative from `outDir` where the built js/css/image assets will
2707
- * be placed.
2708
- * @default 'assets'
2788
+ * Strictly restrict file accessing outside of allowing paths.
2789
+ *
2790
+ * Set to `false` to disable the warning
2791
+ *
2792
+ * @default true
2709
2793
  */
2710
- assetsDir?: string;
2794
+ strict?: boolean;
2711
2795
  /**
2712
- * Static asset files smaller than this number (in bytes) will be inlined as
2713
- * base64 strings. Default limit is `4096` (4 KiB). Set to `0` to disable.
2714
- * @default 4096
2796
+ * Restrict accessing files outside the allowed directories.
2797
+ *
2798
+ * Accepts absolute path or a path relative to project root.
2799
+ * Will try to search up for workspace root by default.
2715
2800
  */
2716
- assetsInlineLimit?: number | ((filePath: string, content: Buffer) => boolean | undefined);
2801
+ allow?: string[];
2717
2802
  /**
2718
- * Whether to code-split CSS. When enabled, CSS in async chunks will be
2719
- * inlined as strings in the chunk and inserted via dynamically created
2720
- * style tags when the chunk is loaded.
2721
- * @default true
2803
+ * Restrict accessing files that matches the patterns.
2804
+ *
2805
+ * This will have higher priority than `allow`.
2806
+ * picomatch patterns are supported.
2807
+ *
2808
+ * @default ['.env', '.env.*', '*.crt', '*.pem']
2722
2809
  */
2723
- cssCodeSplit?: boolean;
2810
+ deny?: string[];
2724
2811
  /**
2725
- * An optional separate target for CSS minification.
2726
- * As esbuild only supports configuring targets to mainstream
2727
- * browsers, users may need this option when they are targeting
2728
- * a niche browser that comes with most modern JavaScript features
2729
- * but has poor CSS support, e.g. Android WeChat WebView, which
2730
- * doesn't support the #RGBA syntax.
2731
- * @default target
2812
+ * Enable caching of fs calls. It is enabled by default if no custom watch ignored patterns are provided.
2813
+ *
2814
+ * @experimental
2815
+ * @default undefined
2732
2816
  */
2733
- cssTarget?: esbuild_TransformOptions['target'] | false;
2817
+ cachedChecks?: boolean;
2818
+ }
2819
+ type ServerHook = (this: void, server: ViteDevServer) => (() => void) | void | Promise<(() => void) | void>;
2820
+ type HttpServer = http.Server | Http2SecureServer;
2821
+ interface ViteDevServer {
2734
2822
  /**
2735
- * Override CSS minification specifically instead of defaulting to `build.minify`,
2736
- * so you can configure minification for JS and CSS separately.
2737
- * @default 'esbuild'
2823
+ * The resolved vite config object
2738
2824
  */
2739
- cssMinify?: boolean | 'esbuild' | 'lightningcss';
2825
+ config: ResolvedConfig;
2740
2826
  /**
2741
- * If `true`, a separate sourcemap file will be created. If 'inline', the
2742
- * sourcemap will be appended to the resulting output file as data URI.
2743
- * 'hidden' works like `true` except that the corresponding sourcemap
2744
- * comments in the bundled files are suppressed.
2745
- * @default false
2827
+ * A connect app instance.
2828
+ * - Can be used to attach custom middlewares to the dev server.
2829
+ * - Can also be used as the handler function of a custom http server
2830
+ * or as a middleware in any connect-style Node.js frameworks
2831
+ *
2832
+ * https://github.com/senchalabs/connect#use-middleware
2746
2833
  */
2747
- sourcemap?: boolean | 'inline' | 'hidden';
2834
+ middlewares: Connect.Server;
2748
2835
  /**
2749
- * Set to `false` to disable minification, or specify the minifier to use.
2750
- * Available options are 'terser' or 'esbuild'.
2751
- * @default 'esbuild'
2836
+ * native Node http server instance
2837
+ * will be null in middleware mode
2752
2838
  */
2753
- minify?: boolean | 'terser' | 'esbuild';
2839
+ httpServer: HttpServer | null;
2754
2840
  /**
2755
- * Options for terser
2756
- * https://terser.org/docs/api-reference#minify-options
2757
- *
2758
- * In addition, you can also pass a `maxWorkers: number` option to specify the
2759
- * max number of workers to spawn. Defaults to the number of CPUs minus 1.
2841
+ * chokidar watcher instance
2842
+ * https://github.com/paulmillr/chokidar#api
2760
2843
  */
2761
- terserOptions?: TerserOptions;
2844
+ watcher: FSWatcher;
2762
2845
  /**
2763
- * Will be merged with internal rollup options.
2764
- * https://rollupjs.org/configuration-options/
2846
+ * web socket server with `send(payload)` method
2847
+ * @deprecated use `hot` instead
2765
2848
  */
2766
- rollupOptions?: RollupOptions;
2849
+ ws: WebSocketServer;
2767
2850
  /**
2768
- * Options to pass on to `@rollup/plugin-commonjs`
2851
+ * HMR broadcaster that can be used to send custom HMR messages to the client
2852
+ *
2853
+ * Always sends a message to at least a WebSocket client. Any third party can
2854
+ * add a channel to the broadcaster to process messages
2855
+ * @deprecated use `environment.hot` instead
2769
2856
  */
2770
- commonjsOptions?: RollupCommonJSOptions;
2857
+ hot: HMRBroadcaster;
2771
2858
  /**
2772
- * Options to pass on to `@rollup/plugin-dynamic-import-vars`
2859
+ * Rollup plugin container that can run plugin hooks on a given file
2860
+ * @deprecated use `environment.pluginContainer` instead
2773
2861
  */
2774
- dynamicImportVarsOptions?: RollupDynamicImportVarsOptions;
2862
+ pluginContainer: PluginContainer;
2775
2863
  /**
2776
- * Whether to write bundle to disk
2777
- * @default true
2864
+ * Module execution environments attached to the Vite server.
2778
2865
  */
2779
- write?: boolean;
2866
+ environments: Record<'client' | 'ssr' | (string & {}), DevEnvironment>;
2780
2867
  /**
2781
- * Empty outDir on write.
2782
- * @default true when outDir is a sub directory of project root
2868
+ * Module graph that tracks the import relationships, url to file mapping
2869
+ * and hmr state.
2870
+ * @deprecated use `environment.moduleGraph` instead
2783
2871
  */
2784
- emptyOutDir?: boolean | null;
2872
+ moduleGraph: ModuleGraph;
2785
2873
  /**
2786
- * Copy the public directory to outDir on write.
2787
- * @default true
2874
+ * The resolved urls Vite prints on the CLI. null in middleware mode or
2875
+ * before `server.listen` is called.
2788
2876
  */
2789
- copyPublicDir?: boolean;
2877
+ resolvedUrls: ResolvedServerUrls | null;
2790
2878
  /**
2791
- * Whether to emit a .vite/manifest.json under assets dir to map hash-less filenames
2792
- * to their hashed versions. Useful when you want to generate your own HTML
2793
- * instead of using the one generated by Vite.
2794
- *
2795
- * Example:
2796
- *
2797
- * ```json
2798
- * {
2799
- * "main.js": {
2800
- * "file": "main.68fe3fad.js",
2801
- * "css": "main.e6b63442.css",
2802
- * "imports": [...],
2803
- * "dynamicImports": [...]
2804
- * }
2805
- * }
2806
- * ```
2807
- * @default false
2879
+ * Programmatically resolve, load and transform a URL and get the result
2880
+ * without going through the http request pipeline.
2881
+ * @deprecated use environment.transformRequest
2808
2882
  */
2809
- manifest?: boolean | string;
2883
+ transformRequest(url: string, options?: TransformOptions): Promise<TransformResult | null>;
2810
2884
  /**
2811
- * Produce SSR oriented build. Note this requires specifying SSR entry via
2812
- * `rollupOptions.input`.
2813
- * @default false
2885
+ * Same as `transformRequest` but only warm up the URLs so the next request
2886
+ * will already be cached. The function will never throw as it handles and
2887
+ * reports errors internally.
2888
+ * @deprecated use environment.warmupRequest
2814
2889
  */
2815
- ssr?: boolean | string;
2890
+ warmupRequest(url: string, options?: TransformOptions): Promise<void>;
2816
2891
  /**
2817
- * Generate SSR manifest for determining style links and asset preload
2818
- * directives in production.
2819
- * @default false
2892
+ * Apply vite built-in HTML transforms and any plugin HTML transforms.
2820
2893
  */
2821
- ssrManifest?: boolean | string;
2894
+ transformIndexHtml(url: string, html: string, originalUrl?: string): Promise<string>;
2822
2895
  /**
2823
- * Emit assets during SSR.
2824
- * @default false
2825
- * @deprecated use emitAssets
2896
+ * Transform module code into SSR format.
2897
+ * TODO: expose this to any environment?
2826
2898
  */
2827
- ssrEmitAssets?: boolean;
2899
+ ssrTransform(code: string, inMap: SourceMap | {
2900
+ mappings: '';
2901
+ } | null, url: string, originalCode?: string): Promise<TransformResult | null>;
2828
2902
  /**
2829
- * Emit assets during build. Frameworks can set environments.ssr.build.emitAssets
2830
- * By default, it is true for the client and false for other environments.
2831
- * TODO: Should this be true for all environments by default? Or should this be
2832
- * controlled by the builder so so we can avoid emitting duplicated assets.
2903
+ * Load a given URL as an instantiated module for SSR.
2833
2904
  */
2834
- emitAssets?: boolean;
2905
+ ssrLoadModule(url: string, opts?: {
2906
+ fixStacktrace?: boolean;
2907
+ }): Promise<Record<string, any>>;
2835
2908
  /**
2836
- * Set to false to disable reporting compressed chunk sizes.
2837
- * Can slightly improve build speed.
2838
- * @default true
2909
+ * Returns a fixed version of the given stack
2839
2910
  */
2840
- reportCompressedSize?: boolean;
2911
+ ssrRewriteStacktrace(stack: string): string;
2841
2912
  /**
2842
- * Adjust chunk size warning limit (in kB).
2843
- * @default 500
2913
+ * Mutates the given SSR error by rewriting the stacktrace
2844
2914
  */
2845
- chunkSizeWarningLimit?: number;
2915
+ ssrFixStacktrace(e: Error): void;
2846
2916
  /**
2847
- * Rollup watch options
2848
- * https://rollupjs.org/configuration-options/#watch
2849
- * @default null
2917
+ * Triggers HMR for a module in the module graph. You can use the `server.moduleGraph`
2918
+ * API to retrieve the module to be reloaded. If `hmr` is false, this is a no-op.
2850
2919
  */
2851
- watch?: WatcherOptions | null;
2920
+ reloadModule(module: ModuleNode): Promise<void>;
2852
2921
  /**
2853
- * create the Build Environment instance
2922
+ * Triggers HMR for an environment module in the module graph.
2923
+ * If `hmr` is false, this is a no-op.
2854
2924
  */
2855
- createEnvironment?: (name: string, config: ResolvedConfig) => Promise<BuildEnvironment> | BuildEnvironment;
2856
- }
2857
- interface BuildOptions extends BuildEnvironmentOptions {
2925
+ reloadEnvironmentModule(module: EnvironmentModuleNode): Promise<void>;
2858
2926
  /**
2859
- * Build in library mode. The value should be the global name of the lib in
2860
- * UMD mode. This will produce esm + cjs + umd bundle formats with default
2861
- * configurations that are suitable for distributing libraries.
2862
- * @default false
2927
+ * Start the server.
2863
2928
  */
2864
- lib?: LibraryOptions | false;
2865
- }
2866
- interface LibraryOptions {
2929
+ listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>;
2867
2930
  /**
2868
- * Path of library entry
2931
+ * Stop the server.
2869
2932
  */
2870
- entry: InputOption;
2933
+ close(): Promise<void>;
2871
2934
  /**
2872
- * The name of the exposed global variable. Required when the `formats` option includes
2873
- * `umd` or `iife`
2935
+ * Print server urls
2874
2936
  */
2875
- name?: string;
2937
+ printUrls(): void;
2876
2938
  /**
2877
- * Output bundle formats
2878
- * @default ['es', 'umd']
2939
+ * Bind CLI shortcuts
2879
2940
  */
2880
- formats?: LibraryFormats[];
2941
+ bindCLIShortcuts(options?: BindCLIShortcutsOptions<ViteDevServer>): void;
2881
2942
  /**
2882
- * The name of the package file output. The default file name is the name option
2883
- * of the project package.json. It can also be defined as a function taking the
2884
- * format as an argument.
2943
+ * Restart the server.
2944
+ *
2945
+ * @param forceOptimize - force the optimizer to re-bundle, same as --force cli flag
2885
2946
  */
2886
- fileName?: string | ((format: ModuleFormat, entryName: string) => string);
2887
- }
2888
- type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife';
2889
- interface ModulePreloadOptions {
2947
+ restart(forceOptimize?: boolean): Promise<void>;
2890
2948
  /**
2891
- * Whether to inject a module preload polyfill.
2892
- * Note: does not apply to library mode.
2893
- * @default true
2949
+ * Open browser
2894
2950
  */
2895
- polyfill?: boolean;
2951
+ openBrowser(): void;
2896
2952
  /**
2897
- * Resolve the list of dependencies to preload for a given dynamic import
2953
+ * Calling `await server.waitForRequestsIdle(id)` will wait until all static imports
2954
+ * are processed. If called from a load or transform plugin hook, the id needs to be
2955
+ * passed as a parameter to avoid deadlocks. Calling this function after the first
2956
+ * static imports section of the module graph has been processed will resolve immediately.
2898
2957
  * @experimental
2958
+ * @deprecated use environment.waitForRequestsIdle()
2899
2959
  */
2900
- resolveDependencies?: ResolveModulePreloadDependenciesFn;
2901
- }
2902
- interface ResolvedModulePreloadOptions {
2903
- polyfill: boolean;
2904
- resolveDependencies?: ResolveModulePreloadDependenciesFn;
2905
- }
2906
- type ResolveModulePreloadDependenciesFn = (filename: string, deps: string[], context: {
2907
- hostId: string;
2908
- hostType: 'html' | 'js';
2909
- }) => string[];
2910
- interface ResolvedBuildEnvironmentOptions extends Required<Omit<BuildEnvironmentOptions, 'polyfillModulePreload'>> {
2911
- modulePreload: false | ResolvedModulePreloadOptions;
2912
- }
2913
- interface ResolvedBuildOptions extends Required<Omit<BuildOptions, 'polyfillModulePreload'>> {
2914
- modulePreload: false | ResolvedModulePreloadOptions;
2915
- }
2916
- /**
2917
- * Bundles the app for production.
2918
- * Returns a Promise containing the build result.
2919
- */
2920
- declare function build(inlineConfig?: InlineConfig): Promise<RollupOutput | RollupOutput[] | RollupWatcher>;
2921
- type RenderBuiltAssetUrl = (filename: string, type: {
2922
- type: 'asset' | 'public';
2923
- hostId: string;
2924
- hostType: 'js' | 'css' | 'html';
2925
- ssr: boolean;
2926
- }) => string | {
2927
- relative?: boolean;
2928
- runtime?: string;
2929
- } | undefined;
2930
- declare class BuildEnvironment extends Environment {
2931
- mode: "build";
2932
- constructor(name: string, config: ResolvedConfig, setup?: {
2933
- options?: EnvironmentOptions;
2934
- });
2935
- init(): Promise<void>;
2936
- }
2937
- interface ViteBuilder {
2938
- environments: Record<string, BuildEnvironment>;
2939
- config: ResolvedConfig;
2940
- buildApp(): Promise<void>;
2941
- build(environment: BuildEnvironment): Promise<RollupOutput | RollupOutput[] | RollupWatcher>;
2960
+ waitForRequestsIdle: (ignoredId?: string) => Promise<void>;
2942
2961
  }
2943
- interface BuilderOptions {
2944
- sharedConfigBuild?: boolean;
2945
- sharedPlugins?: boolean;
2946
- entireApp?: boolean;
2947
- buildApp?: (builder: ViteBuilder) => Promise<void>;
2962
+ interface ResolvedServerUrls {
2963
+ local: string[];
2964
+ network: string[];
2948
2965
  }
2949
- type ResolvedBuilderOptions = Required<BuilderOptions>;
2950
- declare function createBuilder(inlineConfig?: InlineConfig): Promise<ViteBuilder>;
2966
+ declare function createServer(inlineConfig?: InlineConfig): Promise<ViteDevServer>;
2951
2967
 
2952
2968
  interface ESBuildOptions extends esbuild_TransformOptions {
2953
2969
  include?: string | RegExp | string[] | RegExp[];
@@ -3153,7 +3169,7 @@ interface PreprocessCSSResult {
3153
3169
  /**
3154
3170
  * @experimental
3155
3171
  */
3156
- declare function preprocessCSS(code: string, filename: string, config: ResolvedConfig, environment?: Environment): Promise<PreprocessCSSResult>;
3172
+ declare function preprocessCSS(code: string, filename: string, config: ResolvedConfig, environment?: PartialEnvironment): Promise<PreprocessCSSResult>;
3157
3173
  declare function formatPostcssSourceMap(rawMap: ExistingRawSourceMap, file: string): Promise<ExistingRawSourceMap>;
3158
3174
 
3159
3175
  interface HtmlTagDescriptor {
@@ -3232,15 +3248,18 @@ type IndexHtmlTransform = IndexHtmlTransformHook | {
3232
3248
  * or a build environment. Plugins can use this.environment.mode === 'dev' to
3233
3249
  * check if they have access to dev specific APIs.
3234
3250
  */
3235
- type PluginEnvironment = DevEnvironment | BuildEnvironment | ScanEnvironment;
3236
- interface PluginContext extends rollup.PluginContext {
3237
- environment?: PluginEnvironment;
3251
+ interface PluginContextExtension {
3252
+ environment?: Environment;
3253
+ }
3254
+ interface PluginContext extends rollup.PluginContext, PluginContextExtension {
3255
+ }
3256
+ interface ResolveIdPluginContext extends rollup.PluginContext, PluginContextExtension {
3238
3257
  }
3239
- interface ResolveIdPluginContext extends rollup.PluginContext {
3240
- environment?: PluginEnvironment;
3258
+ interface TransformPluginContext extends rollup.TransformPluginContext, PluginContextExtension {
3241
3259
  }
3242
- interface TransformPluginContext extends rollup.TransformPluginContext {
3243
- environment?: PluginEnvironment;
3260
+ declare module 'rollup' {
3261
+ interface PluginContext extends PluginContextExtension {
3262
+ }
3244
3263
  }
3245
3264
  /**
3246
3265
  * There are two types of plugins in Vite. App plugins and environment plugins.
@@ -3252,16 +3271,7 @@ interface TransformPluginContext extends rollup.TransformPluginContext {
3252
3271
  * Environment Plugins are closer to regular rollup plugins. They can't define
3253
3272
  * app level hooks (like config, configResolved, configureServer, etc).
3254
3273
  */
3255
- type ModifyFunctionContext<Function_, NewContext> = Function_ extends (this: infer This, ...parameters: infer Arguments) => infer Return ? (this: NewContext, ...parameters: Arguments) => Return : never;
3256
- type ModifyObjectHookContext<Handler, Object_ extends {
3257
- handler: Handler;
3258
- }, NewContext> = Object_ & {
3259
- handler: ModifyFunctionContext<Handler, NewContext>;
3260
- };
3261
- type ModifyHookContext<Hook, NewContext> = Hook extends {
3262
- handler: infer Handler;
3263
- } ? ModifyObjectHookContext<Handler, Hook, NewContext> : ModifyFunctionContext<Hook, NewContext>;
3264
- interface EnvironmentPlugin<A = any> extends rollup.Plugin<A> {
3274
+ interface Plugin<A = any> extends rollup.Plugin<A> {
3265
3275
  /**
3266
3276
  * Perform custom handling of HMR updates.
3267
3277
  * The handler receives a context containing changed filename, timestamp, a
@@ -3302,11 +3312,6 @@ interface EnvironmentPlugin<A = any> extends rollup.Plugin<A> {
3302
3312
  */
3303
3313
  ssr?: boolean;
3304
3314
  }) => Promise<rollup.TransformResult> | rollup.TransformResult>;
3305
- buildStart?: ModifyHookContext<rollup.Plugin<A>['buildStart'], PluginContext>;
3306
- generateBundle?: ModifyHookContext<rollup.Plugin<A>['generateBundle'], PluginContext>;
3307
- renderChunk?: ModifyHookContext<rollup.Plugin<A>['renderChunk'], PluginContext>;
3308
- }
3309
- interface Plugin<A = any> extends EnvironmentPlugin<A> {
3310
3315
  /**
3311
3316
  * Opt-in this plugin into the shared plugins pipeline.
3312
3317
  * For backward-compatibility, plugins are re-recreated for each environment
@@ -3334,6 +3339,11 @@ interface Plugin<A = any> extends EnvironmentPlugin<A> {
3334
3339
  * Apply the plugin only for serve or build, or on certain conditions.
3335
3340
  */
3336
3341
  apply?: 'serve' | 'build' | ((this: void, config: UserConfig, env: ConfigEnv) => boolean);
3342
+ /**
3343
+ * Define environments where this plugin should be active
3344
+ * By default, the plugin is active in all environments
3345
+ */
3346
+ applyToEnvironment?: (environment: Environment) => boolean;
3337
3347
  /**
3338
3348
  * Modify vite config before it's resolved. The hook can either mutate the
3339
3349
  * passed-in config directly, or return a partial config object that will be
@@ -3394,10 +3404,6 @@ interface Plugin<A = any> extends EnvironmentPlugin<A> {
3394
3404
  * `{ order: 'pre', handler: hook }`
3395
3405
  */
3396
3406
  transformIndexHtml?: IndexHtmlTransform;
3397
- /**
3398
- * Inject per environment plugins after the shared plugin
3399
- */
3400
- environmentPlugins?: (environment: PluginEnvironment) => PluginOption[] | undefined;
3401
3407
  /**
3402
3408
  * @deprecated
3403
3409
  * Compat support, ctx.modules is a backward compatible ModuleNode array
@@ -3409,8 +3415,9 @@ type HookHandler<T> = T extends ObjectHook<infer H> ? H : T;
3409
3415
  type PluginWithRequiredHook<K extends keyof Plugin> = Plugin & {
3410
3416
  [P in K]: NonNullable<Plugin[P]>;
3411
3417
  };
3412
- type MaybePlugin = Plugin | false | null | undefined;
3413
- type PluginOption = MaybePlugin | PluginOption[] | Promise<MaybePlugin | PluginOption[]>;
3418
+ type Thenable<T> = T | Promise<T>;
3419
+ type FalsyPlugin = false | null | undefined;
3420
+ type PluginOption = Thenable<Plugin | FalsyPlugin | PluginOption[]>;
3414
3421
 
3415
3422
  interface JsonOptions {
3416
3423
  /**
@@ -3524,7 +3531,7 @@ declare function defineConfig(config: UserConfigFnObject): UserConfigFnObject;
3524
3531
  declare function defineConfig(config: UserConfigExport): UserConfigExport;
3525
3532
  interface DevEnvironmentOptions {
3526
3533
  /**
3527
- * Files tßo be pre-transformed. Supports glob patterns.
3534
+ * Files to be pre-transformed. Supports glob patterns.
3528
3535
  */
3529
3536
  warmup?: string[];
3530
3537
  /**
@@ -3972,6 +3979,12 @@ declare const rollupVersion: string;
3972
3979
  declare function normalizePath(id: string): string;
3973
3980
  declare function mergeConfig<D extends Record<string, any>, O extends Record<string, any>>(defaults: D extends Function ? never : D, overrides: O extends Function ? never : O, isRoot?: boolean): Record<string, any>;
3974
3981
  declare function mergeAlias(a?: AliasOptions, b?: AliasOptions): AliasOptions | undefined;
3982
+ /**
3983
+ * Creates a function that hides the complexities of a WeakMap with an initial value
3984
+ * to implement object metadata. Used by plugins to implement cross hooks per
3985
+ * environment metadata
3986
+ */
3987
+ declare function createWeakData<Key extends WeakKey, Data>(initial: (key: Key) => Data): (key: Key) => Data;
3975
3988
 
3976
3989
  interface SendOptions {
3977
3990
  etag?: string;
@@ -4011,4 +4024,4 @@ interface ManifestChunk {
4011
4024
  dynamicImports?: string[];
4012
4025
  }
4013
4026
 
4014
- export { type Alias, type AliasOptions, type AnymatchFn, type AnymatchPattern, type AppType, type AwaitWriteFinishOptions, type BindCLIShortcutsOptions, BuildEnvironment, type BuildEnvironmentOptions, type BuildOptions, type BuilderOptions, type CLIShortcut, type CSSModulesOptions, type CSSOptions, type CommonServerOptions, type ConfigEnv, Connect, type CorsOptions, type CorsOrigin, type DepOptimizationConfig, type DepOptimizationMetadata, type DepOptimizationOptions, DevEnvironment, type DevEnvironmentOptions, type DevEnvironmentSetup, type ESBuildOptions, type ESBuildTransformResult, EnvironmentModuleGraph, EnvironmentModuleNode, type EnvironmentPlugin, type ExperimentalOptions, type ExportsData, FSWatcher, type FetchModuleOptions, type FileSystemServeOptions, type FilterPattern, type HMRBroadcaster, type HMRBroadcasterClient, type HMRChannel, type HTMLOptions, type HmrContext, type HmrOptions, type HookHandler, type HotUpdateContext, type HtmlTagDescriptor, HttpProxy, type IndexHtmlTransform, type IndexHtmlTransformContext, type IndexHtmlTransformHook, type IndexHtmlTransformResult, type InlineConfig, type InternalResolveOptions, type JsonOptions, type LegacyOptions, type LibraryFormats, type LibraryOptions, type LightningCSSOptions, type LogErrorOptions, type LogLevel, type LogOptions, type LogType, type Logger, type LoggerOptions, type Manifest, type ManifestChunk, type MapToFunction, type AnymatchMatcher as Matcher, ModuleGraph, ModuleNode, type ModulePreloadOptions, type ModuleRunnerTransformOptions, type OptimizedDepInfo, type Plugin, type PluginContainer, type PluginHookUtils, type PluginOption, type PreprocessCSSResult, type PreviewOptions, type PreviewServer, type PreviewServerHook, type ProxyOptions, RemoteEnvironmentTransport, type RenderBuiltAssetUrl, type ResolveFn, type ResolveModulePreloadDependenciesFn, type ResolveOptions, type ResolvedBuildEnvironmentOptions, type ResolvedBuildOptions, type ResolvedCSSOptions, type ResolvedConfig, type ResolvedDevEnvironmentOptions, type ResolvedModulePreloadOptions, type ResolvedPreviewOptions, type ResolvedSSROptions, type ResolvedServerOptions, type ResolvedServerUrls, type ResolvedUrl, type ResolvedWorkerOptions, type ResolverFunction, type ResolverObject, type RollupCommonJSOptions, type RollupDynamicImportVarsOptions, type SSROptions, type SSRTarget, type SendOptions, type ServerHMRChannel, ServerHMRConnector, type ServerHook, type ServerModuleRunnerOptions, type ServerOptions, SplitVendorChunkCache, type SsrDepOptimizationOptions, Terser, type TerserOptions, type TransformOptions, type TransformResult, type UserConfig, type UserConfigExport, type UserConfigFn, type UserConfigFnObject, type UserConfigFnPromise, type ViteBuilder, type ViteDevServer, type WatchOptions, WebSocket, WebSocketAlias, type WebSocketClient, type WebSocketCustomListener, WebSocketServer, build, buildErrorMessage, createBuilder, createFilter, createLogger, createNodeDevEnvironment, createServer, createServerModuleRunner, defineConfig, fetchModule, formatPostcssSourceMap, isCSSRequest, isFileLoadingAllowed, isFileServingAllowed, loadConfigFromFile, loadEnv, mergeAlias, mergeConfig, ssrTransform as moduleRunnerTransform, normalizePath, preprocessCSS, preview, resolveConfig, resolveEnvPrefix, rollupVersion, searchForWorkspaceRoot, send, sortUserPlugins, splitVendorChunk, splitVendorChunkPlugin, transformWithEsbuild, VERSION as version };
4027
+ export { type Alias, type AliasOptions, type AnymatchFn, type AnymatchPattern, type AppType, type AwaitWriteFinishOptions, type BindCLIShortcutsOptions, BuildEnvironment, type BuildEnvironmentOptions, type BuildOptions, type BuilderOptions, type CLIShortcut, type CSSModulesOptions, type CSSOptions, type CommonServerOptions, type ConfigEnv, Connect, type CorsOptions, type CorsOrigin, type DepOptimizationConfig, type DepOptimizationMetadata, type DepOptimizationOptions, DevEnvironment, type DevEnvironmentOptions, type DevEnvironmentSetup, type ESBuildOptions, type ESBuildTransformResult, type Environment, EnvironmentModuleGraph, EnvironmentModuleNode, type ExperimentalOptions, type ExportsData, FSWatcher, type FetchModuleOptions, type FileSystemServeOptions, type FilterPattern, type HMRBroadcaster, type HMRBroadcasterClient, type HMRChannel, type HTMLOptions, type HmrContext, type HmrOptions, type HookHandler, type HotUpdateContext, type HtmlTagDescriptor, HttpProxy, type IndexHtmlTransform, type IndexHtmlTransformContext, type IndexHtmlTransformHook, type IndexHtmlTransformResult, type InlineConfig, type InternalResolveOptions, type JsonOptions, type LegacyOptions, type LibraryFormats, type LibraryOptions, type LightningCSSOptions, type LogErrorOptions, type LogLevel, type LogOptions, type LogType, type Logger, type LoggerOptions, type Manifest, type ManifestChunk, type MapToFunction, type AnymatchMatcher as Matcher, ModuleGraph, ModuleNode, type ModulePreloadOptions, type ModuleRunnerTransformOptions, type OptimizedDepInfo, type Plugin, type PluginContainer, type PluginHookUtils, type PluginOption, type PreprocessCSSResult, type PreviewOptions, type PreviewServer, type PreviewServerHook, type ProxyOptions, RemoteEnvironmentTransport, type RenderBuiltAssetUrl, type ResolveFn, type ResolveModulePreloadDependenciesFn, type ResolveOptions, type ResolvedBuildEnvironmentOptions, type ResolvedBuildOptions, type ResolvedCSSOptions, type ResolvedConfig, type ResolvedDevEnvironmentOptions, type ResolvedModulePreloadOptions, type ResolvedPreviewOptions, type ResolvedSSROptions, type ResolvedServerOptions, type ResolvedServerUrls, type ResolvedUrl, type ResolvedWorkerOptions, type ResolverFunction, type ResolverObject, type RollupCommonJSOptions, type RollupDynamicImportVarsOptions, type SSROptions, type SSRTarget, type SendOptions, type ServerHMRChannel, ServerHMRConnector, type ServerHook, type ServerModuleRunnerOptions, type ServerOptions, SplitVendorChunkCache, type SsrDepOptimizationOptions, Terser, type TerserOptions, type TransformOptions, type TransformResult, type UserConfig, type UserConfigExport, type UserConfigFn, type UserConfigFnObject, type UserConfigFnPromise, type ViteBuilder, type ViteDevServer, type WatchOptions, WebSocket, WebSocketAlias, type WebSocketClient, type WebSocketCustomListener, WebSocketServer, build, buildErrorMessage, createBuilder, createFilter, createLogger, createNodeDevEnvironment, createServer, createServerModuleRunner, createWeakData, defineConfig, fetchModule, formatPostcssSourceMap, isCSSRequest, isFileLoadingAllowed, isFileServingAllowed, loadConfigFromFile, loadEnv, mergeAlias, mergeConfig, ssrTransform as moduleRunnerTransform, normalizePath, optimizeDeps, preprocessCSS, preview, resolveConfig, resolveEnvPrefix, rollupVersion, searchForWorkspaceRoot, send, sortUserPlugins, splitVendorChunk, splitVendorChunkPlugin, transformWithEsbuild, VERSION as version };