Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
1368 lines (1175 loc) · 40.7 KB
/
Copy pathserver.js
File metadata and controls
1368 lines (1175 loc) · 40.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import path from "node:path";
import fs from "node:fs";
import http from "node:http";
import { Duplex } from "node:stream";
import { fileURLToPath } from "node:url";
import { createRequire } from "node:module";
import { createSecureServer } from "node:http2";
import { createServer } from "node:http";
import { Worker } from "node:worker_threads";
import WebSocket, { WebSocketServer } from "ws";
import mime from "mime";
import chokidar from "chokidar";
import { isPlainObject } from "@11ty/eleventy-utils";
import { createDebug } from "obug";
import wrapResponse from "./server/wrapResponse.js";
import ipAddress from "./server/ipAddress.js";
import StaticFiles from "./server/staticFiles.js";
import { isPortInUse, portInUseError } from "./server/portCheck.js";
import { parseClientMessage, isConnectionAllowed } from "./server/clientConnection.js";
const require = createRequire(import.meta.url);
// Built into Node 24+, and kept out of the generated types
if(!globalThis.URLPattern) {
require("urlpattern-polyfill");
}
const pkg = require("./package.json");
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const debug = createDebug("Eleventy:DevServer");
/** @import { IncomingMessage, ServerResponse } from "node:http" */
/** @import { ChokidarOptions, FSWatcher } from "chokidar" */
/**
* @typedef {(req: IncomingMessage, res: ServerResponse, next: () => unknown) => unknown} Middleware
* @typedef {string | Response | { status?: number, headers?: Record<string, string> | Headers, body?: string } | undefined | null | false} OnRequestResult
* @typedef {(context: { url: URL, pattern: URLPattern, patternGroups: Record<string, string | undefined> }) => OnRequestResult | Promise<OnRequestResult>} OnRequestHandler
* @typedef {{ info(...args: unknown[]): void, log(...args: unknown[]): void, error(...args: unknown[]): void }} Logger
* @typedef {{ id: string, type: string, data: unknown, timestamp: number }} ClientMessage
* @typedef {{ hosts: string[], localhostUrl: string, startupTime: number, version: string, options: Record<string, any> }} StartMessageData
* @typedef {{ url: string, inputPath: string, outputPath?: string, content?: string }} BuildTemplate
* @typedef {{
* files?: string[],
* subtype?: "css",
* build?: {
* templates?: BuildTemplate[],
* stylesheets?: string[],
* passthrough?: string[],
* redirects?: { from: string, to: string }[],
* outputs?: boolean,
* },
* }} ReloadEvent `build.outputs` means `templates` only holds pages whose output changed.
*/
/** @import { WrappedResponse } from "./server/wrapResponse.js" */
/** @typedef {ServerResponse & { proxyAbort(): void, isProxyAborted(): boolean }} ProxyResponse */
const DEFAULT_OPTIONS = {
/** Port to listen on, incremented if in use. */
port: /** @type {number | string} */ (8080),
/** Separate port for live reload, falsy uses `port`. */
reloadPort: /** @type {number | false} */ (false),
/** Enable live reload. */
liveReload: true,
/** Address to listen on, e.g. `0.0.0.0` for network access. */
host: "127.0.0.1",
/** List network addresses (other than localhost), defaults to on when `host` allows network access. */
showAllHosts: /** @type {boolean | undefined} */ (undefined),
/** Folder name for injected scripts. */
injectedScriptsFolder: ".11ty",
/** Number of times to try the next port if in use. */
portReassignmentRetryCount: 10,
/** Paths to a key and certificate, required for HTTPS and HTTP/2. */
https: /** @type {{ key?: string, cert?: string }} */ ({}),
/** Apply HTML changes without a full page reload. */
domDiff: true,
/** Show the server version on start. */
showVersion: false,
/** File encoding. */
encoding: /** @type {BufferEncoding} */ ("utf-8"),
/** Virtual base directory for the served files (may be set by Eleventy). */
pathPrefix: "/",
/** Globs to watch with the dev server’s own watcher. */
watch: /** @type {string[]} */ ([]),
/** Options for the dev server’s own watcher. */
chokidarOptions: /** @type {ChokidarOptions} */ ({}),
/** Watcher instance to use instead of `watch` and `chokidarOptions`. */
chokidar: /** @type {FSWatcher | undefined} */ (undefined),
/** Maps URLs to files outside the served directory. */
aliases: /** @type {Record<string, string>} */ ({}),
/** Index file for directory URLs. */
indexFileName: "index.html",
/** Cache file contents. */
useCache: false,
/** Match URLs to files by exact case, like most production servers (matters on macOS and Windows). */
caseSensitive: true,
/** Headers added to every static file response. */
headers: /** @type {Record<string, string>} */ ({}),
/** Extra hostnames allowed to connect to live reload (localhost and IP addresses always are), or `true` for any. */
allowedHosts: /** @type {string[] | true} */ ([]),
/** Run the HTTP server on a worker thread so requests stay fast during builds. */
serverThread: true,
/** Connect-style middleware, run before static files. */
middleware: /** @type {Middleware[]} */ ([]),
/**
* Returns the start message, or a falsy value for none.
* @param {StartMessageData} data
* @returns {string | false | undefined | void}
*/
messageOnStart: ({ hosts, startupTime, version, options }) => {
let hostsStr = " started";
if(Array.isArray(hosts) && hosts.length > 0) {
// TODO what happens when the cert doesn't cover non-localhost hosts?
hostsStr = ` at ${hosts.join(" or ")}`;
}
return `Server${hostsStr}${options.showVersion ? ` (v${version})` : ""}`;
},
/**
* Returns the close message, or a falsy value for none.
* @param {{ version: string, options: Record<string, any> }} data
* @returns {string | false | undefined | void}
*/
messageOnClose(data) {
return `Server closed.`;
},
/** Maps URL patterns (e.g. `/foo/:name`) to handlers that respond to matching requests. */
onRequest: /** @type {Record<string, OnRequestHandler>} */ ({}),
/** Logger (a fancier one is injected by Eleventy). */
logger: /** @type {Logger} */ ({
info: console.log,
log: console.log,
error: console.error,
}),
/**
* Called for messages sent with the client’s `sendToServer()`.
* @param {ClientMessage} message
* @returns {void}
*/
onClientMessage: function(message) {},
};
/**
* @typedef {typeof DEFAULT_OPTIONS} ResolvedOptions
* @typedef {Partial<ResolvedOptions> & {
* folder?: string,
* domdiff?: boolean,
* enabled?: boolean,
* }} DevServerOptions Old names: `folder` for `injectedScriptsFolder`, `domdiff` for `domDiff`, `enabled` for `liveReload`.
*/
// Option keys that are safe to structured-clone across to the server thread.
const THREAD_TRANSFERABLE_OPTIONS = [
"reloadPort",
"liveReload",
"injectedScriptsFolder",
"portReassignmentRetryCount",
"https",
"domDiff",
"encoding",
"pathPrefix",
"aliases",
"indexFileName",
"useCache",
"headers",
"allowedHosts",
"caseSensitive",
];
const POLITE_WEBSOCKET_CLOSE_TIMEOUT = 50; // in ms
const MAX_WORKER_RESTARTS = 5;
export default class DevServer {
#watcher;
#serverClosing;
#serverState;
#readyPromise;
#readyResolve;
#readyReject;
#portPromise;
#portResolve;
#portReject;
#staticFiles;
#worker;
#workerClosed;
#port;
#updateServer;
#threadClientCount = 0;
#workerListening = false;
#workerRestarts = 0;
#proxyResponses = new Map();
// `buildId` names the current content: new per process, bumped per reload. Clients compare
// it on reconnect to see if they missed a build—see client/reload-client.js
#serverInstanceId = crypto.randomUUID();
#buildCount = 0;
/** @type {string} */
name;
/** Directory being served. @type {string} */
dir;
/** @type {ResolvedOptions} */
options = { ...DEFAULT_OPTIONS };
/** When the server started, for the start message. @internal */
start = 0;
/**
* @param {string} name
* @param {string} dir
* @param {DevServerOptions} [options]
*/
static getServer(name, dir, options) {
return new DevServer(name, dir, options);
}
/**
* @param {string} name
* @param {string} dir Directory to serve.
* @param {DevServerOptions} [options]
*/
constructor(name, dir, options = {}) {
debug("Creating new Dev Server instance.")
this.name = name;
this.normalizeOptions(options);
// Directory to serve
if(!dir) {
throw new Error("Missing `dir` to serve.");
}
this.dir = dir;
this.#staticFiles = new StaticFiles(dir, this.options);
this.getWatcher();
this.#readyPromise = new Promise((resolve, reject) => {
this.#readyResolve = resolve;
this.#readyReject = reject;
});
this.#portPromise = new Promise((resolve, reject) => {
this.#portResolve = resolve;
this.#portReject = reject;
});
// Rejections surface through `ready()` and `getPort()`, not as unhandled rejections
this.#readyPromise.catch(() => {});
this.#portPromise.catch(() => {});
}
/** @returns {Logger} */
get logger() {
return this.options.logger;
}
/**
* Whether the HTTP server runs on a dedicated worker thread.
* @returns {boolean}
*/
get isThreaded() {
return this.options.serverThread !== false;
}
#hasUserRequestHandlers() {
return (this.options.middleware || []).length > 0;
}
get buildId() {
return `${this.#serverInstanceId}:${this.#buildCount}`;
}
/** @param {DevServerOptions} [options] */
normalizeOptions(options = {}) {
this.options = Object.assign({}, DEFAULT_OPTIONS, options);
// better names for options https://github.com/11ty/eleventy-dev-server/issues/41
if(options.folder !== undefined) {
this.options.injectedScriptsFolder = options.folder;
delete this.options.folder;
}
if(options.domdiff !== undefined) {
this.options.domDiff = options.domdiff;
delete this.options.domdiff;
}
if(options.enabled !== undefined) {
this.options.liveReload = options.enabled;
delete this.options.enabled;
}
this.options.pathPrefix = this.cleanupPathPrefix(this.options.pathPrefix);
this.#staticFiles?.setOptions(this.options);
}
/** @returns {FSWatcher} */
get watcher() {
if(this.#watcher) {
return this.#watcher;
}
debug("Watching files: %O", this.options.watch);
if(!this.options.chokidar) {
this.#watcher = chokidar.watch(this.options.watch, Object.assign({
ignoreInitial: true,
ignored: ["**/node_modules/**", ".git"],
// same values as Eleventy core
awaitWriteFinish: {
stabilityThreshold: 150,
pollInterval: 25,
},
}, this.options.chokidarOptions));
} else {
this.#watcher = this.options.chokidar;
}
this.#watcher.on("change", (path) => {
this.logger.log( `File changed: ${path} (skips build)` );
this.reloadFiles([path]);
});
this.#watcher.on("add", (path) => {
this.logger.log( `File added: ${path} (skips build)` );
this.reloadFiles([path]);
});
this.#watcher.on("unlink", (path) => {
this.logger.log( `File deleted: ${path} (skips build)` );
this.reloadFiles([path]);
});
return this.#watcher;
}
/** @internal */
getWatcher() {
// only initialize watcher if watcher via getWatcher if has targets
// this.watcher in watchFiles() is a manual workaround
if(this.options.watch.length > 0 || this.options.chokidar) {
return this.watcher;
}
}
/** @param {string[]} targets */
watchFiles(targets) {
if(Array.isArray(targets) && targets.length > 0) {
debug("Also watching: %O", targets);
this.watcher.add(targets);
}
}
/** @internal */
cleanupPathPrefix(pathPrefix) {
if(!pathPrefix || pathPrefix === "/") {
return "/";
}
if(!pathPrefix.startsWith("/")) {
pathPrefix = `/${pathPrefix}`
}
if(!pathPrefix.endsWith("/")) {
pathPrefix = `${pathPrefix}/`;
}
return pathPrefix;
}
/* Static file resolution and serving lives in `server/staticFiles.js` so that it can
* run either here or on the server thread. These stay as delegates for API compatibility. */
/**
* Maps URLs to files outside the served directory (emulated passthrough copy).
* @param {Record<string, string>} aliases
*/
setAliases(aliases) {
this.#staticFiles.setAliases(aliases);
this.#worker?.postMessage({ type: "aliases", aliases });
}
/** @internal */
matchPassthroughAlias(url) {
return this.#staticFiles.matchPassthroughAlias(url);
}
/** @internal */
isFileInDirectory(dir, file) {
return this.#staticFiles.isFileInDirectory(dir, file);
}
/** @internal */
getOutputDirFilePath(filepath, filename = "") {
return this.#staticFiles.getOutputDirFilePath(filepath, filename);
}
/** @internal */
isOutputFilePathExists(rawPath) {
return this.#staticFiles.isOutputFilePathExists(rawPath);
}
/** @internal */
mapUrlToFilePath(url) {
return this.#staticFiles.mapUrlToFilePath(url);
}
/** @internal */
augmentContentWithNotifier(content, options = {}) {
return this.#staticFiles.augmentContentWithNotifier(content, options);
}
/** @internal */
getFileContentType(filepath, res) {
return this.#staticFiles.getFileContentType(filepath, res);
}
/** @internal */
renderFile(filepath, res) {
return this.#staticFiles.renderFile(filepath, res);
}
/** @param {string} pathname @returns {string} */
getServerPath(pathname) {
return this.#staticFiles.getServerPath(pathname);
}
// This runs at the end of the middleware chain
/** @internal */
projectStaticMiddleware(req, res) {
return this.#staticFiles.serve(req, res);
}
/** @internal */
async devServerMiddleware(req, res, next) {
if(this.#serverState === "CLOSING") {
return res.end("");
}
for(let urlPatternString in this.options.onRequest) {
let fn = this.options.onRequest[urlPatternString];
let fullPath = this.getServerPath(urlPatternString);
let p = new URLPattern({ pathname: fullPath });
// request url should already include pathprefix.
let fullUrl = this.getServerUrlRaw("localhost", req.url);
let match = p.exec(fullUrl);
let u = new URL(fullUrl);
if(match) {
let result = await fn({
url: u,
pattern: p,
patternGroups: match?.pathname?.groups || {},
});
if(!result && result !== "") {
continue;
}
if(typeof result === "string") {
return res.end(result);
}
if(isPlainObject(result) || result instanceof Response) {
if(typeof result.status === "number") {
res.statusCode = result.status;
}
if(result.headers instanceof Headers) {
for(let [key, value] of result.headers.entries()) {
res.setHeader(key, value);
}
} else if(isPlainObject(result.headers)) {
let headers = /** @type {Record<string, string>} */ (result.headers);
for(let key of Object.keys(headers)) {
res.setHeader(key, headers[key]);
}
}
if(result instanceof Response) {
// no gzip/br compression here, uncompressed from fetch https://github.com/w3c/ServiceWorker/issues/339
res.removeHeader("content-encoding");
let arrayBuffer = await result.arrayBuffer();
res.setHeader("content-length", arrayBuffer.byteLength);
let buffer = Buffer.from(arrayBuffer);
return res.end(buffer);
}
return res.end(result.body || "");
}
throw new Error(`Invalid return type from \`onRequest\` pattern for ${urlPatternString}: expected string, object literal, or Response instance.`);
}
} // end onRequest
let injectedScript = this.#staticFiles.matchInjectedScript(req.url);
if(injectedScript === "reload-client.js") {
if(this.options.liveReload) {
res.setHeader("Content-Type", mime.getType("js"));
return res.end(this.#staticFiles.getReloadClientContents());
}
} else if(injectedScript === "morphdom.js") {
if(this.options.domDiff) {
res.setHeader("Content-Type", mime.getType("js"));
return res.end(this.#staticFiles.readFile(this.#staticFiles.getMorphdomPath()));
}
}
next();
}
// Injects the live reload client into HTML responses.
#transformHtml(req, res) {
return (content) => {
// check to see if this is a client fetch and not a navigation
let isXHR = req.headers["sec-fetch-mode"] && req.headers["sec-fetch-mode"] != "navigate";
if(this.options.liveReload !== false && !isXHR) {
let scriptContents = this.#staticFiles.getReloadClientContents();
let integrityHash = this.#staticFiles.sri(scriptContents);
return this.augmentContentWithNotifier(content, {
scriptContents,
integrityHash
});
}
return content;
};
}
/**
* Builds and runs the middleware chain, ending with `terminal`.
* @param {Middleware} terminal runs last, after all user middleware
*/
async #runMiddlewareChain(req, res, terminal) {
let middlewares = this.options.middleware || [];
middlewares = middlewares.slice();
// TODO because this runs at the very end of the middleware chain,
// if we move the static stuff up in the order we could use middleware to modify
// the static content in middleware!
middlewares.push(terminal);
middlewares.reverse();
// Runs very first in the middleware chain
middlewares.push(this.devServerMiddleware);
let handleError = (e) => {
this.logger.error(`Server error: ${e.message}`);
if(!res.bodyUsed) {
this.#staticFiles.sendError(req, res, 500, e.message);
}
};
let bound = [];
let next;
for(let ware of middlewares) {
let wareNext = next;
// Middleware call `next()` without awaiting it, so each one catches its own errors
let fn = () => {
try {
let result = /** @type {any} */ (ware.call(this, req, res, wareNext));
return typeof result?.catch === "function" ? result.catch(handleError) : result;
} catch(e) {
handleError(e);
}
};
bound.push(fn);
next = fn;
}
bound.reverse();
let [first] = bound;
await first();
}
/** @internal */
async onRequestHandler (req, res) {
res = wrapResponse(res, this.#transformHtml(req, res));
await this.#runMiddlewareChain(req, res, this.projectStaticMiddleware);
}
/* ---------------------------------------------------------------------- *
* Server thread
* ---------------------------------------------------------------------- */
#startWorker(port) {
let options = {};
for(let key of THREAD_TRANSFERABLE_OPTIONS) {
options[key] = this.options[key];
}
this.#worker = new Worker(new URL("./server/serverThread.js", import.meta.url), {
workerData: {
dir: this.dir,
options,
onRequestPatterns: Object.keys(this.options.onRequest || {}),
hasMiddleware: this.#hasUserRequestHandlers(),
// Eleventy may call setAliases() before serve()
passthroughAliases: this.#staticFiles.passthroughAliases,
port,
host: this.listenHost,
buildId: this.buildId,
},
});
let worker = this.#worker;
this.#workerListening = false;
worker.on("message", (msg) => this.#onWorkerMessage(msg));
worker.on("error", (err) => {
this.logger.error(`Server error: ${err.message}`);
});
worker.on("exit", (code) => this.#onWorkerExit(worker, code));
this.start = Date.now();
}
// Rejects `ready()` and `getPort()` so callers don't wait on a server that will never listen.
#failToStart(error) {
this.logger.error(error.message);
this.#portReject(error);
this.#readyReject(error);
}
#abortProxyResponses() {
for(let res of this.#proxyResponses.values()) {
res.proxyAbort();
}
this.#proxyResponses.clear();
}
#onWorkerExit(worker, code) {
// Exits from `close()` or a fatal startup error are expected
if(worker !== this.#worker) {
return;
}
this.#worker = undefined;
this.#abortProxyResponses();
if(this.#workerListening && this.#workerRestarts < MAX_WORKER_RESTARTS) {
this.#workerRestarts++;
this.logger.error(`Server thread exited unexpectedly (code ${code}), restarting.`);
this.#startWorker(this.#port);
return;
}
this.#failToStart(new Error(`Server thread exited unexpectedly (code ${code}).`));
}
#onWorkerMessage(msg) {
if(msg.type === "listening") {
let isRestart = this.#port !== undefined;
this.#workerListening = true;
this.#port = msg.port;
this._serverProtocol = msg.protocol;
if(!isRestart) {
this.#portResolve(msg.port);
this.logStartMessage();
this.#readyResolve();
}
} else if(msg.type === "proxyRequest") {
this.#handleProxyRequest(msg);
} else if(msg.type === "proxyAbort") {
this.#proxyResponses.get(msg.id)?.proxyAbort();
} else if(msg.type === "clientMessage") {
if(typeof this.options.onClientMessage === "function") {
this.options.onClientMessage(msg.parsed);
}
} else if(msg.type === "clientCount") {
this.#threadClientCount = msg.size;
} else if(msg.type === "log") {
this.logger[msg.level]?.(...msg.args);
} else if(msg.type === "serverError") {
this._serverErrorHandler({ code: msg.code, port: msg.port, message: msg.message });
} else if(msg.type === "fatal") {
let worker = this.#worker;
this.#worker = undefined;
worker?.terminate();
this.#failToStart(new Error(msg.message));
} else if(msg.type === "closed") {
this.#workerClosed?.();
}
}
/**
* A response object that streams everything written to it back to the server thread,
* so a request proxied from there can run the normal middleware chain here.
*/
#createProxyResponse(req, id) {
let res = /** @type {ProxyResponse} */ (new http.ServerResponse(req));
let headSent = false;
let aborted = false;
let post = (msg) => {
if(!aborted) {
this.#worker?.postMessage(msg);
}
};
let sendHead = () => {
if(headSent) {
return;
}
headSent = true;
post({ type: "proxyHead", id, statusCode: res.statusCode, headers: res.getHeaders() });
};
res.write = /** @type {any} */ (/** @this {ProxyResponse} */ function(data, encoding, callback) {
if(typeof encoding === "function") {
callback = encoding;
encoding = undefined;
}
sendHead();
if(data !== undefined && data !== null) {
let chunk = Buffer.isBuffer(data) ? data : Buffer.from(data, typeof encoding === "string" ? /** @type {BufferEncoding} */ (encoding) : "utf8");
// Copy so a pooled Buffer doesn't clone its whole backing store
post({ type: "proxyChunk", id, chunk: new Uint8Array(chunk) });
}
if(typeof callback === "function") {
callback();
}
return true;
});
res.writeHead = function(statusCode, ...args) {
this.statusCode = statusCode;
let headers = args[args.length - 1];
if(headers && typeof headers === "object") {
for(let key of Object.keys(headers)) {
this.setHeader(key, headers[key]);
}
}
return this;
};
res.flushHeaders = sendHead;
res.end = /** @type {any} */ (/** @this {ProxyResponse} */ function(data, encoding, callback) {
if(typeof data === "function") {
callback = data;
data = undefined;
} else if(typeof encoding === "function") {
callback = encoding;
encoding = undefined;
}
if(data !== undefined && data !== null) {
this.write(data, encoding);
}
if(typeof callback === "function") {
callback();
}
this.emit("finish");
return this;
});
// The browser went away: let middleware clean up (e.g. stop a stream)
res.proxyAbort = () => {
if(aborted) {
return;
}
aborted = true;
req.destroy();
res.emit("close");
};
res.isProxyAborted = () => aborted;
return res;
}
async #handleProxyRequest(msg) {
/** @type {Record<string, any>} */
let reply = { type: "proxyResponse", id: msg.id };
try {
// Stands in for the real socket on the server thread
let socket = Object.assign(new Duplex({ read() {}, write(chunk, encoding, callback) { callback(); } }), msg.socket, {
setTimeout() {
return this;
},
setNoDelay() {},
setKeepAlive() {},
});
let req = new http.IncomingMessage(socket);
req.method = msg.method;
req.url = msg.url;
req.headers = msg.headers || {};
req.httpVersion = "1.1";
req.httpVersionMajor = 1;
req.httpVersionMinor = 1;
if(msg.body) {
req.push(Buffer.from(msg.body));
}
req.push(null);
// The whole body is already here; without this, closing the request emits `aborted`
req.complete = true;
let proxyRes = this.#createProxyResponse(req, msg.id);
let res = /** @type {ProxyResponse & WrappedResponse} */ (wrapResponse(proxyRes, this.#transformHtml(req, proxyRes)));
this.#proxyResponses.set(msg.id, res);
// Middleware in the chain call `next()` without awaiting it, so the promise
// returned by the chain can settle before an async middleware has written
// anything. Wait on the response itself instead.
let fellThrough = false;
let settled = new Promise((resolve, reject) => {
res.once("finish", resolve);
res.once("close", resolve);
// Terminal handler: nothing here claimed the request, so the server thread
// serves the file itself (keeping file I/O off this thread).
this.#runMiddlewareChain(req, res, function fallthrough() {
fellThrough = true;
resolve(undefined);
}).catch(reject);
});
await settled;
if(res.isProxyAborted()) {
return;
}
if(!fellThrough && res.bodyUsed) {
// The body was already streamed to the server thread
reply.ended = true;
reply.statusCode = res.statusCode;
reply.headers = res.getHeaders();
} else {
reply.fallthrough = true;
reply.statusCode = res.statusCode;
reply.headers = res.getHeaders();
// A middleware may have set a body without ending; hand it along.
reply.body = res.body;
reply.shouldForceEnd = res._shouldForceEnd;
}
} catch(e) {
this.logger.error(`Server error: ${e.message}`);
reply.error = e.message;
} finally {
this.#proxyResponses.delete(msg.id);
}
this.#worker?.postMessage(reply);
}
/* ---------------------------------------------------------------------- *
* Single-threaded server (used when `serverThread: false`)
* ---------------------------------------------------------------------- */
get listenHost() {
return this.options.host || DEFAULT_OPTIONS.host;
}
get #listensOnAllInterfaces() {
let host = this.listenHost;
return host === "0.0.0.0" || host === "::";
}
// Hostname for the local URL: `localhost` unless the server only listens on another address.
get #localHostname() {
let host = this.listenHost;
if(this.#listensOnAllInterfaces || host === "localhost" || host === "::1" || host.startsWith("127.")) {
return "localhost";
}
return host.includes(":") ? `[${host}]` : host;
}
/** URLs the server can be reached at. @returns {string[]} */
getHosts() {
let hosts = new Set();
if((this.options.showAllHosts ?? true) && this.#listensOnAllInterfaces) {
for(let host of ipAddress()) {
hosts.add(this.getServerUrl(host));
}
}
hosts.add(this.getServerUrl(this.#localHostname));
return Array.from(hosts);
}
/** @type {import("node:http").Server | import("node:http2").Http2SecureServer | undefined} */
/** @internal */
_server;
/** @internal */
portRetryCount = 0;
/** @internal @type {string | undefined} */
_serverProtocol;
/** @internal */
get server() {
if (this._server) {
return this._server;
}
this.start = Date.now();
// Check for secure server requirements, otherwise use HTTP
let { key, cert } = this.options.https;
if(key && cert) {
let options = {
allowHTTP1: true,
// Credentials
key: fs.readFileSync(key),
cert: fs.readFileSync(cert),
};
this._server = createSecureServer(options, /** @type {any} */ (this.onRequestHandler.bind(this)));
this._serverProtocol = "https:";
} else {
this._server = createServer(this.onRequestHandler.bind(this));
this._serverProtocol = "http:";
}
let server = this._server;
this.portRetryCount = 0;
server.on("error", (/** @type {NodeJS.ErrnoException & { port: number }} */ err) => {
if (err.code == "EADDRINUSE") {
if (this.portRetryCount < this.options.portReassignmentRetryCount) {
this.portRetryCount++;
debug(
"Server already using port %o, trying the next port %o. Retry number %o of %o",
err.port,
err.port + 1,
this.portRetryCount,
this.options.portReassignmentRetryCount
);
this._serverListen(err.port + 1);
} else {
throw new Error(
`Tried ${this.options.portReassignmentRetryCount} different ports but they were all in use. You can a different starter port using --port on the command line.`
);
}
} else {
this._serverErrorHandler(err);
}
});
server.on("listening", () => {
this.#port = /** @type {import("node:net").AddressInfo} */ (server.address()).port;
this.setupReloadNotifier();
this.logStartMessage();
this.#portResolve(this.#port);
this.#readyResolve();
});
return server;
}
/** Resolves once the server is listening. @returns {Promise<void>} */
async ready() {
return this.#readyPromise;
}
/** @internal */
async _serverListen(port) {
// Goes through the usual retry on the next port
if(await isPortInUse(port, this.listenHost)) {
this.server.emit("error", portInUseError(port));
return;
}
this.server.listen({
port,
host: this.listenHost,
});
}
/** @internal */
getServerUrlRaw(host, pathname = "", isRaw = true) {
if(!this.#port || !this._serverProtocol) {
throw new Error("Access to server url not yet available.");
}
return `${this._serverProtocol}//${host}:${this.#port}${isRaw ? pathname : this.getServerPath(pathname)}`;
}
/** @param {string} host @param {string} [pathname] @returns {string} */
getServerUrl(host, pathname = "") {
return this.getServerUrlRaw(host, pathname, false);
}
/** Resolves with the port the server is listening on. @returns {Promise<number>} */
async getPort() {
return this.#portPromise;
}
/** @param {number | string} [port] */
serve(port) {