@rspack/dev-server 2.0.0-beta.6 → 2.0.0-rc.0

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.
package/dist/831.js ADDED
@@ -0,0 +1,2641 @@
1
+ import { createRequire } from "node:module";
2
+ import { devMiddleware } from "@rspack/dev-middleware";
3
+ import { createRequire as __rspack_createRequire } from "node:module";
4
+ const __rspack_createRequire_require = __rspack_createRequire(import.meta.url);
5
+ import * as __rspack_external_node_fs_5ea92f0c from "node:fs";
6
+ import * as __rspack_external_node_os_74b4b876 from "node:os";
7
+ import * as __rspack_external_node_path_c5b9b54f from "node:path";
8
+ import * as __rspack_external_node_url_e96de089 from "node:url";
9
+ import * as __rspack_external_node_util_1b29d436 from "node:util";
10
+ import * as __rspack_external_node_net_0373943e from "node:net";
11
+ import * as __rspack_external_ws from "ws";
12
+ var __webpack_modules__ = {};
13
+ var __webpack_module_cache__ = {};
14
+ function __webpack_require__(moduleId) {
15
+ var cachedModule = __webpack_module_cache__[moduleId];
16
+ if (void 0 !== cachedModule) return cachedModule.exports;
17
+ var module = __webpack_module_cache__[moduleId] = {
18
+ exports: {}
19
+ };
20
+ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
21
+ return module.exports;
22
+ }
23
+ __webpack_require__.m = __webpack_modules__;
24
+ (()=>{
25
+ __webpack_require__.n = (module)=>{
26
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
27
+ __webpack_require__.d(getter, {
28
+ a: getter
29
+ });
30
+ return getter;
31
+ };
32
+ })();
33
+ (()=>{
34
+ var getProto = Object.getPrototypeOf ? (obj)=>Object.getPrototypeOf(obj) : (obj)=>obj.__proto__;
35
+ var leafPrototypes;
36
+ __webpack_require__.t = function(value, mode) {
37
+ if (1 & mode) value = this(value);
38
+ if (8 & mode) return value;
39
+ if ('object' == typeof value && value) {
40
+ if (4 & mode && value.__esModule) return value;
41
+ if (16 & mode && 'function' == typeof value.then) return value;
42
+ }
43
+ var ns = Object.create(null);
44
+ __webpack_require__.r(ns);
45
+ var def = {};
46
+ leafPrototypes = leafPrototypes || [
47
+ null,
48
+ getProto({}),
49
+ getProto([]),
50
+ getProto(getProto)
51
+ ];
52
+ for(var current = 2 & mode && value; ('object' == typeof current || 'function' == typeof current) && !~leafPrototypes.indexOf(current); current = getProto(current))Object.getOwnPropertyNames(current).forEach((key)=>{
53
+ def[key] = ()=>value[key];
54
+ });
55
+ def['default'] = ()=>value;
56
+ __webpack_require__.d(ns, def);
57
+ return ns;
58
+ };
59
+ })();
60
+ (()=>{
61
+ __webpack_require__.d = (exports, definition)=>{
62
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
63
+ enumerable: true,
64
+ get: definition[key]
65
+ });
66
+ };
67
+ })();
68
+ (()=>{
69
+ __webpack_require__.add = function(modules) {
70
+ Object.assign(__webpack_require__.m, modules);
71
+ };
72
+ })();
73
+ var __webpack_require__temp = __webpack_require__;
74
+ (()=>{
75
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
76
+ })();
77
+ (()=>{
78
+ __webpack_require__.r = (exports)=>{
79
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports, Symbol.toStringTag, {
80
+ value: 'Module'
81
+ });
82
+ Object.defineProperty(exports, '__esModule', {
83
+ value: true
84
+ });
85
+ };
86
+ })();
87
+ (()=>{
88
+ var installedChunks = {
89
+ 410: 0,
90
+ 831: 0
91
+ };
92
+ var installChunk = (data)=>{
93
+ var __rspack_esm_ids = data.__rspack_esm_ids;
94
+ var __webpack_modules__ = data.__webpack_modules__;
95
+ var __rspack_esm_runtime = data.__rspack_esm_runtime;
96
+ var moduleId, chunkId, i = 0;
97
+ for(moduleId in __webpack_modules__)if (__webpack_require__.o(__webpack_modules__, moduleId)) __webpack_require__.m[moduleId] = __webpack_modules__[moduleId];
98
+ if (__rspack_esm_runtime) __rspack_esm_runtime(__webpack_require__);
99
+ for(; i < __rspack_esm_ids.length; i++){
100
+ chunkId = __rspack_esm_ids[i];
101
+ if (__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) installedChunks[chunkId][0]();
102
+ installedChunks[__rspack_esm_ids[i]] = 0;
103
+ }
104
+ };
105
+ __webpack_require__.C = installChunk;
106
+ })();
107
+ __webpack_require__.add({
108
+ "./node_modules/.pnpm/http-compression@1.1.2/node_modules/http-compression/src/index.js" (module, __unused_rspack_exports, __webpack_require__) {
109
+ const zlib = __webpack_require__("zlib");
110
+ const MIMES = /text|javascript|\/json|xml/i;
111
+ const noop = ()=>{};
112
+ const getChunkSize = (chunk, enc)=>chunk ? Buffer.byteLength(chunk, enc) : 0;
113
+ module.exports = ({ threshold = 1024, level = {
114
+ brotli: 0,
115
+ gzip: 1
116
+ }, brotli = true, gzip = true, mimes = MIMES } = {})=>{
117
+ const brotliOpts = 'object' == typeof brotli && brotli || {};
118
+ const gzipOpts = 'object' == typeof gzip && gzip || {};
119
+ if (brotli && !zlib.createBrotliCompress) brotli = false;
120
+ return (req, res, next = noop)=>{
121
+ const accept = req.headers['accept-encoding'];
122
+ const encoding = accept && (brotli && accept.match(/\bbr\b/) || gzip && accept.match(/\bgzip\b/) || [])[0];
123
+ if ('HEAD' === req.method || !encoding) return next();
124
+ let compress;
125
+ let pendingStatus;
126
+ let pendingListeners = [];
127
+ let started = false;
128
+ let size = 0;
129
+ function start() {
130
+ started = true;
131
+ size = 0 | res.getHeader('Content-Length') || size;
132
+ const compressible = mimes.test(String(res.getHeader('Content-Type') || 'text/plain'));
133
+ const cleartext = !res.getHeader('Content-Encoding');
134
+ const listeners = pendingListeners || [];
135
+ if (compressible && cleartext && size >= threshold) {
136
+ res.setHeader('Content-Encoding', encoding);
137
+ res.removeHeader('Content-Length');
138
+ compress = 'br' === encoding ? zlib.createBrotliCompress({
139
+ params: Object.assign({
140
+ [zlib.constants.BROTLI_PARAM_QUALITY]: level.brotli,
141
+ [zlib.constants.BROTLI_PARAM_SIZE_HINT]: size
142
+ }, brotliOpts)
143
+ }) : zlib.createGzip(Object.assign({
144
+ level: level.gzip
145
+ }, gzipOpts));
146
+ compress.on('data', (chunk)=>false === write.call(res, chunk) && compress.pause());
147
+ on.call(res, 'drain', ()=>compress.resume());
148
+ compress.on('end', ()=>end.call(res));
149
+ listeners.forEach((p)=>compress.on.apply(compress, p));
150
+ } else {
151
+ pendingListeners = null;
152
+ listeners.forEach((p)=>on.apply(res, p));
153
+ }
154
+ writeHead.call(res, pendingStatus || res.statusCode);
155
+ }
156
+ const { end, write, on, writeHead } = res;
157
+ res.writeHead = function(status, reason, headers) {
158
+ if ('string' != typeof reason) [headers, reason] = [
159
+ reason,
160
+ headers
161
+ ];
162
+ if (headers) for(const i in headers)res.setHeader(i, headers[i]);
163
+ pendingStatus = status;
164
+ return this;
165
+ };
166
+ res.write = function(chunk, enc) {
167
+ size += getChunkSize(chunk, enc);
168
+ if (!started) start();
169
+ if (!compress) return write.apply(this, arguments);
170
+ return compress.write.apply(compress, arguments);
171
+ };
172
+ res.end = function(chunk, enc) {
173
+ if (arguments.length > 0 && 'function' != typeof chunk) size += getChunkSize(chunk, enc);
174
+ if (!started) start();
175
+ if (!compress) return end.apply(this, arguments);
176
+ return compress.end.apply(compress, arguments);
177
+ };
178
+ res.on = function(type, listener) {
179
+ if (pendingListeners && 'drain' === type) if (compress) compress.on(type, listener);
180
+ else pendingListeners.push([
181
+ type,
182
+ listener
183
+ ]);
184
+ else on.call(this, type, listener);
185
+ return this;
186
+ };
187
+ next();
188
+ };
189
+ };
190
+ },
191
+ "./node_modules/.pnpm/ipaddr.js@2.3.0/node_modules/ipaddr.js/lib/ipaddr.js" (module) {
192
+ (function(root) {
193
+ 'use strict';
194
+ const ipv4Part = '(0?\\d+|0x[a-f0-9]+)';
195
+ const ipv4Regexes = {
196
+ fourOctet: new RegExp(`^${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}$`, 'i'),
197
+ threeOctet: new RegExp(`^${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}$`, 'i'),
198
+ twoOctet: new RegExp(`^${ipv4Part}\\.${ipv4Part}$`, 'i'),
199
+ longValue: new RegExp(`^${ipv4Part}$`, 'i')
200
+ };
201
+ const octalRegex = new RegExp("^0[0-7]+$", 'i');
202
+ const hexRegex = new RegExp("^0x[a-f0-9]+$", 'i');
203
+ const zoneIndex = '%[0-9a-z]{1,}';
204
+ const ipv6Part = '(?:[0-9a-f]+::?)+';
205
+ const ipv6Regexes = {
206
+ zoneIndex: new RegExp(zoneIndex, 'i'),
207
+ native: new RegExp(`^(::)?(${ipv6Part})?([0-9a-f]+)?(::)?(${zoneIndex})?$`, 'i'),
208
+ deprecatedTransitional: new RegExp(`^(?:::)(${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}(${zoneIndex})?)$`, 'i'),
209
+ transitional: new RegExp(`^((?:${ipv6Part})|(?:::)(?:${ipv6Part})?)${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}(${zoneIndex})?$`, 'i')
210
+ };
211
+ function expandIPv6(string, parts) {
212
+ if (string.indexOf('::') !== string.lastIndexOf('::')) return null;
213
+ let colonCount = 0;
214
+ let lastColon = -1;
215
+ let zoneId = (string.match(ipv6Regexes.zoneIndex) || [])[0];
216
+ let replacement, replacementCount;
217
+ if (zoneId) {
218
+ zoneId = zoneId.substring(1);
219
+ string = string.replace(/%.+$/, '');
220
+ }
221
+ while((lastColon = string.indexOf(':', lastColon + 1)) >= 0)colonCount++;
222
+ if ('::' === string.substr(0, 2)) colonCount--;
223
+ if ('::' === string.substr(-2, 2)) colonCount--;
224
+ if (colonCount > parts) return null;
225
+ replacementCount = parts - colonCount;
226
+ replacement = ':';
227
+ while(replacementCount--)replacement += '0:';
228
+ string = string.replace('::', replacement);
229
+ if (':' === string[0]) string = string.slice(1);
230
+ if (':' === string[string.length - 1]) string = string.slice(0, -1);
231
+ parts = function() {
232
+ const ref = string.split(':');
233
+ const results = [];
234
+ for(let i = 0; i < ref.length; i++)results.push(parseInt(ref[i], 16));
235
+ return results;
236
+ }();
237
+ return {
238
+ parts: parts,
239
+ zoneId: zoneId
240
+ };
241
+ }
242
+ function matchCIDR(first, second, partSize, cidrBits) {
243
+ if (first.length !== second.length) throw new Error('ipaddr: cannot match CIDR for objects with different lengths');
244
+ let part = 0;
245
+ let shift;
246
+ while(cidrBits > 0){
247
+ shift = partSize - cidrBits;
248
+ if (shift < 0) shift = 0;
249
+ if (first[part] >> shift !== second[part] >> shift) return false;
250
+ cidrBits -= partSize;
251
+ part += 1;
252
+ }
253
+ return true;
254
+ }
255
+ function parseIntAuto(string) {
256
+ if (hexRegex.test(string)) return parseInt(string, 16);
257
+ if ('0' === string[0] && !isNaN(parseInt(string[1], 10))) {
258
+ if (octalRegex.test(string)) return parseInt(string, 8);
259
+ throw new Error(`ipaddr: cannot parse ${string} as octal`);
260
+ }
261
+ return parseInt(string, 10);
262
+ }
263
+ function padPart(part, length) {
264
+ while(part.length < length)part = `0${part}`;
265
+ return part;
266
+ }
267
+ const ipaddr = {};
268
+ ipaddr.IPv4 = function() {
269
+ function IPv4(octets) {
270
+ if (4 !== octets.length) throw new Error('ipaddr: ipv4 octet count should be 4');
271
+ let i, octet;
272
+ for(i = 0; i < octets.length; i++){
273
+ octet = octets[i];
274
+ if (!(0 <= octet && octet <= 255)) throw new Error('ipaddr: ipv4 octet should fit in 8 bits');
275
+ }
276
+ this.octets = octets;
277
+ }
278
+ IPv4.prototype.SpecialRanges = {
279
+ unspecified: [
280
+ [
281
+ new IPv4([
282
+ 0,
283
+ 0,
284
+ 0,
285
+ 0
286
+ ]),
287
+ 8
288
+ ]
289
+ ],
290
+ broadcast: [
291
+ [
292
+ new IPv4([
293
+ 255,
294
+ 255,
295
+ 255,
296
+ 255
297
+ ]),
298
+ 32
299
+ ]
300
+ ],
301
+ multicast: [
302
+ [
303
+ new IPv4([
304
+ 224,
305
+ 0,
306
+ 0,
307
+ 0
308
+ ]),
309
+ 4
310
+ ]
311
+ ],
312
+ linkLocal: [
313
+ [
314
+ new IPv4([
315
+ 169,
316
+ 254,
317
+ 0,
318
+ 0
319
+ ]),
320
+ 16
321
+ ]
322
+ ],
323
+ loopback: [
324
+ [
325
+ new IPv4([
326
+ 127,
327
+ 0,
328
+ 0,
329
+ 0
330
+ ]),
331
+ 8
332
+ ]
333
+ ],
334
+ carrierGradeNat: [
335
+ [
336
+ new IPv4([
337
+ 100,
338
+ 64,
339
+ 0,
340
+ 0
341
+ ]),
342
+ 10
343
+ ]
344
+ ],
345
+ private: [
346
+ [
347
+ new IPv4([
348
+ 10,
349
+ 0,
350
+ 0,
351
+ 0
352
+ ]),
353
+ 8
354
+ ],
355
+ [
356
+ new IPv4([
357
+ 172,
358
+ 16,
359
+ 0,
360
+ 0
361
+ ]),
362
+ 12
363
+ ],
364
+ [
365
+ new IPv4([
366
+ 192,
367
+ 168,
368
+ 0,
369
+ 0
370
+ ]),
371
+ 16
372
+ ]
373
+ ],
374
+ reserved: [
375
+ [
376
+ new IPv4([
377
+ 192,
378
+ 0,
379
+ 0,
380
+ 0
381
+ ]),
382
+ 24
383
+ ],
384
+ [
385
+ new IPv4([
386
+ 192,
387
+ 0,
388
+ 2,
389
+ 0
390
+ ]),
391
+ 24
392
+ ],
393
+ [
394
+ new IPv4([
395
+ 192,
396
+ 88,
397
+ 99,
398
+ 0
399
+ ]),
400
+ 24
401
+ ],
402
+ [
403
+ new IPv4([
404
+ 198,
405
+ 18,
406
+ 0,
407
+ 0
408
+ ]),
409
+ 15
410
+ ],
411
+ [
412
+ new IPv4([
413
+ 198,
414
+ 51,
415
+ 100,
416
+ 0
417
+ ]),
418
+ 24
419
+ ],
420
+ [
421
+ new IPv4([
422
+ 203,
423
+ 0,
424
+ 113,
425
+ 0
426
+ ]),
427
+ 24
428
+ ],
429
+ [
430
+ new IPv4([
431
+ 240,
432
+ 0,
433
+ 0,
434
+ 0
435
+ ]),
436
+ 4
437
+ ]
438
+ ],
439
+ as112: [
440
+ [
441
+ new IPv4([
442
+ 192,
443
+ 175,
444
+ 48,
445
+ 0
446
+ ]),
447
+ 24
448
+ ],
449
+ [
450
+ new IPv4([
451
+ 192,
452
+ 31,
453
+ 196,
454
+ 0
455
+ ]),
456
+ 24
457
+ ]
458
+ ],
459
+ amt: [
460
+ [
461
+ new IPv4([
462
+ 192,
463
+ 52,
464
+ 193,
465
+ 0
466
+ ]),
467
+ 24
468
+ ]
469
+ ]
470
+ };
471
+ IPv4.prototype.kind = function() {
472
+ return 'ipv4';
473
+ };
474
+ IPv4.prototype.match = function(other, cidrRange) {
475
+ let ref;
476
+ if (void 0 === cidrRange) {
477
+ ref = other;
478
+ other = ref[0];
479
+ cidrRange = ref[1];
480
+ }
481
+ if ('ipv4' !== other.kind()) throw new Error('ipaddr: cannot match ipv4 address with non-ipv4 one');
482
+ return matchCIDR(this.octets, other.octets, 8, cidrRange);
483
+ };
484
+ IPv4.prototype.prefixLengthFromSubnetMask = function() {
485
+ let cidr = 0;
486
+ let stop = false;
487
+ const zerotable = {
488
+ 0: 8,
489
+ 128: 7,
490
+ 192: 6,
491
+ 224: 5,
492
+ 240: 4,
493
+ 248: 3,
494
+ 252: 2,
495
+ 254: 1,
496
+ 255: 0
497
+ };
498
+ let i, octet, zeros;
499
+ for(i = 3; i >= 0; i -= 1){
500
+ octet = this.octets[i];
501
+ if (!(octet in zerotable)) return null;
502
+ zeros = zerotable[octet];
503
+ if (stop && 0 !== zeros) return null;
504
+ if (8 !== zeros) stop = true;
505
+ cidr += zeros;
506
+ }
507
+ return 32 - cidr;
508
+ };
509
+ IPv4.prototype.range = function() {
510
+ return ipaddr.subnetMatch(this, this.SpecialRanges);
511
+ };
512
+ IPv4.prototype.toByteArray = function() {
513
+ return this.octets.slice(0);
514
+ };
515
+ IPv4.prototype.toIPv4MappedAddress = function() {
516
+ return ipaddr.IPv6.parse(`::ffff:${this.toString()}`);
517
+ };
518
+ IPv4.prototype.toNormalizedString = function() {
519
+ return this.toString();
520
+ };
521
+ IPv4.prototype.toString = function() {
522
+ return this.octets.join('.');
523
+ };
524
+ return IPv4;
525
+ }();
526
+ ipaddr.IPv4.broadcastAddressFromCIDR = function(string) {
527
+ try {
528
+ const cidr = this.parseCIDR(string);
529
+ const ipInterfaceOctets = cidr[0].toByteArray();
530
+ const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
531
+ const octets = [];
532
+ let i = 0;
533
+ while(i < 4){
534
+ octets.push(parseInt(ipInterfaceOctets[i], 10) | 255 ^ parseInt(subnetMaskOctets[i], 10));
535
+ i++;
536
+ }
537
+ return new this(octets);
538
+ } catch (e) {
539
+ throw new Error('ipaddr: the address does not have IPv4 CIDR format');
540
+ }
541
+ };
542
+ ipaddr.IPv4.isIPv4 = function(string) {
543
+ return null !== this.parser(string);
544
+ };
545
+ ipaddr.IPv4.isValid = function(string) {
546
+ try {
547
+ new this(this.parser(string));
548
+ return true;
549
+ } catch (e) {
550
+ return false;
551
+ }
552
+ };
553
+ ipaddr.IPv4.isValidCIDR = function(string) {
554
+ try {
555
+ this.parseCIDR(string);
556
+ return true;
557
+ } catch (e) {
558
+ return false;
559
+ }
560
+ };
561
+ ipaddr.IPv4.isValidFourPartDecimal = function(string) {
562
+ if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) return true;
563
+ return false;
564
+ };
565
+ ipaddr.IPv4.isValidCIDRFourPartDecimal = function(string) {
566
+ const match = string.match(/^(.+)\/(\d+)$/);
567
+ if (!ipaddr.IPv4.isValidCIDR(string) || !match) return false;
568
+ return ipaddr.IPv4.isValidFourPartDecimal(match[1]);
569
+ };
570
+ ipaddr.IPv4.networkAddressFromCIDR = function(string) {
571
+ let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;
572
+ try {
573
+ cidr = this.parseCIDR(string);
574
+ ipInterfaceOctets = cidr[0].toByteArray();
575
+ subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
576
+ octets = [];
577
+ i = 0;
578
+ while(i < 4){
579
+ octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));
580
+ i++;
581
+ }
582
+ return new this(octets);
583
+ } catch (e) {
584
+ throw new Error('ipaddr: the address does not have IPv4 CIDR format');
585
+ }
586
+ };
587
+ ipaddr.IPv4.parse = function(string) {
588
+ const parts = this.parser(string);
589
+ if (null === parts) throw new Error('ipaddr: string is not formatted like an IPv4 Address');
590
+ return new this(parts);
591
+ };
592
+ ipaddr.IPv4.parseCIDR = function(string) {
593
+ let match;
594
+ if (match = string.match(/^(.+)\/(\d+)$/)) {
595
+ const maskLength = parseInt(match[2]);
596
+ if (maskLength >= 0 && maskLength <= 32) {
597
+ const parsed = [
598
+ this.parse(match[1]),
599
+ maskLength
600
+ ];
601
+ Object.defineProperty(parsed, 'toString', {
602
+ value: function() {
603
+ return this.join('/');
604
+ }
605
+ });
606
+ return parsed;
607
+ }
608
+ }
609
+ throw new Error('ipaddr: string is not formatted like an IPv4 CIDR range');
610
+ };
611
+ ipaddr.IPv4.parser = function(string) {
612
+ let match, part, value;
613
+ if (match = string.match(ipv4Regexes.fourOctet)) return function() {
614
+ const ref = match.slice(1, 6);
615
+ const results = [];
616
+ for(let i = 0; i < ref.length; i++){
617
+ part = ref[i];
618
+ results.push(parseIntAuto(part));
619
+ }
620
+ return results;
621
+ }();
622
+ if (match = string.match(ipv4Regexes.longValue)) {
623
+ value = parseIntAuto(match[1]);
624
+ if (value > 0xffffffff || value < 0) throw new Error('ipaddr: address outside defined range');
625
+ return (function() {
626
+ const results = [];
627
+ let shift;
628
+ for(shift = 0; shift <= 24; shift += 8)results.push(value >> shift & 0xff);
629
+ return results;
630
+ })().reverse();
631
+ }
632
+ if (match = string.match(ipv4Regexes.twoOctet)) return function() {
633
+ const ref = match.slice(1, 4);
634
+ const results = [];
635
+ value = parseIntAuto(ref[1]);
636
+ if (value > 0xffffff || value < 0) throw new Error('ipaddr: address outside defined range');
637
+ results.push(parseIntAuto(ref[0]));
638
+ results.push(value >> 16 & 0xff);
639
+ results.push(value >> 8 & 0xff);
640
+ results.push(0xff & value);
641
+ return results;
642
+ }();
643
+ if (match = string.match(ipv4Regexes.threeOctet)) return function() {
644
+ const ref = match.slice(1, 5);
645
+ const results = [];
646
+ value = parseIntAuto(ref[2]);
647
+ if (value > 0xffff || value < 0) throw new Error('ipaddr: address outside defined range');
648
+ results.push(parseIntAuto(ref[0]));
649
+ results.push(parseIntAuto(ref[1]));
650
+ results.push(value >> 8 & 0xff);
651
+ results.push(0xff & value);
652
+ return results;
653
+ }();
654
+ return null;
655
+ };
656
+ ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) {
657
+ prefix = parseInt(prefix);
658
+ if (prefix < 0 || prefix > 32) throw new Error('ipaddr: invalid IPv4 prefix length');
659
+ const octets = [
660
+ 0,
661
+ 0,
662
+ 0,
663
+ 0
664
+ ];
665
+ let j = 0;
666
+ const filledOctetCount = Math.floor(prefix / 8);
667
+ while(j < filledOctetCount){
668
+ octets[j] = 255;
669
+ j++;
670
+ }
671
+ if (filledOctetCount < 4) octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - prefix % 8;
672
+ return new this(octets);
673
+ };
674
+ ipaddr.IPv6 = function() {
675
+ function IPv6(parts, zoneId) {
676
+ let i, part;
677
+ if (16 === parts.length) {
678
+ this.parts = [];
679
+ for(i = 0; i <= 14; i += 2)this.parts.push(parts[i] << 8 | parts[i + 1]);
680
+ } else if (8 === parts.length) this.parts = parts;
681
+ else throw new Error('ipaddr: ipv6 part count should be 8 or 16');
682
+ for(i = 0; i < this.parts.length; i++){
683
+ part = this.parts[i];
684
+ if (!(0 <= part && part <= 0xffff)) throw new Error('ipaddr: ipv6 part should fit in 16 bits');
685
+ }
686
+ if (zoneId) this.zoneId = zoneId;
687
+ }
688
+ IPv6.prototype.SpecialRanges = {
689
+ unspecified: [
690
+ new IPv6([
691
+ 0,
692
+ 0,
693
+ 0,
694
+ 0,
695
+ 0,
696
+ 0,
697
+ 0,
698
+ 0
699
+ ]),
700
+ 128
701
+ ],
702
+ linkLocal: [
703
+ new IPv6([
704
+ 0xfe80,
705
+ 0,
706
+ 0,
707
+ 0,
708
+ 0,
709
+ 0,
710
+ 0,
711
+ 0
712
+ ]),
713
+ 10
714
+ ],
715
+ multicast: [
716
+ new IPv6([
717
+ 0xff00,
718
+ 0,
719
+ 0,
720
+ 0,
721
+ 0,
722
+ 0,
723
+ 0,
724
+ 0
725
+ ]),
726
+ 8
727
+ ],
728
+ loopback: [
729
+ new IPv6([
730
+ 0,
731
+ 0,
732
+ 0,
733
+ 0,
734
+ 0,
735
+ 0,
736
+ 0,
737
+ 1
738
+ ]),
739
+ 128
740
+ ],
741
+ uniqueLocal: [
742
+ new IPv6([
743
+ 0xfc00,
744
+ 0,
745
+ 0,
746
+ 0,
747
+ 0,
748
+ 0,
749
+ 0,
750
+ 0
751
+ ]),
752
+ 7
753
+ ],
754
+ ipv4Mapped: [
755
+ new IPv6([
756
+ 0,
757
+ 0,
758
+ 0,
759
+ 0,
760
+ 0,
761
+ 0xffff,
762
+ 0,
763
+ 0
764
+ ]),
765
+ 96
766
+ ],
767
+ discard: [
768
+ new IPv6([
769
+ 0x100,
770
+ 0,
771
+ 0,
772
+ 0,
773
+ 0,
774
+ 0,
775
+ 0,
776
+ 0
777
+ ]),
778
+ 64
779
+ ],
780
+ rfc6145: [
781
+ new IPv6([
782
+ 0,
783
+ 0,
784
+ 0,
785
+ 0,
786
+ 0xffff,
787
+ 0,
788
+ 0,
789
+ 0
790
+ ]),
791
+ 96
792
+ ],
793
+ rfc6052: [
794
+ new IPv6([
795
+ 0x64,
796
+ 0xff9b,
797
+ 0,
798
+ 0,
799
+ 0,
800
+ 0,
801
+ 0,
802
+ 0
803
+ ]),
804
+ 96
805
+ ],
806
+ '6to4': [
807
+ new IPv6([
808
+ 0x2002,
809
+ 0,
810
+ 0,
811
+ 0,
812
+ 0,
813
+ 0,
814
+ 0,
815
+ 0
816
+ ]),
817
+ 16
818
+ ],
819
+ teredo: [
820
+ new IPv6([
821
+ 0x2001,
822
+ 0,
823
+ 0,
824
+ 0,
825
+ 0,
826
+ 0,
827
+ 0,
828
+ 0
829
+ ]),
830
+ 32
831
+ ],
832
+ benchmarking: [
833
+ new IPv6([
834
+ 0x2001,
835
+ 0x2,
836
+ 0,
837
+ 0,
838
+ 0,
839
+ 0,
840
+ 0,
841
+ 0
842
+ ]),
843
+ 48
844
+ ],
845
+ amt: [
846
+ new IPv6([
847
+ 0x2001,
848
+ 0x3,
849
+ 0,
850
+ 0,
851
+ 0,
852
+ 0,
853
+ 0,
854
+ 0
855
+ ]),
856
+ 32
857
+ ],
858
+ as112v6: [
859
+ [
860
+ new IPv6([
861
+ 0x2001,
862
+ 0x4,
863
+ 0x112,
864
+ 0,
865
+ 0,
866
+ 0,
867
+ 0,
868
+ 0
869
+ ]),
870
+ 48
871
+ ],
872
+ [
873
+ new IPv6([
874
+ 0x2620,
875
+ 0x4f,
876
+ 0x8000,
877
+ 0,
878
+ 0,
879
+ 0,
880
+ 0,
881
+ 0
882
+ ]),
883
+ 48
884
+ ]
885
+ ],
886
+ deprecated: [
887
+ new IPv6([
888
+ 0x2001,
889
+ 0x10,
890
+ 0,
891
+ 0,
892
+ 0,
893
+ 0,
894
+ 0,
895
+ 0
896
+ ]),
897
+ 28
898
+ ],
899
+ orchid2: [
900
+ new IPv6([
901
+ 0x2001,
902
+ 0x20,
903
+ 0,
904
+ 0,
905
+ 0,
906
+ 0,
907
+ 0,
908
+ 0
909
+ ]),
910
+ 28
911
+ ],
912
+ droneRemoteIdProtocolEntityTags: [
913
+ new IPv6([
914
+ 0x2001,
915
+ 0x30,
916
+ 0,
917
+ 0,
918
+ 0,
919
+ 0,
920
+ 0,
921
+ 0
922
+ ]),
923
+ 28
924
+ ],
925
+ reserved: [
926
+ [
927
+ new IPv6([
928
+ 0x2001,
929
+ 0,
930
+ 0,
931
+ 0,
932
+ 0,
933
+ 0,
934
+ 0,
935
+ 0
936
+ ]),
937
+ 23
938
+ ],
939
+ [
940
+ new IPv6([
941
+ 0x2001,
942
+ 0xdb8,
943
+ 0,
944
+ 0,
945
+ 0,
946
+ 0,
947
+ 0,
948
+ 0
949
+ ]),
950
+ 32
951
+ ]
952
+ ]
953
+ };
954
+ IPv6.prototype.isIPv4MappedAddress = function() {
955
+ return 'ipv4Mapped' === this.range();
956
+ };
957
+ IPv6.prototype.kind = function() {
958
+ return 'ipv6';
959
+ };
960
+ IPv6.prototype.match = function(other, cidrRange) {
961
+ let ref;
962
+ if (void 0 === cidrRange) {
963
+ ref = other;
964
+ other = ref[0];
965
+ cidrRange = ref[1];
966
+ }
967
+ if ('ipv6' !== other.kind()) throw new Error('ipaddr: cannot match ipv6 address with non-ipv6 one');
968
+ return matchCIDR(this.parts, other.parts, 16, cidrRange);
969
+ };
970
+ IPv6.prototype.prefixLengthFromSubnetMask = function() {
971
+ let cidr = 0;
972
+ let stop = false;
973
+ const zerotable = {
974
+ 0: 16,
975
+ 32768: 15,
976
+ 49152: 14,
977
+ 57344: 13,
978
+ 61440: 12,
979
+ 63488: 11,
980
+ 64512: 10,
981
+ 65024: 9,
982
+ 65280: 8,
983
+ 65408: 7,
984
+ 65472: 6,
985
+ 65504: 5,
986
+ 65520: 4,
987
+ 65528: 3,
988
+ 65532: 2,
989
+ 65534: 1,
990
+ 65535: 0
991
+ };
992
+ let part, zeros;
993
+ for(let i = 7; i >= 0; i -= 1){
994
+ part = this.parts[i];
995
+ if (!(part in zerotable)) return null;
996
+ zeros = zerotable[part];
997
+ if (stop && 0 !== zeros) return null;
998
+ if (16 !== zeros) stop = true;
999
+ cidr += zeros;
1000
+ }
1001
+ return 128 - cidr;
1002
+ };
1003
+ IPv6.prototype.range = function() {
1004
+ return ipaddr.subnetMatch(this, this.SpecialRanges);
1005
+ };
1006
+ IPv6.prototype.toByteArray = function() {
1007
+ let part;
1008
+ const bytes = [];
1009
+ const ref = this.parts;
1010
+ for(let i = 0; i < ref.length; i++){
1011
+ part = ref[i];
1012
+ bytes.push(part >> 8);
1013
+ bytes.push(0xff & part);
1014
+ }
1015
+ return bytes;
1016
+ };
1017
+ IPv6.prototype.toFixedLengthString = function() {
1018
+ const addr = (function() {
1019
+ const results = [];
1020
+ for(let i = 0; i < this.parts.length; i++)results.push(padPart(this.parts[i].toString(16), 4));
1021
+ return results;
1022
+ }).call(this).join(':');
1023
+ let suffix = '';
1024
+ if (this.zoneId) suffix = `%${this.zoneId}`;
1025
+ return addr + suffix;
1026
+ };
1027
+ IPv6.prototype.toIPv4Address = function() {
1028
+ if (!this.isIPv4MappedAddress()) throw new Error('ipaddr: trying to convert a generic ipv6 address to ipv4');
1029
+ const ref = this.parts.slice(-2);
1030
+ const high = ref[0];
1031
+ const low = ref[1];
1032
+ return new ipaddr.IPv4([
1033
+ high >> 8,
1034
+ 0xff & high,
1035
+ low >> 8,
1036
+ 0xff & low
1037
+ ]);
1038
+ };
1039
+ IPv6.prototype.toNormalizedString = function() {
1040
+ const addr = (function() {
1041
+ const results = [];
1042
+ for(let i = 0; i < this.parts.length; i++)results.push(this.parts[i].toString(16));
1043
+ return results;
1044
+ }).call(this).join(':');
1045
+ let suffix = '';
1046
+ if (this.zoneId) suffix = `%${this.zoneId}`;
1047
+ return addr + suffix;
1048
+ };
1049
+ IPv6.prototype.toRFC5952String = function() {
1050
+ const regex = /((^|:)(0(:|$)){2,})/g;
1051
+ const string = this.toNormalizedString();
1052
+ let bestMatchIndex = 0;
1053
+ let bestMatchLength = -1;
1054
+ let match;
1055
+ while(match = regex.exec(string))if (match[0].length > bestMatchLength) {
1056
+ bestMatchIndex = match.index;
1057
+ bestMatchLength = match[0].length;
1058
+ }
1059
+ if (bestMatchLength < 0) return string;
1060
+ return `${string.substring(0, bestMatchIndex)}::${string.substring(bestMatchIndex + bestMatchLength)}`;
1061
+ };
1062
+ IPv6.prototype.toString = function() {
1063
+ return this.toRFC5952String();
1064
+ };
1065
+ return IPv6;
1066
+ }();
1067
+ ipaddr.IPv6.broadcastAddressFromCIDR = function(string) {
1068
+ try {
1069
+ const cidr = this.parseCIDR(string);
1070
+ const ipInterfaceOctets = cidr[0].toByteArray();
1071
+ const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
1072
+ const octets = [];
1073
+ let i = 0;
1074
+ while(i < 16){
1075
+ octets.push(parseInt(ipInterfaceOctets[i], 10) | 255 ^ parseInt(subnetMaskOctets[i], 10));
1076
+ i++;
1077
+ }
1078
+ return new this(octets);
1079
+ } catch (e) {
1080
+ throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`);
1081
+ }
1082
+ };
1083
+ ipaddr.IPv6.isIPv6 = function(string) {
1084
+ return null !== this.parser(string);
1085
+ };
1086
+ ipaddr.IPv6.isValid = function(string) {
1087
+ if ('string' == typeof string && -1 === string.indexOf(':')) return false;
1088
+ try {
1089
+ const addr = this.parser(string);
1090
+ new this(addr.parts, addr.zoneId);
1091
+ return true;
1092
+ } catch (e) {
1093
+ return false;
1094
+ }
1095
+ };
1096
+ ipaddr.IPv6.isValidCIDR = function(string) {
1097
+ if ('string' == typeof string && -1 === string.indexOf(':')) return false;
1098
+ try {
1099
+ this.parseCIDR(string);
1100
+ return true;
1101
+ } catch (e) {
1102
+ return false;
1103
+ }
1104
+ };
1105
+ ipaddr.IPv6.networkAddressFromCIDR = function(string) {
1106
+ let cidr, i, ipInterfaceOctets, octets, subnetMaskOctets;
1107
+ try {
1108
+ cidr = this.parseCIDR(string);
1109
+ ipInterfaceOctets = cidr[0].toByteArray();
1110
+ subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
1111
+ octets = [];
1112
+ i = 0;
1113
+ while(i < 16){
1114
+ octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));
1115
+ i++;
1116
+ }
1117
+ return new this(octets);
1118
+ } catch (e) {
1119
+ throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`);
1120
+ }
1121
+ };
1122
+ ipaddr.IPv6.parse = function(string) {
1123
+ const addr = this.parser(string);
1124
+ if (null === addr.parts) throw new Error('ipaddr: string is not formatted like an IPv6 Address');
1125
+ return new this(addr.parts, addr.zoneId);
1126
+ };
1127
+ ipaddr.IPv6.parseCIDR = function(string) {
1128
+ let maskLength, match, parsed;
1129
+ if (match = string.match(/^(.+)\/(\d+)$/)) {
1130
+ maskLength = parseInt(match[2]);
1131
+ if (maskLength >= 0 && maskLength <= 128) {
1132
+ parsed = [
1133
+ this.parse(match[1]),
1134
+ maskLength
1135
+ ];
1136
+ Object.defineProperty(parsed, 'toString', {
1137
+ value: function() {
1138
+ return this.join('/');
1139
+ }
1140
+ });
1141
+ return parsed;
1142
+ }
1143
+ }
1144
+ throw new Error('ipaddr: string is not formatted like an IPv6 CIDR range');
1145
+ };
1146
+ ipaddr.IPv6.parser = function(string) {
1147
+ let addr, i, match, octet, octets, zoneId;
1148
+ if (match = string.match(ipv6Regexes.deprecatedTransitional)) return this.parser(`::ffff:${match[1]}`);
1149
+ if (ipv6Regexes.native.test(string)) return expandIPv6(string, 8);
1150
+ if (match = string.match(ipv6Regexes.transitional)) {
1151
+ zoneId = match[6] || '';
1152
+ addr = match[1];
1153
+ if (!match[1].endsWith('::')) addr = addr.slice(0, -1);
1154
+ addr = expandIPv6(addr + zoneId, 6);
1155
+ if (addr.parts) {
1156
+ octets = [
1157
+ parseInt(match[2]),
1158
+ parseInt(match[3]),
1159
+ parseInt(match[4]),
1160
+ parseInt(match[5])
1161
+ ];
1162
+ for(i = 0; i < octets.length; i++){
1163
+ octet = octets[i];
1164
+ if (!(0 <= octet && octet <= 255)) return null;
1165
+ }
1166
+ addr.parts.push(octets[0] << 8 | octets[1]);
1167
+ addr.parts.push(octets[2] << 8 | octets[3]);
1168
+ return {
1169
+ parts: addr.parts,
1170
+ zoneId: addr.zoneId
1171
+ };
1172
+ }
1173
+ }
1174
+ return null;
1175
+ };
1176
+ ipaddr.IPv6.subnetMaskFromPrefixLength = function(prefix) {
1177
+ prefix = parseInt(prefix);
1178
+ if (prefix < 0 || prefix > 128) throw new Error('ipaddr: invalid IPv6 prefix length');
1179
+ const octets = [
1180
+ 0,
1181
+ 0,
1182
+ 0,
1183
+ 0,
1184
+ 0,
1185
+ 0,
1186
+ 0,
1187
+ 0,
1188
+ 0,
1189
+ 0,
1190
+ 0,
1191
+ 0,
1192
+ 0,
1193
+ 0,
1194
+ 0,
1195
+ 0
1196
+ ];
1197
+ let j = 0;
1198
+ const filledOctetCount = Math.floor(prefix / 8);
1199
+ while(j < filledOctetCount){
1200
+ octets[j] = 255;
1201
+ j++;
1202
+ }
1203
+ if (filledOctetCount < 16) octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - prefix % 8;
1204
+ return new this(octets);
1205
+ };
1206
+ ipaddr.fromByteArray = function(bytes) {
1207
+ const length = bytes.length;
1208
+ if (4 === length) return new ipaddr.IPv4(bytes);
1209
+ if (16 === length) return new ipaddr.IPv6(bytes);
1210
+ throw new Error('ipaddr: the binary input is neither an IPv6 nor IPv4 address');
1211
+ };
1212
+ ipaddr.isValid = function(string) {
1213
+ return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);
1214
+ };
1215
+ ipaddr.isValidCIDR = function(string) {
1216
+ return ipaddr.IPv6.isValidCIDR(string) || ipaddr.IPv4.isValidCIDR(string);
1217
+ };
1218
+ ipaddr.parse = function(string) {
1219
+ if (ipaddr.IPv6.isValid(string)) return ipaddr.IPv6.parse(string);
1220
+ if (ipaddr.IPv4.isValid(string)) return ipaddr.IPv4.parse(string);
1221
+ throw new Error('ipaddr: the address has neither IPv6 nor IPv4 format');
1222
+ };
1223
+ ipaddr.parseCIDR = function(string) {
1224
+ try {
1225
+ return ipaddr.IPv6.parseCIDR(string);
1226
+ } catch (e) {
1227
+ try {
1228
+ return ipaddr.IPv4.parseCIDR(string);
1229
+ } catch (e2) {
1230
+ throw new Error('ipaddr: the address has neither IPv6 nor IPv4 CIDR format');
1231
+ }
1232
+ }
1233
+ };
1234
+ ipaddr.process = function(string) {
1235
+ const addr = this.parse(string);
1236
+ if ('ipv6' === addr.kind() && addr.isIPv4MappedAddress()) return addr.toIPv4Address();
1237
+ return addr;
1238
+ };
1239
+ ipaddr.subnetMatch = function(address, rangeList, defaultName) {
1240
+ let i, rangeName, rangeSubnets, subnet;
1241
+ if (null == defaultName) defaultName = 'unicast';
1242
+ for(rangeName in rangeList)if (Object.prototype.hasOwnProperty.call(rangeList, rangeName)) {
1243
+ rangeSubnets = rangeList[rangeName];
1244
+ if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) rangeSubnets = [
1245
+ rangeSubnets
1246
+ ];
1247
+ for(i = 0; i < rangeSubnets.length; i++){
1248
+ subnet = rangeSubnets[i];
1249
+ if (address.kind() === subnet[0].kind() && address.match.apply(address, subnet)) return rangeName;
1250
+ }
1251
+ }
1252
+ return defaultName;
1253
+ };
1254
+ if (module.exports) module.exports = ipaddr;
1255
+ else root.ipaddr = ipaddr;
1256
+ })(this);
1257
+ },
1258
+ async_hooks (module) {
1259
+ module.exports = __rspack_createRequire_require("async_hooks");
1260
+ },
1261
+ child_process (module) {
1262
+ module.exports = __rspack_createRequire_require("child_process");
1263
+ },
1264
+ crypto (module) {
1265
+ module.exports = __rspack_createRequire_require("crypto");
1266
+ },
1267
+ fs (module) {
1268
+ module.exports = __rspack_createRequire_require("fs");
1269
+ },
1270
+ os (module) {
1271
+ module.exports = __rspack_createRequire_require("os");
1272
+ },
1273
+ path (module) {
1274
+ module.exports = __rspack_createRequire_require("path");
1275
+ },
1276
+ stream (module) {
1277
+ module.exports = __rspack_createRequire_require("stream");
1278
+ },
1279
+ tty (module) {
1280
+ module.exports = __rspack_createRequire_require("tty");
1281
+ },
1282
+ url (module) {
1283
+ module.exports = __rspack_createRequire_require("url");
1284
+ },
1285
+ util (module) {
1286
+ module.exports = __rspack_createRequire_require("util");
1287
+ },
1288
+ zlib (module) {
1289
+ module.exports = __rspack_createRequire_require("zlib");
1290
+ }
1291
+ });
1292
+ const minPort = 1024;
1293
+ const maxPort = 65535;
1294
+ const getLocalHosts = ()=>{
1295
+ const interfaces = __rspack_external_node_os_74b4b876.networkInterfaces();
1296
+ const results = new Set([
1297
+ void 0,
1298
+ '0.0.0.0'
1299
+ ]);
1300
+ for (const _interface of Object.values(interfaces))if (_interface) for (const config of _interface)results.add(config.address);
1301
+ return results;
1302
+ };
1303
+ const checkAvailablePort = (basePort, host)=>new Promise((resolve, reject)=>{
1304
+ const server = __rspack_external_node_net_0373943e.createServer();
1305
+ server.unref();
1306
+ server.on('error', reject);
1307
+ server.listen(basePort, host, ()=>{
1308
+ const { port } = server.address();
1309
+ server.close(()=>{
1310
+ resolve(port);
1311
+ });
1312
+ });
1313
+ });
1314
+ const getAvailablePort = async (port, hosts)=>{
1315
+ const nonExistentInterfaceErrors = new Set([
1316
+ 'EADDRNOTAVAIL',
1317
+ 'EINVAL'
1318
+ ]);
1319
+ for (const host of hosts)try {
1320
+ await checkAvailablePort(port, host);
1321
+ } catch (error) {
1322
+ if (!nonExistentInterfaceErrors.has(error.code || '')) throw error;
1323
+ }
1324
+ return port;
1325
+ };
1326
+ async function getPort(basePort, host) {
1327
+ if (basePort < minPort || basePort > maxPort) throw new Error(`Port number must lie between ${minPort} and ${maxPort}`);
1328
+ let port = basePort;
1329
+ const localhosts = getLocalHosts();
1330
+ const hosts = host && !localhosts.has(host) ? new Set([
1331
+ host
1332
+ ]) : localhosts;
1333
+ const portUnavailableErrors = new Set([
1334
+ 'EADDRINUSE',
1335
+ 'EACCES'
1336
+ ]);
1337
+ while(port <= maxPort)try {
1338
+ const availablePort = await getAvailablePort(port, hosts);
1339
+ return availablePort;
1340
+ } catch (error) {
1341
+ if (!portUnavailableErrors.has(error.code || '')) throw error;
1342
+ port += 1;
1343
+ }
1344
+ throw new Error('No available ports found');
1345
+ }
1346
+ class BaseServer {
1347
+ server;
1348
+ clients;
1349
+ constructor(server){
1350
+ this.server = server;
1351
+ this.clients = [];
1352
+ }
1353
+ }
1354
+ const servers_BaseServer = BaseServer;
1355
+ class WebsocketServer extends servers_BaseServer {
1356
+ static heartbeatInterval = 1000;
1357
+ implementation;
1358
+ constructor(server){
1359
+ super(server);
1360
+ const options = {
1361
+ ...this.server.options.webSocketServer.options,
1362
+ clientTracking: false
1363
+ };
1364
+ const isNoServerMode = void 0 === options.port && void 0 === options.server;
1365
+ if (isNoServerMode) options.noServer = true;
1366
+ this.implementation = new __rspack_external_ws.WebSocketServer(options);
1367
+ this.server.server.on('upgrade', (req, sock, head)=>{
1368
+ if (!this.implementation.shouldHandle(req)) return;
1369
+ this.implementation.handleUpgrade(req, sock, head, (connection)=>{
1370
+ this.implementation.emit('connection', connection, req);
1371
+ });
1372
+ });
1373
+ this.implementation.on('error', (err)=>{
1374
+ this.server.logger.error(err.message);
1375
+ });
1376
+ const interval = setInterval(()=>{
1377
+ for (const client of this.clients){
1378
+ if (false === client.isAlive) {
1379
+ client.terminate();
1380
+ continue;
1381
+ }
1382
+ client.isAlive = false;
1383
+ client.ping(()=>{});
1384
+ }
1385
+ }, WebsocketServer.heartbeatInterval);
1386
+ this.implementation.on('connection', (client)=>{
1387
+ this.clients.push(client);
1388
+ client.isAlive = true;
1389
+ client.on('pong', ()=>{
1390
+ client.isAlive = true;
1391
+ });
1392
+ client.on('close', ()=>{
1393
+ this.clients.splice(this.clients.indexOf(client), 1);
1394
+ });
1395
+ client.on('error', (err)=>{
1396
+ this.server.logger.error(err.message);
1397
+ });
1398
+ });
1399
+ this.implementation.on('close', ()=>{
1400
+ clearInterval(interval);
1401
+ });
1402
+ }
1403
+ }
1404
+ const src = __webpack_require__("./node_modules/.pnpm/http-compression@1.1.2/node_modules/http-compression/src/index.js");
1405
+ var src_default = /*#__PURE__*/ __webpack_require__.n(src);
1406
+ const ipaddr = __webpack_require__("./node_modules/.pnpm/ipaddr.js@2.3.0/node_modules/ipaddr.js/lib/ipaddr.js");
1407
+ var ipaddr_default = /*#__PURE__*/ __webpack_require__.n(ipaddr);
1408
+ const { styleText: styleText } = __rspack_external_node_util_1b29d436;
1409
+ const server_require = createRequire(import.meta.url);
1410
+ if (!process.env.RSPACK_SERVE) process.env.RSPACK_SERVE = 'true';
1411
+ const getConnect = async ()=>{
1412
+ const { connect } = await import("connect-next");
1413
+ return connect;
1414
+ };
1415
+ const getChokidar = ()=>import("chokidar");
1416
+ const encodeOverlaySettings = (setting)=>'function' == typeof setting ? encodeURIComponent(setting.toString()) : setting;
1417
+ const DEFAULT_ALLOWED_PROTOCOLS = /^(file|.+-extension):/i;
1418
+ function parseHostnameFromHeader(header) {
1419
+ try {
1420
+ const parsedUrl = new URL(/^(.+:)?\/\//.test(header) ? header : `//${header}`, 'http://localhost/');
1421
+ let { hostname } = parsedUrl;
1422
+ if (hostname.startsWith('[') && hostname.endsWith(']')) hostname = hostname.slice(1, -1);
1423
+ return hostname;
1424
+ } catch {
1425
+ return null;
1426
+ }
1427
+ }
1428
+ function isMultiCompiler(compiler) {
1429
+ return Array.isArray(compiler.compilers);
1430
+ }
1431
+ class Server {
1432
+ compiler;
1433
+ logger;
1434
+ options;
1435
+ staticWatchers;
1436
+ listeners;
1437
+ webSocketProxies;
1438
+ sockets;
1439
+ currentHash;
1440
+ isTlsServer = false;
1441
+ webSocketServer;
1442
+ middleware;
1443
+ server;
1444
+ app;
1445
+ stats;
1446
+ constructor(options, compiler){
1447
+ this.compiler = compiler;
1448
+ this.logger = this.compiler.getInfrastructureLogger('rspack-dev-server');
1449
+ this.options = options;
1450
+ this.staticWatchers = [];
1451
+ this.listeners = [];
1452
+ this.webSocketProxies = [];
1453
+ this.sockets = [];
1454
+ this.currentHash = void 0;
1455
+ }
1456
+ static get DEFAULT_STATS() {
1457
+ return {
1458
+ all: false,
1459
+ hash: true,
1460
+ warnings: true,
1461
+ errors: true,
1462
+ errorDetails: false
1463
+ };
1464
+ }
1465
+ static isAbsoluteURL(URL1) {
1466
+ if (/^[a-zA-Z]:\\/.test(URL1)) return false;
1467
+ return /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(URL1);
1468
+ }
1469
+ static findIp(gatewayOrFamily, isInternal) {
1470
+ if ('v4' === gatewayOrFamily || 'v6' === gatewayOrFamily) {
1471
+ let host;
1472
+ const networks = Object.values(__rspack_external_node_os_74b4b876.networkInterfaces()).flatMap((networks)=>networks ?? []).filter((network)=>{
1473
+ if (!network || !network.address) return false;
1474
+ if (network.family !== `IP${gatewayOrFamily}`) return false;
1475
+ if (void 0 !== isInternal && network.internal !== isInternal) return false;
1476
+ if ('v6' === gatewayOrFamily) {
1477
+ const range = ipaddr_default().parse(network.address).range();
1478
+ if ('ipv4Mapped' !== range && 'uniqueLocal' !== range && 'loopback' !== range) return false;
1479
+ }
1480
+ return network.address;
1481
+ });
1482
+ if (networks.length > 0) {
1483
+ host = networks[0].address;
1484
+ if (host.includes(':')) host = `[${host}]`;
1485
+ }
1486
+ return host;
1487
+ }
1488
+ const gatewayIp = ipaddr_default().parse(gatewayOrFamily);
1489
+ for (const addresses of Object.values(__rspack_external_node_os_74b4b876.networkInterfaces()))for (const { cidr } of addresses){
1490
+ const net = ipaddr_default().parseCIDR(cidr);
1491
+ if (net[0] && net[0].kind() === gatewayIp.kind() && gatewayIp.match(net)) return net[0].toString();
1492
+ }
1493
+ }
1494
+ static async getHostname(hostname) {
1495
+ if ('local-ip' === hostname) return Server.findIp('v4', false) || Server.findIp('v6', false) || '0.0.0.0';
1496
+ if ('local-ipv4' === hostname) return Server.findIp('v4', false) || '0.0.0.0';
1497
+ if ('local-ipv6' === hostname) return Server.findIp('v6', false) || '::';
1498
+ return hostname;
1499
+ }
1500
+ static async getFreePort(port, host) {
1501
+ if (null != port && 'auto' !== port) return port;
1502
+ const { default: pRetry } = await import("./0~p-retry.js");
1503
+ const basePort = void 0 !== process.env.RSPACK_DEV_SERVER_BASE_PORT ? Number.parseInt(process.env.RSPACK_DEV_SERVER_BASE_PORT, 10) : 8080;
1504
+ const defaultPortRetry = void 0 !== process.env.RSPACK_DEV_SERVER_PORT_RETRY ? Number.parseInt(process.env.RSPACK_DEV_SERVER_PORT_RETRY, 10) : 3;
1505
+ return pRetry(()=>getPort(basePort, host), {
1506
+ retries: defaultPortRetry
1507
+ });
1508
+ }
1509
+ static findCacheDir() {
1510
+ const cwd = process.cwd();
1511
+ let dir = cwd;
1512
+ for(;;){
1513
+ try {
1514
+ if (__rspack_external_node_fs_5ea92f0c.statSync(__rspack_external_node_path_c5b9b54f.join(dir, 'package.json')).isFile()) break;
1515
+ } catch {}
1516
+ const parent = __rspack_external_node_path_c5b9b54f.dirname(dir);
1517
+ if (dir === parent) {
1518
+ dir = void 0;
1519
+ break;
1520
+ }
1521
+ dir = parent;
1522
+ }
1523
+ if (!dir) return __rspack_external_node_path_c5b9b54f.resolve(cwd, '.cache/rspack-dev-server');
1524
+ if ('1' === process.versions.pnp) return __rspack_external_node_path_c5b9b54f.resolve(dir, '.pnp/.cache/rspack-dev-server');
1525
+ if ('3' === process.versions.pnp) return __rspack_external_node_path_c5b9b54f.resolve(dir, '.yarn/.cache/rspack-dev-server');
1526
+ return __rspack_external_node_path_c5b9b54f.resolve(dir, 'node_modules/.cache/rspack-dev-server');
1527
+ }
1528
+ #addAdditionalEntries(compiler) {
1529
+ const additionalEntries = [];
1530
+ const isWebTarget = Boolean(compiler.platform.web);
1531
+ if (this.options.client && isWebTarget) {
1532
+ let webSocketURLStr = '';
1533
+ if (this.options.webSocketServer) {
1534
+ const webSocketURL = this.options.client.webSocketURL;
1535
+ const webSocketServer = this.options.webSocketServer;
1536
+ const searchParams = new URLSearchParams();
1537
+ let protocol;
1538
+ protocol = void 0 !== webSocketURL.protocol ? webSocketURL.protocol : this.isTlsServer ? 'wss:' : 'ws:';
1539
+ searchParams.set('protocol', protocol);
1540
+ if (void 0 !== webSocketURL.username) searchParams.set('username', webSocketURL.username);
1541
+ if (void 0 !== webSocketURL.password) searchParams.set('password', webSocketURL.password);
1542
+ let hostname;
1543
+ const isWebSocketServerHostDefined = void 0 !== webSocketServer.options.host;
1544
+ const isWebSocketServerPortDefined = void 0 !== webSocketServer.options.port;
1545
+ hostname = void 0 !== webSocketURL.hostname ? webSocketURL.hostname : isWebSocketServerHostDefined ? webSocketServer.options.host : void 0 !== this.options.host ? this.options.host : '0.0.0.0';
1546
+ searchParams.set('hostname', hostname);
1547
+ let port;
1548
+ port = void 0 !== webSocketURL.port ? webSocketURL.port : isWebSocketServerPortDefined ? webSocketServer.options.port : 'number' == typeof this.options.port ? this.options.port : 'string' == typeof this.options.port && 'auto' !== this.options.port ? Number(this.options.port) : '0';
1549
+ searchParams.set('port', String(port));
1550
+ let pathname = '';
1551
+ if (void 0 !== webSocketURL.pathname) pathname = webSocketURL.pathname;
1552
+ else if (void 0 !== webSocketServer.options.path) pathname = webSocketServer.options.path;
1553
+ searchParams.set('pathname', pathname);
1554
+ const client = this.options.client;
1555
+ if (void 0 !== client.logging) searchParams.set('logging', client.logging);
1556
+ if (void 0 !== client.progress) searchParams.set('progress', String(client.progress));
1557
+ if (void 0 !== client.overlay) {
1558
+ const overlayString = 'boolean' == typeof client.overlay ? String(client.overlay) : JSON.stringify({
1559
+ ...client.overlay,
1560
+ errors: encodeOverlaySettings(client.overlay.errors),
1561
+ warnings: encodeOverlaySettings(client.overlay.warnings),
1562
+ runtimeErrors: encodeOverlaySettings(client.overlay.runtimeErrors)
1563
+ });
1564
+ searchParams.set('overlay', overlayString);
1565
+ }
1566
+ if (void 0 !== client.reconnect) searchParams.set('reconnect', 'number' == typeof client.reconnect ? String(client.reconnect) : '10');
1567
+ if (void 0 !== this.options.hot) searchParams.set('hot', String(this.options.hot));
1568
+ if (void 0 !== this.options.liveReload) searchParams.set('live-reload', String(this.options.liveReload));
1569
+ webSocketURLStr = searchParams.toString();
1570
+ }
1571
+ additionalEntries.push(`${this.getClientEntry()}?${webSocketURLStr}`);
1572
+ }
1573
+ const clientHotEntry = this.getClientHotEntry();
1574
+ if (clientHotEntry) additionalEntries.push(clientHotEntry);
1575
+ for (const additionalEntry of additionalEntries)new compiler.rspack.EntryPlugin(compiler.context, additionalEntry, {
1576
+ name: void 0
1577
+ }).apply(compiler);
1578
+ }
1579
+ #getCompilerOptions() {
1580
+ if (void 0 !== this.compiler.compilers) {
1581
+ if (1 === this.compiler.compilers.length) return this.compiler.compilers[0].options;
1582
+ const compilerWithDevServer = this.compiler.compilers.find((config)=>config.options.devServer);
1583
+ if (compilerWithDevServer) return compilerWithDevServer.options;
1584
+ const compilerWithWebTarget = this.compiler.compilers.find((compiler)=>Boolean(compiler.platform.web));
1585
+ if (compilerWithWebTarget) return compilerWithWebTarget.options;
1586
+ return this.compiler.compilers[0].options;
1587
+ }
1588
+ return this.compiler.options;
1589
+ }
1590
+ #shouldLogInfrastructureInfo() {
1591
+ const compilerOptions = this.#getCompilerOptions();
1592
+ const { level = 'info' } = compilerOptions.infrastructureLogging || {};
1593
+ return 'info' === level || 'log' === level || 'verbose' === level;
1594
+ }
1595
+ async #normalizeOptions() {
1596
+ const { options } = this;
1597
+ const compilerOptions = this.#getCompilerOptions();
1598
+ const compilerWatchOptions = compilerOptions.watchOptions;
1599
+ const getWatchOptions = (watchOptions = {})=>{
1600
+ const getPolling = ()=>{
1601
+ if (void 0 !== watchOptions.usePolling) return watchOptions.usePolling;
1602
+ if (void 0 !== watchOptions.poll) return Boolean(watchOptions.poll);
1603
+ if (void 0 !== compilerWatchOptions.poll) return Boolean(compilerWatchOptions.poll);
1604
+ return false;
1605
+ };
1606
+ const getInterval = ()=>{
1607
+ if (void 0 !== watchOptions.interval) return watchOptions.interval;
1608
+ if ('number' == typeof watchOptions.poll) return watchOptions.poll;
1609
+ if ('number' == typeof compilerWatchOptions.poll) return compilerWatchOptions.poll;
1610
+ };
1611
+ const usePolling = getPolling();
1612
+ const interval = getInterval();
1613
+ const { poll: _poll, ...rest } = watchOptions;
1614
+ return {
1615
+ ignoreInitial: true,
1616
+ persistent: true,
1617
+ followSymlinks: false,
1618
+ atomic: false,
1619
+ alwaysStat: true,
1620
+ ignorePermissionErrors: true,
1621
+ usePolling,
1622
+ ...void 0 !== interval ? {
1623
+ interval
1624
+ } : {},
1625
+ ...rest
1626
+ };
1627
+ };
1628
+ const getStaticItem = (optionsForStatic)=>{
1629
+ const getDefaultStaticOptions = ()=>({
1630
+ directory: __rspack_external_node_path_c5b9b54f.join(process.cwd(), 'public'),
1631
+ staticOptions: {},
1632
+ publicPath: [
1633
+ '/'
1634
+ ],
1635
+ watch: getWatchOptions()
1636
+ });
1637
+ let item;
1638
+ if (void 0 === optionsForStatic) item = getDefaultStaticOptions();
1639
+ else if ('string' == typeof optionsForStatic) item = {
1640
+ ...getDefaultStaticOptions(),
1641
+ directory: optionsForStatic
1642
+ };
1643
+ else {
1644
+ const def = getDefaultStaticOptions();
1645
+ item = {
1646
+ directory: void 0 !== optionsForStatic.directory ? optionsForStatic.directory : def.directory,
1647
+ staticOptions: void 0 !== optionsForStatic.staticOptions ? {
1648
+ ...def.staticOptions,
1649
+ ...optionsForStatic.staticOptions
1650
+ } : def.staticOptions,
1651
+ publicPath: void 0 !== optionsForStatic.publicPath ? Array.isArray(optionsForStatic.publicPath) ? optionsForStatic.publicPath : [
1652
+ optionsForStatic.publicPath
1653
+ ] : def.publicPath,
1654
+ watch: void 0 !== optionsForStatic.watch ? 'boolean' == typeof optionsForStatic.watch ? optionsForStatic.watch ? def.watch : false : getWatchOptions(optionsForStatic.watch) : def.watch
1655
+ };
1656
+ }
1657
+ if (Server.isAbsoluteURL(item.directory)) throw new Error('Using a URL as static.directory is not supported');
1658
+ return item;
1659
+ };
1660
+ if (void 0 === options.allowedHosts) options.allowedHosts = 'auto';
1661
+ else if ('string' == typeof options.allowedHosts && 'auto' !== options.allowedHosts && 'all' !== options.allowedHosts) options.allowedHosts = [
1662
+ options.allowedHosts
1663
+ ];
1664
+ else if (Array.isArray(options.allowedHosts) && options.allowedHosts.includes('all')) options.allowedHosts = 'all';
1665
+ if (void 0 === options.client || 'object' == typeof options.client && null !== options.client) {
1666
+ if (!options.client) options.client = {};
1667
+ if (void 0 === options.client.webSocketURL) options.client.webSocketURL = {};
1668
+ else if ('string' == typeof options.client.webSocketURL) {
1669
+ const parsedURL = new URL(options.client.webSocketURL);
1670
+ options.client.webSocketURL = {
1671
+ protocol: parsedURL.protocol,
1672
+ hostname: parsedURL.hostname,
1673
+ port: parsedURL.port.length > 0 ? Number(parsedURL.port) : '',
1674
+ pathname: parsedURL.pathname,
1675
+ username: parsedURL.username,
1676
+ password: parsedURL.password
1677
+ };
1678
+ } else if ('string' == typeof options.client.webSocketURL.port) options.client.webSocketURL.port = Number(options.client.webSocketURL.port);
1679
+ if (void 0 === options.client.overlay) options.client.overlay = true;
1680
+ else if ('boolean' != typeof options.client.overlay) options.client.overlay = {
1681
+ errors: true,
1682
+ warnings: true,
1683
+ ...options.client.overlay
1684
+ };
1685
+ if (void 0 === options.client.reconnect) options.client.reconnect = 10;
1686
+ else if (true === options.client.reconnect) options.client.reconnect = 1 / 0;
1687
+ else if (false === options.client.reconnect) options.client.reconnect = 0;
1688
+ if (void 0 === options.client.logging) options.client.logging = compilerOptions.infrastructureLogging ? compilerOptions.infrastructureLogging.level : 'info';
1689
+ }
1690
+ if (void 0 === options.compress) options.compress = true;
1691
+ if (void 0 === options.devMiddleware) options.devMiddleware = {};
1692
+ if (void 0 === options.historyApiFallback) options.historyApiFallback = false;
1693
+ else if ('boolean' == typeof options.historyApiFallback && options.historyApiFallback) options.historyApiFallback = {};
1694
+ options.hot = 'boolean' == typeof options.hot || 'only' === options.hot ? options.hot : true;
1695
+ if ('function' == typeof options.server || 'string' == typeof options.server) options.server = {
1696
+ type: options.server,
1697
+ options: {}
1698
+ };
1699
+ else {
1700
+ const serverOptions = options.server || {};
1701
+ options.server = {
1702
+ type: serverOptions.type || 'http',
1703
+ options: {
1704
+ ...serverOptions.options
1705
+ }
1706
+ };
1707
+ }
1708
+ const serverOptions = options.server.options;
1709
+ if ('https' === options.server.type || 'http2' === options.server.type) {
1710
+ if (void 0 === serverOptions.requestCert) serverOptions.requestCert = false;
1711
+ const httpsProperties = [
1712
+ 'ca',
1713
+ 'cert',
1714
+ 'crl',
1715
+ 'key',
1716
+ 'pfx'
1717
+ ];
1718
+ for (const property of httpsProperties){
1719
+ if (void 0 === serverOptions[property]) continue;
1720
+ const value = serverOptions[property];
1721
+ const readFile = (item)=>{
1722
+ if (Buffer.isBuffer(item) || 'object' == typeof item && null !== item && !Array.isArray(item)) return item;
1723
+ if (item) {
1724
+ let stats = null;
1725
+ try {
1726
+ stats = __rspack_external_node_fs_5ea92f0c.lstatSync(__rspack_external_node_fs_5ea92f0c.realpathSync(item)).isFile();
1727
+ } catch {}
1728
+ return stats ? __rspack_external_node_fs_5ea92f0c.readFileSync(item) : item;
1729
+ }
1730
+ };
1731
+ serverOptions[property] = Array.isArray(value) ? value.map((item)=>readFile(item)) : readFile(value);
1732
+ }
1733
+ let fakeCert;
1734
+ if (!serverOptions.key || !serverOptions.cert) {
1735
+ const certificateDir = Server.findCacheDir();
1736
+ const certificatePath = __rspack_external_node_path_c5b9b54f.join(certificateDir, 'server.pem');
1737
+ let certificateExists;
1738
+ try {
1739
+ const certificate = await __rspack_external_node_fs_5ea92f0c.promises.stat(certificatePath);
1740
+ certificateExists = certificate.isFile();
1741
+ } catch {
1742
+ certificateExists = false;
1743
+ }
1744
+ if (certificateExists) {
1745
+ const certificateTtl = 86400000;
1746
+ const certificateStat = await __rspack_external_node_fs_5ea92f0c.promises.stat(certificatePath);
1747
+ const now = Number(new Date());
1748
+ if ((now - Number(certificateStat.ctime)) / certificateTtl > 30) {
1749
+ this.logger.info('SSL certificate is more than 30 days old. Removing...');
1750
+ await __rspack_external_node_fs_5ea92f0c.promises.rm(certificatePath, {
1751
+ recursive: true
1752
+ });
1753
+ certificateExists = false;
1754
+ }
1755
+ }
1756
+ if (!certificateExists) {
1757
+ this.logger.info('Generating SSL certificate...');
1758
+ let selfsigned;
1759
+ try {
1760
+ selfsigned = server_require('selfsigned');
1761
+ } catch (error) {
1762
+ if (error instanceof Error && 'MODULE_NOT_FOUND' === error.code) throw new Error('Cannot generate a self-signed certificate because optional peer dependency `selfsigned@^5.0.0` is not installed. Please install it and try again.');
1763
+ throw error;
1764
+ }
1765
+ const attributes = [
1766
+ {
1767
+ name: 'commonName',
1768
+ value: 'localhost'
1769
+ }
1770
+ ];
1771
+ const notBeforeDate = new Date();
1772
+ const notAfterDate = new Date(notBeforeDate);
1773
+ notAfterDate.setDate(notAfterDate.getDate() + 30);
1774
+ const pems = await selfsigned.generate(attributes, {
1775
+ algorithm: 'sha256',
1776
+ keySize: 2048,
1777
+ notBeforeDate,
1778
+ notAfterDate,
1779
+ extensions: [
1780
+ {
1781
+ name: 'basicConstraints',
1782
+ cA: true
1783
+ },
1784
+ {
1785
+ name: 'keyUsage',
1786
+ keyCertSign: true,
1787
+ digitalSignature: true,
1788
+ nonRepudiation: true,
1789
+ keyEncipherment: true,
1790
+ dataEncipherment: true
1791
+ },
1792
+ {
1793
+ name: 'extKeyUsage',
1794
+ serverAuth: true,
1795
+ clientAuth: true,
1796
+ codeSigning: true,
1797
+ timeStamping: true
1798
+ },
1799
+ {
1800
+ name: 'subjectAltName',
1801
+ altNames: [
1802
+ {
1803
+ type: 2,
1804
+ value: 'localhost'
1805
+ },
1806
+ {
1807
+ type: 2,
1808
+ value: 'localhost.localdomain'
1809
+ },
1810
+ {
1811
+ type: 2,
1812
+ value: 'lvh.me'
1813
+ },
1814
+ {
1815
+ type: 2,
1816
+ value: '*.lvh.me'
1817
+ },
1818
+ {
1819
+ type: 2,
1820
+ value: '[::1]'
1821
+ },
1822
+ {
1823
+ type: 7,
1824
+ ip: '127.0.0.1'
1825
+ },
1826
+ {
1827
+ type: 7,
1828
+ ip: 'fe80::1'
1829
+ }
1830
+ ]
1831
+ }
1832
+ ]
1833
+ });
1834
+ await __rspack_external_node_fs_5ea92f0c.promises.mkdir(certificateDir, {
1835
+ recursive: true
1836
+ });
1837
+ await __rspack_external_node_fs_5ea92f0c.promises.writeFile(certificatePath, pems.private + pems.cert, {
1838
+ encoding: 'utf8'
1839
+ });
1840
+ }
1841
+ fakeCert = await __rspack_external_node_fs_5ea92f0c.promises.readFile(certificatePath);
1842
+ this.logger.info(`SSL certificate: ${certificatePath}`);
1843
+ }
1844
+ serverOptions.key = serverOptions.key || fakeCert;
1845
+ serverOptions.cert = serverOptions.cert || fakeCert;
1846
+ }
1847
+ if ('boolean' == typeof options.ipc) {
1848
+ const isWindows = 'win32' === process.platform;
1849
+ const pipePrefix = isWindows ? '\\\\.\\pipe\\' : __rspack_external_node_os_74b4b876.tmpdir();
1850
+ const pipeName = 'webpack-dev-server.sock';
1851
+ options.ipc = __rspack_external_node_path_c5b9b54f.join(pipePrefix, pipeName);
1852
+ }
1853
+ options.liveReload = void 0 !== options.liveReload ? options.liveReload : true;
1854
+ const defaultOpenOptions = {
1855
+ wait: false
1856
+ };
1857
+ const getOpenItemsFromObject = ({ target, ...rest })=>{
1858
+ const normalizedOptions = {
1859
+ ...defaultOpenOptions,
1860
+ ...rest
1861
+ };
1862
+ if ('string' == typeof normalizedOptions.app) normalizedOptions.app = {
1863
+ name: normalizedOptions.app
1864
+ };
1865
+ const normalizedTarget = void 0 === target ? '<url>' : target;
1866
+ if (Array.isArray(normalizedTarget)) return normalizedTarget.map((singleTarget)=>({
1867
+ target: singleTarget,
1868
+ options: normalizedOptions
1869
+ }));
1870
+ return [
1871
+ {
1872
+ target: normalizedTarget,
1873
+ options: normalizedOptions
1874
+ }
1875
+ ];
1876
+ };
1877
+ let normalizedOpens = [];
1878
+ if (void 0 === options.open) ;
1879
+ else if ('boolean' == typeof options.open) {
1880
+ if (options.open) normalizedOpens = [
1881
+ {
1882
+ target: '<url>',
1883
+ options: defaultOpenOptions
1884
+ }
1885
+ ];
1886
+ } else if ('string' == typeof options.open) normalizedOpens = [
1887
+ {
1888
+ target: options.open,
1889
+ options: defaultOpenOptions
1890
+ }
1891
+ ];
1892
+ else if (Array.isArray(options.open)) for (const item of options.open){
1893
+ if ('string' == typeof item) {
1894
+ normalizedOpens.push({
1895
+ target: item,
1896
+ options: defaultOpenOptions
1897
+ });
1898
+ continue;
1899
+ }
1900
+ normalizedOpens.push(...getOpenItemsFromObject(item));
1901
+ }
1902
+ else normalizedOpens = [
1903
+ ...getOpenItemsFromObject(options.open)
1904
+ ];
1905
+ options.open = normalizedOpens;
1906
+ if ('string' == typeof options.port && 'auto' !== options.port) options.port = Number(options.port);
1907
+ if (void 0 === options.setupExitSignals) options.setupExitSignals = true;
1908
+ if (void 0 === options.static) options.static = [
1909
+ getStaticItem()
1910
+ ];
1911
+ else if ('boolean' == typeof options.static) options.static = options.static ? [
1912
+ getStaticItem()
1913
+ ] : false;
1914
+ else if ('string' == typeof options.static) options.static = [
1915
+ getStaticItem(options.static)
1916
+ ];
1917
+ else if (Array.isArray(options.static)) options.static = options.static.map((item)=>getStaticItem(item));
1918
+ else options.static = [
1919
+ getStaticItem(options.static)
1920
+ ];
1921
+ if ('string' == typeof options.watchFiles) options.watchFiles = [
1922
+ {
1923
+ paths: options.watchFiles,
1924
+ options: getWatchOptions()
1925
+ }
1926
+ ];
1927
+ else if ('object' != typeof options.watchFiles || null === options.watchFiles || Array.isArray(options.watchFiles)) if (Array.isArray(options.watchFiles)) options.watchFiles = options.watchFiles.map((item)=>{
1928
+ if ('string' == typeof item) return {
1929
+ paths: item,
1930
+ options: getWatchOptions()
1931
+ };
1932
+ return {
1933
+ paths: item.paths,
1934
+ options: getWatchOptions(item.options || {})
1935
+ };
1936
+ });
1937
+ else options.watchFiles = [];
1938
+ else options.watchFiles = [
1939
+ {
1940
+ paths: options.watchFiles.paths,
1941
+ options: getWatchOptions(options.watchFiles.options || {})
1942
+ }
1943
+ ];
1944
+ const defaultWebSocketServerType = 'ws';
1945
+ const defaultWebSocketServerOptions = {
1946
+ path: '/ws'
1947
+ };
1948
+ if (void 0 === options.webSocketServer) options.webSocketServer = {
1949
+ type: defaultWebSocketServerType,
1950
+ options: defaultWebSocketServerOptions
1951
+ };
1952
+ else if ('boolean' != typeof options.webSocketServer || options.webSocketServer) if ('string' == typeof options.webSocketServer || 'function' == typeof options.webSocketServer) options.webSocketServer = {
1953
+ type: options.webSocketServer,
1954
+ options: defaultWebSocketServerOptions
1955
+ };
1956
+ else {
1957
+ options.webSocketServer = {
1958
+ type: options.webSocketServer.type || defaultWebSocketServerType,
1959
+ options: {
1960
+ ...defaultWebSocketServerOptions,
1961
+ ...options.webSocketServer.options
1962
+ }
1963
+ };
1964
+ const webSocketServer = options.webSocketServer;
1965
+ if ('string' == typeof webSocketServer.options.port) webSocketServer.options.port = Number(webSocketServer.options.port);
1966
+ }
1967
+ else options.webSocketServer = false;
1968
+ }
1969
+ #getClientTransport() {
1970
+ let clientImplementation;
1971
+ let clientImplementationFound = true;
1972
+ let clientTransport = 'object' == typeof this.options.client && null !== this.options.client && void 0 !== this.options.client.webSocketTransport ? this.options.client.webSocketTransport : 'ws';
1973
+ switch(typeof clientTransport){
1974
+ case 'string':
1975
+ if ('sockjs' === clientTransport) throw new Error("SockJS support has been removed. Please set client.webSocketTransport to 'ws' or provide a custom transport implementation path.");
1976
+ if ('ws' === clientTransport) clientImplementation = server_require.resolve('../client/clients/WebSocketClient');
1977
+ else try {
1978
+ clientImplementation = server_require.resolve(clientTransport);
1979
+ } catch {
1980
+ clientImplementationFound = false;
1981
+ }
1982
+ break;
1983
+ default:
1984
+ clientImplementationFound = false;
1985
+ }
1986
+ if (!clientImplementationFound) throw new Error("client.webSocketTransport must be a string denoting a default implementation (e.g. 'ws') or a full path to a JS file via require.resolve(...) which exports a class ");
1987
+ return clientImplementation;
1988
+ }
1989
+ #getServerTransport() {
1990
+ let implementation;
1991
+ let implementationFound = true;
1992
+ switch(typeof this.options.webSocketServer.type){
1993
+ case 'string':
1994
+ if ('sockjs' === this.options.webSocketServer.type) throw new Error("SockJS support has been removed. Please set webSocketServer to 'ws' or provide a custom WebSocket server implementation.");
1995
+ if ('ws' === this.options.webSocketServer.type) implementation = WebsocketServer;
1996
+ else try {
1997
+ implementation = server_require(this.options.webSocketServer.type);
1998
+ } catch {
1999
+ implementationFound = false;
2000
+ }
2001
+ break;
2002
+ case 'function':
2003
+ implementation = this.options.webSocketServer.type;
2004
+ break;
2005
+ default:
2006
+ implementationFound = false;
2007
+ }
2008
+ if (!implementationFound) throw new Error("webSocketServer (webSocketServer.type) must be a string denoting a default implementation (e.g. 'ws'), a full path to a JS file which exports a class extending BaseServer (webpack-dev-server/lib/servers/BaseServer.js) via require.resolve(...), or the class itself which extends BaseServer");
2009
+ return implementation;
2010
+ }
2011
+ getClientEntry() {
2012
+ return server_require.resolve('@rspack/dev-server/client/index');
2013
+ }
2014
+ getClientHotEntry() {
2015
+ if ('only' === this.options.hot) return server_require.resolve('@rspack/core/hot/only-dev-server');
2016
+ if (this.options.hot) return server_require.resolve('@rspack/core/hot/dev-server');
2017
+ }
2018
+ #setupProgressPlugin() {
2019
+ const { ProgressPlugin } = this.compiler.compilers ? this.compiler.compilers[0].webpack : this.compiler.webpack;
2020
+ new ProgressPlugin((percent, msg)=>{
2021
+ const percentValue = Math.floor(100 * percent);
2022
+ let msgValue = msg;
2023
+ if (100 === percentValue) msgValue = 'Compilation completed';
2024
+ const payload = {
2025
+ percent: percentValue,
2026
+ msg: msgValue
2027
+ };
2028
+ if (this.webSocketServer) this.sendMessage(this.webSocketServer.clients, 'progress-update', payload);
2029
+ if (this.server) this.server.emit('progress-update', payload);
2030
+ }).apply(this.compiler);
2031
+ }
2032
+ async #initialize() {
2033
+ const compilers = isMultiCompiler(this.compiler) ? this.compiler.compilers : [
2034
+ this.compiler
2035
+ ];
2036
+ for (const compiler of compilers){
2037
+ const mode = compiler.options.mode || process.env.NODE_ENV;
2038
+ if (this.options.hot) {
2039
+ if ('production' === mode) this.logger.warn("Hot Module Replacement (HMR) is enabled for the production build. \nMake sure to disable HMR for production by setting `devServer.hot` to `false` in the configuration.");
2040
+ compiler.options.resolve.alias = {
2041
+ 'ansi-html-community': server_require.resolve('@rspack/dev-server/client/utils/ansiHTML'),
2042
+ ...compiler.options.resolve.alias
2043
+ };
2044
+ }
2045
+ }
2046
+ this.#setupHooks();
2047
+ await this.#setupApp();
2048
+ await this.#createServer();
2049
+ if (this.options.webSocketServer) {
2050
+ const compilers = this.compiler.compilers || [
2051
+ this.compiler
2052
+ ];
2053
+ for (const compiler of compilers){
2054
+ if (false === compiler.options.devServer) continue;
2055
+ this.#addAdditionalEntries(compiler);
2056
+ const { ProvidePlugin, HotModuleReplacementPlugin } = compiler.rspack;
2057
+ new ProvidePlugin({
2058
+ __rspack_dev_server_client__: this.#getClientTransport()
2059
+ }).apply(compiler);
2060
+ if (this.options.hot) {
2061
+ const HMRPluginExists = compiler.options.plugins.find((plugin)=>plugin && plugin.constructor === HotModuleReplacementPlugin);
2062
+ if (HMRPluginExists) this.logger.warn('"hot: true" automatically applies HMR plugin, you don\'t have to add it manually to your webpack configuration.');
2063
+ else {
2064
+ const plugin = new HotModuleReplacementPlugin();
2065
+ plugin.apply(compiler);
2066
+ }
2067
+ }
2068
+ }
2069
+ if (this.options.client && this.options.client.progress) this.#setupProgressPlugin();
2070
+ }
2071
+ await this.#setupWatchFiles();
2072
+ await this.#setupWatchStaticFiles();
2073
+ await this.#setupMiddlewares();
2074
+ if (this.options.setupExitSignals) {
2075
+ const signals = [
2076
+ 'SIGINT',
2077
+ 'SIGTERM'
2078
+ ];
2079
+ let needForceShutdown = false;
2080
+ for (const signal of signals){
2081
+ const listener = ()=>{
2082
+ if (needForceShutdown) process.exit();
2083
+ this.logger.info('Gracefully shutting down. Press ^C again to force exit...');
2084
+ needForceShutdown = true;
2085
+ this.stopCallback(()=>{
2086
+ if ('function' == typeof this.compiler.close) this.compiler.close(()=>{
2087
+ process.exit();
2088
+ });
2089
+ else process.exit();
2090
+ });
2091
+ };
2092
+ this.listeners.push({
2093
+ name: signal,
2094
+ listener
2095
+ });
2096
+ process.on(signal, listener);
2097
+ }
2098
+ }
2099
+ const webSocketProxies = this.webSocketProxies;
2100
+ for (const webSocketProxy of webSocketProxies)this.server.on('upgrade', webSocketProxy.upgrade);
2101
+ }
2102
+ async #setupApp() {
2103
+ this.app = 'function' == typeof this.options.app ? await this.options.app() : (await getConnect())();
2104
+ }
2105
+ #getStats(statsObj) {
2106
+ const stats = Server.DEFAULT_STATS;
2107
+ const compilerOptions = this.#getCompilerOptions();
2108
+ if (compilerOptions.stats && compilerOptions.stats.warningsFilter) stats.warningsFilter = compilerOptions.stats.warningsFilter;
2109
+ return statsObj.toJson(stats);
2110
+ }
2111
+ #setupHooks() {
2112
+ this.compiler.hooks.invalid.tap('rspack-dev-server', ()=>{
2113
+ if (this.webSocketServer) this.sendMessage(this.webSocketServer.clients, 'invalid');
2114
+ });
2115
+ this.compiler.hooks.done.tap('rspack-dev-server', (stats)=>{
2116
+ if (this.webSocketServer) this.#sendStats(this.webSocketServer.clients, this.#getStats(stats));
2117
+ this.stats = stats;
2118
+ });
2119
+ }
2120
+ async #setupWatchStaticFiles() {
2121
+ const watchFiles = this.options.static;
2122
+ if (watchFiles.length > 0) {
2123
+ for (const item of watchFiles)if (item.watch) await this.watchFiles(item.directory, item.watch);
2124
+ }
2125
+ }
2126
+ async #setupWatchFiles() {
2127
+ const watchFiles = this.options.watchFiles;
2128
+ if (watchFiles.length > 0) for (const item of watchFiles)await this.watchFiles(item.paths, item.options);
2129
+ }
2130
+ async #setupMiddlewares() {
2131
+ let middlewares = [];
2132
+ middlewares.push({
2133
+ name: 'host-header-check',
2134
+ middleware: (req, res, next)=>{
2135
+ const headers = req.headers;
2136
+ const headerName = headers[':authority'] ? ':authority' : 'host';
2137
+ if (this.isValidHost(headers, headerName)) return void next();
2138
+ res.statusCode = 403;
2139
+ res.end('Invalid Host header');
2140
+ }
2141
+ });
2142
+ middlewares.push({
2143
+ name: 'cross-origin-header-check',
2144
+ middleware: (req, res, next)=>{
2145
+ const headers = req.headers;
2146
+ const headerName = headers[':authority'] ? ':authority' : 'host';
2147
+ if (this.isValidHost(headers, headerName, false)) return void next();
2148
+ if ('no-cors' === headers['sec-fetch-mode'] && 'cross-site' === headers['sec-fetch-site']) {
2149
+ res.statusCode = 403;
2150
+ res.end('Cross-Origin request blocked');
2151
+ return;
2152
+ }
2153
+ next();
2154
+ }
2155
+ });
2156
+ const isHTTP2 = 'http2' === this.options.server.type;
2157
+ if (isHTTP2) middlewares.push({
2158
+ name: 'http2-status-message-patch',
2159
+ middleware: (_req, res, next)=>{
2160
+ Object.defineProperty(res, 'statusMessage', {
2161
+ get () {
2162
+ return '';
2163
+ },
2164
+ set () {}
2165
+ });
2166
+ next();
2167
+ }
2168
+ });
2169
+ if (this.options.compress) middlewares.push({
2170
+ name: 'compression',
2171
+ middleware: src_default()()
2172
+ });
2173
+ if (void 0 !== this.options.headers) middlewares.push({
2174
+ name: 'set-headers',
2175
+ middleware: this.#setHeaders.bind(this)
2176
+ });
2177
+ middlewares.push({
2178
+ name: '@rspack/dev-middleware',
2179
+ middleware: this.middleware
2180
+ });
2181
+ middlewares.push({
2182
+ name: 'rspack-dev-server-invalidate',
2183
+ path: '/rspack-dev-server/invalidate',
2184
+ middleware: (req, res, next)=>{
2185
+ if ('GET' !== req.method && 'HEAD' !== req.method) return void next();
2186
+ this.invalidate();
2187
+ res.end();
2188
+ }
2189
+ });
2190
+ middlewares.push({
2191
+ name: 'rspack-dev-server-open-editor',
2192
+ path: '/rspack-dev-server/open-editor',
2193
+ middleware: async (req, res, next)=>{
2194
+ if ('GET' !== req.method && 'HEAD' !== req.method) return void next();
2195
+ if (!req.url) return void next();
2196
+ const resolveUrl = new URL(req.url, `http://${req.headers.host}`);
2197
+ const params = new URLSearchParams(resolveUrl.search);
2198
+ const fileName = params.get('fileName');
2199
+ if ('string' == typeof fileName) {
2200
+ const { default: launchEditor } = await import("./0~launch-editor.js").then(__webpack_require__.t.bind(__webpack_require__, "./node_modules/.pnpm/launch-editor@2.13.2/node_modules/launch-editor/index.js", 23));
2201
+ launchEditor(fileName);
2202
+ }
2203
+ res.end();
2204
+ }
2205
+ });
2206
+ middlewares.push({
2207
+ name: 'rspack-dev-server-assets',
2208
+ path: '/rspack-dev-server',
2209
+ middleware: (req, res, next)=>{
2210
+ if ('GET' !== req.method && 'HEAD' !== req.method) return void next();
2211
+ if (!this.middleware) return void next();
2212
+ this.middleware.waitUntilValid((stats)=>{
2213
+ res.setHeader('Content-Type', 'text/html; charset=utf-8');
2214
+ if ('HEAD' === req.method) return void res.end();
2215
+ res.write('<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body>');
2216
+ const statsForPrint = void 0 !== stats.stats ? stats.toJson({
2217
+ assets: true
2218
+ }).children : [
2219
+ stats.toJson({
2220
+ assets: true
2221
+ })
2222
+ ];
2223
+ res.write('<h1>Assets Report:</h1>');
2224
+ for (const [index, item] of statsForPrint?.entries() ?? []){
2225
+ res.write('<div>');
2226
+ const name = void 0 !== item.name ? item.name : stats.stats ? `unnamed[${index}]` : 'unnamed';
2227
+ res.write(`<h2>Compilation: ${name}</h2>`);
2228
+ res.write('<ul>');
2229
+ const publicPath = 'auto' === item.publicPath ? '' : item.publicPath;
2230
+ const assets = item.assets;
2231
+ for (const asset of assets ?? []){
2232
+ const assetName = asset.name;
2233
+ const assetURL = `${publicPath}${assetName}`;
2234
+ res.write(`<li>
2235
+ <strong><a href="${assetURL}" target="_blank">${assetName}</a></strong>
2236
+ </li>`);
2237
+ }
2238
+ res.write('</ul>');
2239
+ res.write('</div>');
2240
+ }
2241
+ res.end('</body></html>');
2242
+ });
2243
+ }
2244
+ });
2245
+ if (this.options.proxy) {
2246
+ const { createProxyMiddleware } = server_require('http-proxy-middleware');
2247
+ const getProxyMiddleware = (proxyConfig)=>{
2248
+ const { context, ...proxyOptions } = proxyConfig;
2249
+ const pathFilter = proxyOptions.pathFilter ?? context;
2250
+ if (void 0 !== pathFilter) proxyOptions.pathFilter = pathFilter;
2251
+ if (void 0 === proxyOptions.logger) proxyOptions.logger = this.logger;
2252
+ if (proxyOptions.target || proxyOptions.router) return createProxyMiddleware(proxyOptions);
2253
+ __rspack_external_node_util_1b29d436.deprecate(()=>{}, `Invalid proxy configuration:\n\n${JSON.stringify(proxyConfig, null, 2)}\n\nThe use of proxy object notation as proxy routes has been removed.\nPlease use the 'router' or 'context' options. Read more at https://github.com/chimurai/http-proxy-middleware`, 'DEP_WEBPACK_DEV_SERVER_PROXY_ROUTES_ARGUMENT')();
2254
+ };
2255
+ for (const proxyConfigOrCallback of this.options.proxy){
2256
+ let proxyMiddleware;
2257
+ let proxyConfig = 'function' == typeof proxyConfigOrCallback ? proxyConfigOrCallback() : proxyConfigOrCallback;
2258
+ proxyMiddleware = getProxyMiddleware(proxyConfig);
2259
+ if (proxyConfig.ws && proxyMiddleware) this.webSocketProxies.push(proxyMiddleware);
2260
+ const handler = async (req, res, next)=>{
2261
+ if ('function' == typeof proxyConfigOrCallback) {
2262
+ const newProxyConfig = proxyConfigOrCallback(req, res, next);
2263
+ if (newProxyConfig !== proxyConfig) {
2264
+ proxyConfig = newProxyConfig;
2265
+ const socket = req.socket || req.connection;
2266
+ const server = socket ? socket.server : null;
2267
+ if (server) server.removeAllListeners('close');
2268
+ proxyMiddleware = getProxyMiddleware(proxyConfig);
2269
+ }
2270
+ }
2271
+ if (proxyMiddleware) return proxyMiddleware(req, res, next);
2272
+ next();
2273
+ };
2274
+ middlewares.push({
2275
+ name: 'http-proxy-middleware',
2276
+ middleware: handler
2277
+ });
2278
+ middlewares.push({
2279
+ name: 'http-proxy-middleware-error-handler',
2280
+ middleware: (error, req, res, next)=>handler(req, res, next)
2281
+ });
2282
+ }
2283
+ middlewares.push({
2284
+ name: '@rspack/dev-middleware',
2285
+ middleware: this.middleware
2286
+ });
2287
+ }
2288
+ const staticOptions = this.options.static;
2289
+ const useStatic = staticOptions.length > 0;
2290
+ const serveStatic = useStatic ? (await import("./0~serve-static.js").then(__webpack_require__.t.bind(__webpack_require__, "./node_modules/.pnpm/serve-static@2.2.1/node_modules/serve-static/index.js", 23))).default : null;
2291
+ if (useStatic) for (const staticOption of staticOptions)for (const publicPath of staticOption.publicPath)middlewares.push({
2292
+ name: 'serve-static',
2293
+ path: publicPath,
2294
+ middleware: serveStatic(staticOption.directory, staticOption.staticOptions)
2295
+ });
2296
+ if (this.options.historyApiFallback) {
2297
+ const connectHistoryApiFallback = server_require('connect-history-api-fallback');
2298
+ const { historyApiFallback } = this.options;
2299
+ if (void 0 === historyApiFallback && !historyApiFallback.verbose) historyApiFallback.logger = this.logger.log.bind(this.logger, '[connect-history-api-fallback]');
2300
+ middlewares.push({
2301
+ name: 'connect-history-api-fallback',
2302
+ middleware: connectHistoryApiFallback(historyApiFallback)
2303
+ });
2304
+ middlewares.push({
2305
+ name: '@rspack/dev-middleware',
2306
+ middleware: this.middleware
2307
+ });
2308
+ if (useStatic) for (const staticOption of staticOptions)for (const publicPath of staticOption.publicPath)middlewares.push({
2309
+ name: 'serve-static',
2310
+ path: publicPath,
2311
+ middleware: serveStatic(staticOption.directory, staticOption.staticOptions)
2312
+ });
2313
+ }
2314
+ middlewares.push({
2315
+ name: 'options-middleware',
2316
+ middleware: (req, res, next)=>{
2317
+ if ('OPTIONS' === req.method) {
2318
+ res.statusCode = 204;
2319
+ res.setHeader('Content-Length', '0');
2320
+ res.end();
2321
+ return;
2322
+ }
2323
+ next();
2324
+ }
2325
+ });
2326
+ if ('function' == typeof this.options.setupMiddlewares) middlewares = this.options.setupMiddlewares(middlewares, this);
2327
+ const lazyInitDevMiddleware = ()=>{
2328
+ if (!this.middleware) this.middleware = devMiddleware(this.compiler, this.options.devMiddleware);
2329
+ return this.middleware;
2330
+ };
2331
+ for (const i of middlewares)if ('@rspack/dev-middleware' === i.name) {
2332
+ const item = i;
2333
+ if (void 0 === item.middleware) item.middleware = lazyInitDevMiddleware();
2334
+ }
2335
+ for (const middleware of middlewares)if ('function' == typeof middleware) this.app.use(middleware);
2336
+ else if (void 0 !== middleware.path) this.app.use(middleware.path, middleware.middleware);
2337
+ else this.app.use(middleware.middleware);
2338
+ }
2339
+ async #createServer() {
2340
+ const { type, options } = this.options.server;
2341
+ if ('function' == typeof type) this.server = await type(options, this.app);
2342
+ else {
2343
+ const serverType = server_require(type);
2344
+ this.server = 'http2' === type ? serverType.createSecureServer({
2345
+ ...options,
2346
+ allowHTTP1: true
2347
+ }, this.app) : serverType.createServer(options, this.app);
2348
+ }
2349
+ this.isTlsServer = void 0 !== this.server.setSecureContext;
2350
+ this.server.on('connection', (socket)=>{
2351
+ this.sockets.push(socket);
2352
+ socket.once('close', ()=>{
2353
+ this.sockets.splice(this.sockets.indexOf(socket), 1);
2354
+ });
2355
+ });
2356
+ this.server.on('error', (error)=>{
2357
+ throw error;
2358
+ });
2359
+ }
2360
+ #createWebSocketServer() {
2361
+ this.webSocketServer = new (this.#getServerTransport())(this);
2362
+ (this.webSocketServer?.implementation).on('connection', (client, request)=>{
2363
+ const headers = void 0 !== request ? request.headers : void 0;
2364
+ if (!headers) this.logger.warn('webSocketServer implementation must pass headers for the "connection" event');
2365
+ if (!headers || !this.isValidHost(headers, 'host') || !this.isValidHost(headers, 'origin') || !this.#isSameOrigin(headers)) {
2366
+ this.sendMessage([
2367
+ client
2368
+ ], 'error', 'Invalid Host/Origin header');
2369
+ client.close();
2370
+ return;
2371
+ }
2372
+ if (true === this.options.hot || 'only' === this.options.hot) this.sendMessage([
2373
+ client
2374
+ ], 'hot');
2375
+ if (this.options.liveReload) this.sendMessage([
2376
+ client
2377
+ ], 'liveReload');
2378
+ if (this.options.client && this.options.client.progress) this.sendMessage([
2379
+ client
2380
+ ], 'progress', this.options.client.progress);
2381
+ if (this.options.client && this.options.client.reconnect) this.sendMessage([
2382
+ client
2383
+ ], 'reconnect', this.options.client.reconnect);
2384
+ if (this.options.client && this.options.client.overlay) {
2385
+ const overlayConfig = this.options.client.overlay;
2386
+ this.sendMessage([
2387
+ client
2388
+ ], 'overlay', 'object' == typeof overlayConfig ? {
2389
+ ...overlayConfig,
2390
+ errors: overlayConfig.errors && encodeOverlaySettings(overlayConfig.errors),
2391
+ warnings: overlayConfig.warnings && encodeOverlaySettings(overlayConfig.warnings),
2392
+ runtimeErrors: overlayConfig.runtimeErrors && encodeOverlaySettings(overlayConfig.runtimeErrors)
2393
+ } : overlayConfig);
2394
+ }
2395
+ if (!this.stats) return;
2396
+ this.#sendStats([
2397
+ client
2398
+ ], this.#getStats(this.stats), true);
2399
+ });
2400
+ }
2401
+ async #openBrowser(defaultOpenTarget) {
2402
+ const { default: open } = await import("./0~open.js");
2403
+ Promise.all(this.options.open.map((item)=>{
2404
+ let openTarget;
2405
+ openTarget = '<url>' === item.target ? defaultOpenTarget : Server.isAbsoluteURL(item.target) ? item.target : new URL(item.target, defaultOpenTarget).toString();
2406
+ return open(openTarget, item.options).catch(()=>{
2407
+ const app = item.options.app;
2408
+ this.logger.warn(`Unable to open "${openTarget}" page${app ? ` in "${app.name}" app${app.arguments ? ` with "${app.arguments.join(' ')}" arguments` : ''}` : ''}. If you are running in a headless environment, please do not use the "open" option or related flags like "--open", "--open-target", and "--open-app-name".`);
2409
+ });
2410
+ }));
2411
+ }
2412
+ async #logStatus() {
2413
+ const server = this.server;
2414
+ if (this.options.ipc) this.logger.info(`Project is running at: "${server?.address()}"`);
2415
+ else {
2416
+ const protocol = this.isTlsServer ? 'https' : 'http';
2417
+ const addressInfo = server?.address();
2418
+ if (!addressInfo) return;
2419
+ const { address, port } = addressInfo;
2420
+ const prettyPrintURL = (newHostname)=>__rspack_external_node_url_e96de089.format({
2421
+ protocol,
2422
+ hostname: newHostname,
2423
+ port,
2424
+ pathname: '/'
2425
+ });
2426
+ let localhost;
2427
+ let loopbackIPv4;
2428
+ let loopbackIPv6;
2429
+ let networkUrlIPv4;
2430
+ let networkUrlIPv6;
2431
+ if ('localhost' === this.options.host) localhost = prettyPrintURL('localhost');
2432
+ const parsedIP = ipaddr_default().parse(address);
2433
+ if ('unspecified' === parsedIP.range()) {
2434
+ localhost = prettyPrintURL('localhost');
2435
+ loopbackIPv6 = prettyPrintURL('::1');
2436
+ const networkIPv4 = Server.findIp('v4', false);
2437
+ if (networkIPv4) networkUrlIPv4 = prettyPrintURL(networkIPv4);
2438
+ const networkIPv6 = Server.findIp('v6', false);
2439
+ if (networkIPv6) networkUrlIPv6 = prettyPrintURL(networkIPv6);
2440
+ } else if ('loopback' === parsedIP.range()) {
2441
+ if ('ipv4' === parsedIP.kind()) loopbackIPv4 = prettyPrintURL(parsedIP.toString());
2442
+ else if ('ipv6' === parsedIP.kind()) loopbackIPv6 = prettyPrintURL(parsedIP.toString());
2443
+ } else {
2444
+ networkUrlIPv4 = 'ipv6' === parsedIP.kind() && parsedIP.isIPv4MappedAddress() ? prettyPrintURL(parsedIP.toIPv4Address().toString()) : prettyPrintURL(address);
2445
+ if ('ipv6' === parsedIP.kind()) networkUrlIPv6 = prettyPrintURL(address);
2446
+ }
2447
+ const urlLogs = [];
2448
+ const local = localhost || loopbackIPv4 || loopbackIPv6;
2449
+ if (local) urlLogs.push(` ${styleText('white', '➜')} ${styleText([
2450
+ 'white',
2451
+ 'dim'
2452
+ ], 'Local:')} ${styleText('cyan', local)}`);
2453
+ if (networkUrlIPv4) urlLogs.push(` ${styleText('white', '➜')} ${styleText([
2454
+ 'white',
2455
+ 'dim'
2456
+ ], 'Network:')} ${styleText('cyan', networkUrlIPv4)}`);
2457
+ else if (networkUrlIPv6) urlLogs.push(` ${styleText('white', '➜')} ${styleText([
2458
+ 'white',
2459
+ 'dim'
2460
+ ], 'Network:')} ${styleText('cyan', networkUrlIPv6)}`);
2461
+ if (urlLogs.length && this.#shouldLogInfrastructureInfo()) console.log(`${urlLogs.join('\n')}\n`);
2462
+ if (this.options.open?.length > 0) {
2463
+ const openTarget = prettyPrintURL(this.options.host && '0.0.0.0' !== this.options.host && '::' !== this.options.host ? this.options.host : 'localhost');
2464
+ await this.#openBrowser(openTarget);
2465
+ }
2466
+ }
2467
+ }
2468
+ #setHeaders(req, res, next) {
2469
+ let { headers } = this.options;
2470
+ if (headers) {
2471
+ if ('function' == typeof headers) headers = headers(req, res, this.middleware ? this.middleware.context : void 0);
2472
+ const allHeaders = [];
2473
+ if (!Array.isArray(headers)) {
2474
+ for(const name in headers)allHeaders.push({
2475
+ key: name,
2476
+ value: headers[name]
2477
+ });
2478
+ headers = allHeaders;
2479
+ }
2480
+ for (const { key, value } of headers)res.setHeader(key, value);
2481
+ }
2482
+ next();
2483
+ }
2484
+ #isHostAllowed(value) {
2485
+ const { allowedHosts } = this.options;
2486
+ if ('all' === allowedHosts) return true;
2487
+ if (Array.isArray(allowedHosts) && allowedHosts.length > 0) for (const allowedHost of allowedHosts){
2488
+ if (allowedHost === value) return true;
2489
+ if (allowedHost.startsWith('.') && (value === allowedHost.slice(1) || value.endsWith(allowedHost))) return true;
2490
+ }
2491
+ if (this.options.client && void 0 !== this.options.client.webSocketURL) return this.options.client.webSocketURL === value;
2492
+ return false;
2493
+ }
2494
+ isValidHost(headers, headerToCheck, validateHost = true) {
2495
+ if ('all' === this.options.allowedHosts) return true;
2496
+ const header = headers[headerToCheck];
2497
+ if (!header) return false;
2498
+ if (DEFAULT_ALLOWED_PROTOCOLS.test(header)) return true;
2499
+ const hostname = parseHostnameFromHeader(header);
2500
+ if (null === hostname) return false;
2501
+ if (this.#isHostAllowed(hostname)) return true;
2502
+ const isValidHostname = validateHost ? ipaddr_default().IPv4.isValid(hostname) || ipaddr_default().IPv6.isValid(hostname) || 'localhost' === hostname || hostname.endsWith('.localhost') || hostname === this.options.host : false;
2503
+ return isValidHostname;
2504
+ }
2505
+ #isSameOrigin(headers) {
2506
+ if ('all' === this.options.allowedHosts) return true;
2507
+ const originHeader = headers.origin;
2508
+ if (!originHeader) return 'all' === this.options.allowedHosts;
2509
+ if (DEFAULT_ALLOWED_PROTOCOLS.test(originHeader)) return true;
2510
+ const origin = parseHostnameFromHeader(originHeader);
2511
+ if (null === origin) return false;
2512
+ if (this.#isHostAllowed(origin)) return true;
2513
+ const hostHeader = headers.host;
2514
+ if (!hostHeader) return 'all' === this.options.allowedHosts;
2515
+ if (DEFAULT_ALLOWED_PROTOCOLS.test(hostHeader)) return true;
2516
+ const host = parseHostnameFromHeader(hostHeader);
2517
+ if (null === host) return false;
2518
+ if (this.#isHostAllowed(host)) return true;
2519
+ return origin === host;
2520
+ }
2521
+ sendMessage(clients, type, data, params) {
2522
+ for (const client of clients)if (1 === client.readyState) client.send(JSON.stringify({
2523
+ type,
2524
+ data,
2525
+ params
2526
+ }));
2527
+ }
2528
+ #sendStats(clients, stats, force) {
2529
+ if (!stats) return;
2530
+ const shouldEmit = !force && stats && (!stats.errors || 0 === stats.errors.length) && (!stats.warnings || 0 === stats.warnings.length) && this.currentHash === stats.hash;
2531
+ if (shouldEmit) return void this.sendMessage(clients, 'still-ok');
2532
+ this.currentHash = stats.hash;
2533
+ this.sendMessage(clients, 'hash', stats.hash);
2534
+ if (stats.errors?.length > 0 || stats.warnings?.length > 0) {
2535
+ const hasErrors = stats.errors?.length > 0;
2536
+ if (stats.warnings?.length > 0) {
2537
+ let params;
2538
+ if (hasErrors) params = {
2539
+ preventReloading: true
2540
+ };
2541
+ this.sendMessage(clients, 'warnings', stats.warnings, params);
2542
+ }
2543
+ if (stats.errors?.length > 0) this.sendMessage(clients, 'errors', stats.errors);
2544
+ } else this.sendMessage(clients, 'ok');
2545
+ }
2546
+ async watchFiles(watchPath, watchOptions) {
2547
+ const { watch } = await getChokidar();
2548
+ const watcher = watch(watchPath, watchOptions);
2549
+ if (this.options.liveReload) watcher.on('change', (item)=>{
2550
+ if (this.webSocketServer) this.sendMessage(this.webSocketServer.clients, 'static-changed', item);
2551
+ });
2552
+ this.staticWatchers.push(watcher);
2553
+ }
2554
+ invalidate(callback = ()=>{}) {
2555
+ if (this.middleware) this.middleware.invalidate(callback);
2556
+ }
2557
+ async start() {
2558
+ await this.#normalizeOptions();
2559
+ if (this.options.ipc) await new Promise((resolve, reject)=>{
2560
+ const net = server_require('node:net');
2561
+ const socket = new net.Socket();
2562
+ socket.on('error', (error)=>{
2563
+ if ('ECONNREFUSED' === error.code) {
2564
+ __rspack_external_node_fs_5ea92f0c.unlinkSync(this.options.ipc);
2565
+ resolve();
2566
+ return;
2567
+ }
2568
+ if ('ENOENT' === error.code) return void resolve();
2569
+ reject(error);
2570
+ });
2571
+ socket.connect({
2572
+ path: this.options.ipc
2573
+ }, ()=>{
2574
+ throw new Error(`IPC "${this.options.ipc}" is already used`);
2575
+ });
2576
+ });
2577
+ else {
2578
+ this.options.host = await Server.getHostname(this.options.host);
2579
+ this.options.port = await Server.getFreePort(this.options.port, this.options.host);
2580
+ }
2581
+ await this.#initialize();
2582
+ const listenOptions = this.options.ipc ? {
2583
+ path: this.options.ipc
2584
+ } : {
2585
+ host: this.options.host,
2586
+ port: this.options.port
2587
+ };
2588
+ await new Promise((resolve)=>{
2589
+ this.server.listen(listenOptions, ()=>{
2590
+ resolve();
2591
+ });
2592
+ });
2593
+ if (this.options.ipc) {
2594
+ const READ_WRITE = 438;
2595
+ await __rspack_external_node_fs_5ea92f0c.promises.chmod(this.options.ipc, READ_WRITE);
2596
+ }
2597
+ if (this.options.webSocketServer) this.#createWebSocketServer();
2598
+ await this.#logStatus();
2599
+ if ('function' == typeof this.options.onListening) this.options.onListening(this);
2600
+ }
2601
+ startCallback(callback = ()=>{}) {
2602
+ this.start().then(()=>callback(), callback).catch(callback);
2603
+ }
2604
+ async stop() {
2605
+ this.webSocketProxies = [];
2606
+ await Promise.all(this.staticWatchers.map((watcher)=>watcher.close()));
2607
+ this.staticWatchers = [];
2608
+ if (this.webSocketServer) await new Promise((resolve)=>{
2609
+ this.webSocketServer.implementation.close(()=>{
2610
+ this.webSocketServer = null;
2611
+ resolve();
2612
+ });
2613
+ for (const client of this.webSocketServer.clients)client.terminate();
2614
+ this.webSocketServer.clients = [];
2615
+ });
2616
+ if (this.server) {
2617
+ await new Promise((resolve)=>{
2618
+ this.server.close(()=>{
2619
+ this.server = void 0;
2620
+ resolve();
2621
+ });
2622
+ for (const socket of this.sockets)socket.destroy();
2623
+ this.sockets = [];
2624
+ });
2625
+ if (this.middleware) {
2626
+ await new Promise((resolve, reject)=>{
2627
+ this.middleware.close((error)=>{
2628
+ if (error) return void reject(error);
2629
+ resolve();
2630
+ });
2631
+ });
2632
+ this.middleware = void 0;
2633
+ }
2634
+ }
2635
+ for (const item of this.listeners)process.removeListener(item.name, item.listener);
2636
+ }
2637
+ stopCallback(callback = ()=>{}) {
2638
+ this.stop().then(()=>callback(), callback).catch(callback);
2639
+ }
2640
+ }
2641
+ export { __webpack_require__temp as __webpack_require__, Server as RspackDevServer };