Repository navigation
Expand file tree
/
Copy pathServer.js
More file actions
4117 lines (3559 loc) · 125 KB
/
Copy pathServer.js
File metadata and controls
4117 lines (3559 loc) · 125 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { EventEmitter } from "node:events";
import { createRequire } from "node:module";
import os from "node:os";
import path from "node:path";
import url from "node:url";
import util from "node:util";
import fs from "graceful-fs";
import ipaddr from "ipaddr.js";
import { validate } from "schema-utils";
import hotOptions, { bridge, clientEntryQuery } from "./hotOptions.js";
import schemaCheck from "./options.check.js";
import schema from "./options.json" with { type: "json" };
// Named `cjsRequire` (not `require`) so it doesn't shadow the implicit CommonJS
// `require` in the transpiled `dist/cjs` build, which would collide with the
// `require("url")` that `babel-plugin-transform-import-meta` injects here.
const cjsRequire = createRequire(import.meta.url);
/** @type {Promise<typeof import("webpack") | undefined> | undefined} */
let webpackPeer;
/**
* Lazily load the optional `webpack` peer dependency.
* @returns {Promise<typeof import("webpack") | undefined>} resolved webpack module, or undefined when not installed
*/
function loadWebpackPeer() {
webpackPeer ??= import("webpack")
.then((m) => m.default)
.catch(() => undefined);
return webpackPeer;
}
/** @typedef {import("schema-utils").Schema} Schema */
/** @typedef {import("webpack").Compiler} Compiler */
/** @typedef {import("webpack").MultiCompiler} MultiCompiler */
/** @typedef {import("webpack").Configuration} WebpackConfiguration */
/** @typedef {import("webpack").StatsOptions} StatsOptions */
/** @typedef {import("webpack").StatsCompilation} StatsCompilation */
/** @typedef {import("webpack").Stats} Stats */
/** @typedef {import("webpack").MultiStats} MultiStats */
/** @typedef {import("os").NetworkInterfaceInfo} NetworkInterfaceInfo */
/** @typedef {import("chokidar").ChokidarOptions} WatchOptions */
/** @typedef {import("chokidar").FSWatcher} FSWatcher */
/** @typedef {import("connect-history-api-fallback").Options} ConnectHistoryApiFallbackOptions */
/** @typedef {import("bonjour-service").Bonjour} Bonjour */
/** @typedef {import("bonjour-service").Service} BonjourOptions */
/** @typedef {import("http-proxy-middleware").RequestHandler} RequestHandler */
/** @typedef {import("http-proxy-middleware").Options} HttpProxyMiddlewareOptions */
/** @typedef {import("http-proxy-middleware").Filter} HttpProxyMiddlewareOptionsFilter */
/** @typedef {import("serve-index").Options} ServeIndexOptions */
/** @typedef {import("serve-static").ServeStaticOptions} ServeStaticOptions */
/** @typedef {import("ipaddr.js").IPv4} IPv4 */
/** @typedef {import("ipaddr.js").IPv6} IPv6 */
/** @typedef {import("net").Socket} Socket */
/** @typedef {import("http").Server} HTTPServer */
/** @typedef {import("http").IncomingMessage} IncomingMessage */
/** @typedef {import("http").ServerResponse} ServerResponse */
/** @typedef {import("open").Options} OpenOptions */
/** @typedef {import("express").Application} ExpressApplication */
/** @typedef {import("express").RequestHandler} ExpressRequestHandler */
/** @typedef {import("express").ErrorRequestHandler} ExpressErrorRequestHandler */
/** @typedef {import("express").Request} ExpressRequest */
/** @typedef {import("express").Response} ExpressResponse */
// eslint-disable-next-line jsdoc/reject-any-type
/** @typedef {any} EXPECTED_ANY */
/** @typedef {(err?: EXPECTED_ANY) => void} NextFunction */
/** @typedef {(req: IncomingMessage, res: ServerResponse) => void} SimpleHandleFunction */
/** @typedef {(req: IncomingMessage, res: ServerResponse, next: NextFunction) => void} NextHandleFunction */
/** @typedef {(err: EXPECTED_ANY, req: IncomingMessage, res: ServerResponse, next: NextFunction) => void} ErrorHandleFunction */
/** @typedef {SimpleHandleFunction | NextHandleFunction | ErrorHandleFunction} HandleFunction */
/** @typedef {import("https").ServerOptions} ServerOptions */
/**
* @template {BasicApplication} [T=ExpressApplication]
* @typedef {T extends ExpressApplication ? ExpressRequest : IncomingMessage} Request
*/
/**
* @template {BasicApplication} [T=ExpressApplication]
* @typedef {T extends ExpressApplication ? ExpressResponse : ServerResponse} Response
*/
/**
* @template {Request} T
* @template {Response} U
* @typedef {import("webpack-dev-middleware").Options<T, U>} DevMiddlewareOptions
*/
/**
* @template {Request} T
* @template {Response} U
* @typedef {import("webpack-dev-middleware").Context<T, U>} DevMiddlewareContext
*/
/**
* @typedef {"local-ip" | "local-ipv4" | "local-ipv6" | string} Host
*/
/**
* @typedef {number | string | "auto"} Port
*/
/**
* @typedef {object} WatchFiles
* @property {string | string[]} paths paths
* @property {(WatchOptions & { aggregateTimeout?: number, ignored?: WatchOptions["ignored"], poll?: number | boolean })=} options options
*/
/**
* @typedef {object} Static
* @property {string=} directory directory
* @property {(string | string[])=} publicPath public path
* @property {(boolean | ServeIndexOptions)=} serveIndex serve index
* @property {ServeStaticOptions=} staticOptions static options
* @property {(boolean | WatchOptions & { aggregateTimeout?: number, ignored?: WatchOptions["ignored"], poll?: number | boolean })=} watch watch and watch options
*/
/**
* @typedef {object} NormalizedStatic
* @property {string} directory
* @property {string[]} publicPath
* @property {false | ServeIndexOptions} serveIndex
* @property {ServeStaticOptions} staticOptions
* @property {false | WatchOptions} watch
*/
/**
* @template {BasicApplication} [A=ExpressApplication]
* @template {BasicServer} [S=import("http").Server]
* @typedef {"http" | "https" | "http2" | string | ((serverOptions: ServerOptions, application: A) => S)} ServerType
*/
/**
* @template {BasicApplication} [A=ExpressApplication]
* @template {BasicServer} [S=import("http").Server]
* @typedef {object} ServerConfiguration
* @property {ServerType<A, S>=} type type
* @property {ServerOptions=} options options
*/
/**
* @typedef {object} WebSocketServerConfiguration
* @property {("ws" | string | typeof import("./servers/BaseServer.js").default)=} type type
* @property {Record<string, EXPECTED_ANY>=} options options
*/
/**
* @typedef {(import("ws").WebSocket & { send: import("ws").WebSocket["send"], terminate: import("ws").WebSocket["terminate"], ping: import("ws").WebSocket["ping"] }) & { isAlive?: boolean }} ClientConnection
*/
/**
* @typedef {import("ws").WebSocketServer & { close: import("ws").WebSocketServer["close"] }} WebSocketServer
*/
/**
* @typedef {{ implementation: WebSocketServer, clients: ClientConnection[] }} WebSocketServerImplementation
*/
/**
* A client the hot endpoint handed over, of either transport: a WebSocket, or
* the event stream's response. Neither one's write or close method exists on
* the other, which is why anything handling both goes through the middleware
* or asks before calling.
* @typedef {ClientConnection | ServerResponse} HotClient
*/
/**
* @typedef {{ path?: HttpProxyMiddlewareOptionsFilter | undefined, context?: HttpProxyMiddlewareOptionsFilter | undefined } & HttpProxyMiddlewareOptions} ProxyConfigArrayItem
*/
/**
* @typedef {(ProxyConfigArrayItem | ((req?: Request | undefined, res?: Response | undefined, next?: NextFunction | undefined) => ProxyConfigArrayItem))[]} ProxyConfigArray
*/
/**
* @typedef {object} OpenApp
* @property {string=} name
* @property {string[]=} arguments
*/
/**
* @typedef {object} Open
* @property {(string | string[] | OpenApp)=} app
* @property {(string | string[])=} target target
*/
/**
* @typedef {object} NormalizedOpen
* @property {string} target
* @property {import("open").Options} options
*/
/**
* @typedef {object} WebSocketURL
* @property {string=} hostname hostname
* @property {string=} password password
* @property {string=} pathname pathname
* @property {(number | string)=} port port
* @property {string=} protocol protocol
* @property {string=} username username
*/
/**
* @typedef {boolean | ((error: Error) => void)} OverlayMessageOptions
*/
/**
* @typedef {object} ClientConfiguration
* @property {"log" | "info" | "warn" | "error" | "none" | "verbose"=} logging logging
* @property {(boolean | { warnings?: OverlayMessageOptions, errors?: OverlayMessageOptions, runtimeErrors?: OverlayMessageOptions, trustedTypesPolicyName?: string })=} overlay overlay
* @property {(boolean | "linear" | "circular")=} progress progress
* @property {(boolean | number)=} reconnect reconnect
* @property {("ws" | string)=} webSocketTransport web socket transport
* @property {(string | WebSocketURL)=} webSocketURL web socket URL
*/
/**
* @typedef {{ key: string, value: string }[] | Record<string, string | string[]>} Headers
*/
/**
* @template {BasicApplication} [T=ExpressApplication]
* @typedef {T extends ExpressApplication ? ExpressRequestHandler | ExpressErrorRequestHandler : HandleFunction} MiddlewareHandler
*/
/**
* @typedef {{ name?: string, path?: string, middleware: MiddlewareHandler }} MiddlewareObject
*/
/**
* @typedef {MiddlewareObject | MiddlewareHandler} Middleware
*/
/** @typedef {import("net").Server | import("tls").Server} BasicServer */
/**
* @template {BasicApplication} [A=ExpressApplication]
* @template {BasicServer} [S=import("http").Server]
* @typedef {object} Configuration
* @property {(boolean | string)=} ipc
* @property {Host=} host
* @property {Port=} port
* @property {(boolean | "only")=} hot
* @property {boolean=} liveReload
* @property {DevMiddlewareOptions<Request, Response>=} devMiddleware
* @property {boolean=} compress
* @property {("auto" | "all" | string | string[])=} allowedHosts
* @property {(boolean | ConnectHistoryApiFallbackOptions)=} historyApiFallback
* @property {(boolean | Record<string, never> | BonjourOptions)=} bonjour
* @property {(string | string[] | WatchFiles | (string | WatchFiles)[])=} watchFiles
* @property {(boolean | string | Static | (string | Static)[])=} static
* @property {(ServerType<A, S> | ServerConfiguration<A, S>)=} server
* @property {(() => Promise<A>)=} app
* @property {(boolean | "ws" | string | WebSocketServerConfiguration)=} webSocketServer
* @property {ProxyConfigArray=} proxy
* @property {(boolean | string | Open | (string | Open)[])=} open
* @property {boolean=} setupExitSignals
* @property {(boolean | ClientConfiguration)=} client
* @property {(Headers | ((req: Request, res: Response, context: DevMiddlewareContext<Request, Response> | undefined) => Headers))=} headers
* @property {((devServer: Server<A, S>) => void)=} onListening
* @property {((middlewares: Middleware[], devServer: Server<A, S>) => Middleware[])=} setupMiddlewares
*/
if (!process.env.WEBPACK_SERVE) {
process.env.WEBPACK_SERVE = "true";
}
/**
* @template T
* @typedef {() => T} FunctionReturning
*/
/**
* @template T
* @param {FunctionReturning<T>} fn memorized function
* @returns {FunctionReturning<T>} new function
*/
const memoize = (fn) => {
let cache = false;
/** @type {T | undefined} */
let result;
return () => {
if (cache) {
return /** @type {T} */ (result);
}
result = fn();
cache = true;
// Allow to clean up memory for fn
// and all dependent resources
/** @type {FunctionReturning<T> | undefined} */
(fn) = undefined;
return /** @type {T} */ (result);
};
};
const getExpress = memoize(async () => (await import("express")).default);
/**
* @param {OverlayMessageOptions=} setting overlay settings
* @returns {undefined | string | boolean} encoded overlay settings
*/
const encodeOverlaySettings = (setting) =>
typeof setting === "function"
? encodeURIComponent(setting.toString())
: setting;
// TODO remove these three in the next major release, along with what they
// stand behind.
const deprecatedClientEntry = util.deprecate(
() => cjsRequire.resolve("../client/index.js"),
"'getClientEntry()' is deprecated and will be removed in the next major release. webpack-dev-middleware adds the client to the compilation itself; list 'webpack-dev-server/client/index.js' in 'entry' if you need it by hand.",
"DEP_WEBPACK_DEV_SERVER_GET_CLIENT_ENTRY",
);
const deprecatedClientHotEntry = util.deprecate(
/**
* @param {boolean | "only" | undefined} hot the `hot` option
* @returns {string | void} the hot entry
*/
(hot) => {
if (hot === "only") {
return cjsRequire.resolve("webpack/hot/only-dev-server");
} else if (hot) {
return cjsRequire.resolve("webpack/hot/dev-server");
}
},
"'getClientHotEntry()' is deprecated and will be removed in the next major release. webpack-dev-middleware applies updates itself, without a 'webpack/hot' entry.",
"DEP_WEBPACK_DEV_SERVER_GET_CLIENT_HOT_ENTRY",
);
const warnSendMessageDeprecated = util.deprecate(
() => {},
"'sendMessage()' is deprecated and will be removed in the next major release. Use the middleware's 'publish(payload)' or 'publishTo(client, payload)' instead: 'devServer.middleware.publish({ action: \"reload\" })' reloads every page.",
"DEP_WEBPACK_DEV_SERVER_SEND_MESSAGE",
);
// Working for overload, because typescript doesn't support this yes
/**
* @overload
* @param {NextHandleFunction} fn function
* @returns {BasicApplication} application
*/
/**
* @overload
* @param {HandleFunction} fn function
* @returns {BasicApplication} application
*/
/**
* @overload
* @param {string} route route
* @param {NextHandleFunction} fn function
* @returns {BasicApplication} application
*/
/**
* @param {string} route route
* @param {HandleFunction} fn function
* @returns {BasicApplication} application
*/
// eslint-disable-next-line no-unused-vars
function useFn(route, fn) {
return /** @type {BasicApplication} */ ({});
}
const DEFAULT_ALLOWED_PROTOCOLS = /^(file|.+-extension):/i;
/**
* @typedef {object} BasicApplication
* @property {typeof useFn} use
*/
const pluginName = "webpack-dev-server";
/**
* @template {BasicApplication} [A=ExpressApplication]
* @template {BasicServer} [S=HTTPServer]
*/
class Server {
/**
* What `webSocketServer` is while the socket is the middleware's: the
* clients the hot endpoint let through, and an emitter for each that joins.
* @type {{ implementation: EventEmitter, clients: ClientConnection[] } | undefined}
*/
#webSocketServerFacade;
/**
* @param {Configuration<A, S> | undefined} options options
* @param {(Compiler | MultiCompiler)=} compiler compiler, omitted when the server is used as a plugin via `apply()`
*/
constructor(options, compiler) {
options = options === undefined ? {} : options;
if (compiler) {
Server.validateOptions(compiler, options);
this.compiler = compiler;
/**
* @type {ReturnType<Compiler["getInfrastructureLogger"]>}
*/
this.logger = this.compiler.getInfrastructureLogger(pluginName);
}
this.options = options;
/**
* @type {FSWatcher[]}
*/
this.staticWatchers = [];
/**
* @private
* @type {{ name: string | symbol, listener: (...args: EXPECTED_ANY[]) => void }[]} }
*/
this.listeners = [];
// Keep track of websocket proxies for external websocket upgrade.
/**
* @private
* @type {(() => RequestHandler | undefined)[]}
*/
this.webSocketProxies = [];
/**
* @type {Socket[]}
*/
this.sockets = [];
/**
* @private
* @type {string | undefined}
*/
this.currentHash = undefined;
/**
* @private
* @type {boolean}
*/
this.isPlugin = false;
}
static get schema() {
return schema;
}
/**
* @private
* @returns {StatsOptions} default stats options
*/
static get DEFAULT_STATS() {
return {
all: false,
hash: true,
warnings: true,
errors: true,
errorDetails: false,
};
}
/**
* @param {string} URL url
* @returns {boolean} true when URL is absolute, otherwise false
*/
static isAbsoluteURL(URL) {
// Don't match Windows paths `c:\`
if (/^[a-zA-Z]:\\/.test(URL)) {
return false;
}
// Scheme: https://tools.ietf.org/html/rfc3986#section-3.1
// Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3
return /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(URL);
}
/**
* @param {string} gatewayOrFamily gateway or family
* @param {boolean=} isInternal ip should be internal
* @returns {string | undefined} resolved IP
*/
static findIp(gatewayOrFamily, isInternal) {
if (gatewayOrFamily === "v4" || gatewayOrFamily === "v6") {
for (const networks of Object.values(os.networkInterfaces())) {
for (const network of networks ?? []) {
if (!network || !network.address) {
continue;
}
if (network.family !== `IP${gatewayOrFamily}`) {
continue;
}
if (
typeof isInternal !== "undefined" &&
network.internal !== isInternal
) {
continue;
}
if (gatewayOrFamily === "v6") {
const range = ipaddr.parse(network.address).range();
if (
range !== "ipv4Mapped" &&
range !== "uniqueLocal" &&
range !== "loopback"
) {
continue;
}
}
return network.address.includes(":")
? `[${network.address}]`
: network.address;
}
}
return undefined;
}
const gatewayIp = ipaddr.parse(gatewayOrFamily);
// Look for the matching interface in all local interfaces.
for (const addresses of Object.values(os.networkInterfaces())) {
for (const network of addresses ?? []) {
if (!network?.cidr) {
continue;
}
const net = ipaddr.parseCIDR(network.cidr);
if (
net[0] &&
net[0].kind() === gatewayIp.kind() &&
// eslint-disable-next-line unicorn/prefer-regexp-test
gatewayIp.match(net)
) {
return net[0].toString();
}
}
}
}
/**
* @param {Host} hostname hostname
* @returns {Promise<string>} resolved hostname
*/
static async getHostname(hostname) {
if (hostname === "local-ip") {
return (
Server.findIp("v4", false) ||
Server.findIp("v6", false)?.slice(1, -1) ||
"0.0.0.0"
);
} else if (hostname === "local-ipv4") {
return Server.findIp("v4", false) || "0.0.0.0";
} else if (hostname === "local-ipv6") {
return Server.findIp("v6", false)?.slice(1, -1) || "::";
}
return hostname;
}
/**
* @param {Port} port port
* @param {string} host host
* @returns {Promise<number | string>} free port
*/
static async getFreePort(port, host) {
if (typeof port !== "undefined" && port !== null && port !== "auto") {
return port;
}
const { default: pRetry } = await import("p-retry");
const { default: getPort } = await import("./getPort.js");
const basePort =
typeof process.env.WEBPACK_DEV_SERVER_BASE_PORT !== "undefined"
? Number.parseInt(process.env.WEBPACK_DEV_SERVER_BASE_PORT, 10)
: 8080;
// Try to find unused port and listen on it for 3 times,
// if port is not specified in options.
const defaultPortRetry =
typeof process.env.WEBPACK_DEV_SERVER_PORT_RETRY !== "undefined"
? Number.parseInt(process.env.WEBPACK_DEV_SERVER_PORT_RETRY, 10)
: 3;
return pRetry(() => getPort(basePort, host), {
retries: defaultPortRetry,
});
}
/**
* @returns {string} path to cache dir
*/
static findCacheDir() {
const cwd = process.cwd();
/**
* @type {string | undefined}
*/
let dir = cwd;
for (;;) {
try {
if (fs.statSync(path.join(dir, "package.json")).isFile()) break;
// eslint-disable-next-line no-empty
} catch {}
const parent = path.dirname(dir);
if (dir === parent) {
dir = undefined;
break;
}
dir = parent;
}
if (!dir) {
return path.resolve(cwd, `.cache/${pluginName}`);
} else if (process.versions.pnp === "1") {
return path.resolve(dir, `.pnp/.cache/${pluginName}`);
} else if (process.versions.pnp === "3") {
return path.resolve(dir, `.yarn/.cache/${pluginName}`);
}
return path.resolve(dir, `node_modules/.cache/${pluginName}`);
}
/**
* The compiler whose configuration the dev server belongs to. For a
* `MultiCompiler` that is the child naming `devServer`, else the one
* targeting the web, else the first — anything else reads another child's
* settings.
* @private
* @param {Compiler | MultiCompiler} compiler compiler
* @returns {Compiler} the compiler that owns the dev server
*/
static findDevServerCompiler(compiler) {
const { compilers } = /** @type {MultiCompiler} */ (compiler);
if (typeof compilers === "undefined") {
return /** @type {Compiler} */ (compiler);
}
if (compilers.length === 1) {
return compilers[0];
}
return (
compilers.find((child) => child.options.devServer) ||
compilers.find((child) => Server.isWebTarget(child)) ||
compilers[0]
);
}
/**
* Throw unless the options match the schema.
*
* `compiler.hooks.validate` and `compiler.validate`'s lazy-schema and
* precompiled-check parameters landed together in webpack 5.106, so the hook
* doubles as the feature probe for them. Validating through the compiler that
* owns the dev server matters: `compiler.validate` honours that compiler's
* `validate` option, so asking any other child would read a policy that was
* never about these options. Either way the schema is only read, and ajv only
* compiled, once something is actually wrong — the precompiled validator
* answers the common case in ~1ms, against the ~120ms `schema-utils` spends
* compiling the schema on its first call.
* @private
* @param {Compiler | MultiCompiler} compiler compiler that owns the dev server
* @param {EXPECTED_ANY} options options
* @returns {void}
*/
static validateOptions(compiler, options) {
const owner = Server.findDevServerCompiler(compiler);
if (owner.hooks.validate) {
/** @type {EXPECTED_ANY} */
(owner).validate(
() => schema,
options,
{ name: "Dev Server", baseDataPath: "options" },
schemaCheck,
);
return;
}
// TODO remove this fallback in the next major, once the minimum supported
// webpack has `compiler.hooks.validate`, and validate through the compiler
// alone.
if (!schemaCheck(options)) {
validate(/** @type {Schema} */ (schema), options, {
name: "Dev Server",
baseDataPath: "options",
});
}
}
/**
* @private
* @param {Compiler} compiler compiler
* @returns {boolean} true when target is `web` or `universal`, otherwise false
*/
static isWebTarget(compiler) {
const { platform } = compiler;
// A `web` or universal target (`web` and `node` both `null`) injects the
// client. `target: false` is `null` everywhere, so it is excluded.
return Boolean(
platform.web ||
/** @type {{ universal?: boolean | null }} */ (platform)?.universal ||
(compiler.options.target !== false &&
platform.web === null &&
platform.node === null),
);
}
/**
* @private
* @returns {Compiler["options"]} compiler options
*/
getCompilerOptions() {
return Server.findDevServerCompiler(
/** @type {Compiler | MultiCompiler} */ (this.compiler),
).options;
}
/**
* @private
* @returns {Promise<void>}
*/
async normalizeOptions() {
const { options } = this;
const compilerOptions = this.getCompilerOptions();
const compilerWatchOptions = compilerOptions.watchOptions;
/**
* @param {WatchOptions & { aggregateTimeout?: number, ignored?: WatchOptions["ignored"], poll?: number | boolean }} watchOptions watch options
* @returns {WatchOptions} normalized watch options
*/
const getWatchOptions = (watchOptions = {}) => {
const getPolling = () => {
if (typeof watchOptions.usePolling !== "undefined") {
return watchOptions.usePolling;
}
if (typeof watchOptions.poll !== "undefined") {
return Boolean(watchOptions.poll);
}
if (typeof compilerWatchOptions.poll !== "undefined") {
return Boolean(compilerWatchOptions.poll);
}
return false;
};
const getInterval = () => {
if (typeof watchOptions.interval !== "undefined") {
return watchOptions.interval;
}
if (typeof watchOptions.poll === "number") {
return watchOptions.poll;
}
if (typeof compilerWatchOptions.poll === "number") {
return compilerWatchOptions.poll;
}
};
const usePolling = getPolling();
const interval = getInterval();
const { poll: _poll, interval: _interval, ...rest } = watchOptions;
return {
ignoreInitial: true,
persistent: true,
followSymlinks: false,
atomic: false,
alwaysStat: true,
ignorePermissionErrors: true,
// Respect options from compiler watchOptions
usePolling,
...(interval !== undefined ? { interval } : {}),
...rest,
};
};
/**
* @param {(string | Static | undefined)=} optionsForStatic for static
* @returns {NormalizedStatic} normalized options for static
*/
const getStaticItem = (optionsForStatic) => {
const getDefaultStaticOptions = () => ({
directory: path.join(process.cwd(), "public"),
staticOptions: {},
publicPath: ["/"],
serveIndex: { icons: true },
watch: getWatchOptions(),
});
/** @type {NormalizedStatic} */
let item;
if (typeof optionsForStatic === "undefined") {
item = getDefaultStaticOptions();
} else if (typeof optionsForStatic === "string") {
item = {
...getDefaultStaticOptions(),
directory: optionsForStatic,
};
} else {
const def = getDefaultStaticOptions();
item = {
directory:
typeof optionsForStatic.directory !== "undefined"
? optionsForStatic.directory
: def.directory,
staticOptions:
typeof optionsForStatic.staticOptions !== "undefined"
? { ...def.staticOptions, ...optionsForStatic.staticOptions }
: def.staticOptions,
publicPath:
typeof optionsForStatic.publicPath !== "undefined"
? Array.isArray(optionsForStatic.publicPath)
? optionsForStatic.publicPath
: [optionsForStatic.publicPath]
: def.publicPath,
serveIndex:
// Check if 'serveIndex' property is defined in 'optionsForStatic'
// If 'serveIndex' is a boolean and true, use default 'serveIndex'
// If 'serveIndex' is an object, merge its properties with default 'serveIndex'
// If 'serveIndex' is neither a boolean true nor an object, use it as-is
// If 'serveIndex' is not defined in 'optionsForStatic', use default 'serveIndex'
typeof optionsForStatic.serveIndex !== "undefined"
? typeof optionsForStatic.serveIndex === "boolean" &&
optionsForStatic.serveIndex
? def.serveIndex
: typeof optionsForStatic.serveIndex === "object"
? { ...def.serveIndex, ...optionsForStatic.serveIndex }
: optionsForStatic.serveIndex
: def.serveIndex,
watch:
typeof optionsForStatic.watch !== "undefined"
? typeof optionsForStatic.watch === "boolean"
? optionsForStatic.watch
? def.watch
: false
: getWatchOptions(optionsForStatic.watch)
: def.watch,
};
}
if (Server.isAbsoluteURL(item.directory)) {
throw new Error("Using a URL as static.directory is not supported");
}
return item;
};
if (typeof options.allowedHosts === "undefined") {
// AllowedHosts allows some default hosts picked from `options.host` or `webSocketURL.hostname` and `localhost`
options.allowedHosts = "auto";
}
// We store allowedHosts as array when supplied as string
else if (
typeof options.allowedHosts === "string" &&
options.allowedHosts !== "auto" &&
options.allowedHosts !== "all"
) {
options.allowedHosts = [options.allowedHosts];
}
// CLI pass options as array, we should normalize them
else if (
Array.isArray(options.allowedHosts) &&
options.allowedHosts.includes("all")
) {
options.allowedHosts = "all";
}
if (typeof options.bonjour === "undefined") {
options.bonjour = false;
} else if (typeof options.bonjour === "boolean") {
options.bonjour = options.bonjour ? {} : false;
}
if (
typeof options.client === "undefined" ||
(typeof options.client === "object" && options.client !== null)
) {
if (!options.client) {
options.client = {};
}
if (typeof options.client.webSocketURL === "undefined") {
options.client.webSocketURL = {};
} else if (typeof options.client.webSocketURL === "string") {
const parsedURL = new URL(options.client.webSocketURL);
options.client.webSocketURL = {
protocol: parsedURL.protocol,
hostname: parsedURL.hostname,
port: parsedURL.port.length > 0 ? Number(parsedURL.port) : "",
pathname: parsedURL.pathname,
username: parsedURL.username,
password: parsedURL.password,
};
} else if (typeof options.client.webSocketURL.port === "string") {
options.client.webSocketURL.port = Number(
options.client.webSocketURL.port,
);
}
// Enable client overlay by default
if (typeof options.client.overlay === "undefined") {
options.client.overlay = true;
} else if (typeof options.client.overlay !== "boolean") {
options.client.overlay = {
errors: true,
warnings: true,
...options.client.overlay,
};
}
if (typeof options.client.reconnect === "undefined") {
options.client.reconnect = 10;
} else if (options.client.reconnect === true) {
options.client.reconnect = Infinity;
} else if (options.client.reconnect === false) {
options.client.reconnect = 0;
}
// Respect infrastructureLogging.level
if (typeof options.client.logging === "undefined") {
options.client.logging = compilerOptions.infrastructureLogging
? compilerOptions.infrastructureLogging.level
: "info";
}
}
if (typeof options.compress === "undefined") {
options.compress = true;
}
if (typeof options.devMiddleware === "undefined") {
options.devMiddleware = {};
}
// No need to normalize `headers`
if (typeof options.historyApiFallback === "undefined") {
options.historyApiFallback = false;
} else if (
typeof options.historyApiFallback === "boolean" &&
options.historyApiFallback
) {
options.historyApiFallback = {};
}
// No need to normalize `host`
options.hot =
typeof options.hot === "boolean" || options.hot === "only"
? options.hot
: true;
if (
typeof options.server === "function" ||
typeof options.server === "string"
) {
options.server = {
type: options.server,
options: {},
};
} else {
const serverOptions =
/** @type {ServerConfiguration<A, S>} */
(options.server || {});
options.server = {
type: serverOptions.type || "http",
options: { ...serverOptions.options },
};
}
const serverOptions = /** @type {ServerOptions} */ (options.server.options);
if (options.server.type === "https" || options.server.type === "http2") {
if (typeof serverOptions.requestCert === "undefined") {
serverOptions.requestCert = false;
}
const httpsProperties =
/** @type {(keyof ServerOptions)[]} */
(["ca", "cert", "crl", "key", "pfx"]);
for (const property_ of httpsProperties) {
const property = /** @type {keyof ServerOptions} */ (property_);
if (typeof serverOptions[property] === "undefined") {
continue;
}