1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | import assert from 'assert';
|
7 | import {readFileSync} from 'fs';
|
8 | import {ServerOptions as HttpsServerOptions} from 'https';
|
9 | import {ListenOptions} from 'net';
|
10 | import path from 'path';
|
11 |
|
12 | const FIXTURES = path.resolve(__dirname, '../fixtures');
|
13 | const DUMMY_TLS_CONFIG = {
|
14 | key: readFileSync(path.join(FIXTURES, 'key.pem')),
|
15 | cert: readFileSync(path.join(FIXTURES, 'cert.pem')),
|
16 | };
|
17 |
|
18 | export interface HttpOptions extends ListenOptions {
|
19 | protocol?: 'http';
|
20 | }
|
21 |
|
22 | export interface HttpsOptions extends ListenOptions, HttpsServerOptions {
|
23 | protocol: 'https';
|
24 | }
|
25 |
|
26 |
|
27 |
|
28 |
|
29 | export interface HostPort {
|
30 | host: string;
|
31 | port: number;
|
32 | }
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 | function assertHostPort(config: Partial<HostPort>): asserts config is HostPort {
|
39 | assert(config.host != null, 'host is not set');
|
40 | assert(config.port != null, 'port is not set');
|
41 | }
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 | export function givenHttpServerConfig<T extends HttpOptions | HttpsOptions>(
|
53 | customConfig?: T,
|
54 | ): HostPort & T {
|
55 | const defaults: HostPort = {host: '127.0.0.1', port: 0};
|
56 |
|
57 | if (isHttpsConfig(customConfig)) {
|
58 | const config: T = {...customConfig};
|
59 | if (config.host == null) config.host = defaults.host;
|
60 | if (config.port == null) config.port = defaults.port;
|
61 | setupTlsConfig(config as HttpsOptions);
|
62 | assertHostPort(config);
|
63 | return config;
|
64 | }
|
65 |
|
66 | assertHttpConfig(customConfig);
|
67 | const config: T = {...customConfig};
|
68 | if (config.host == null) config.host = defaults.host;
|
69 | if (config.port == null) config.port = defaults.port;
|
70 | assertHostPort(config);
|
71 | return config;
|
72 | }
|
73 |
|
74 | function setupTlsConfig(config: HttpsServerOptions) {
|
75 | if ('key' in config && 'cert' in config) return;
|
76 | if ('pfx' in config) return;
|
77 | Object.assign(config, DUMMY_TLS_CONFIG);
|
78 | }
|
79 |
|
80 |
|
81 |
|
82 |
|
83 | function isHttpsConfig(
|
84 | config?: HttpOptions | HttpsOptions,
|
85 | ): config is HttpsOptions {
|
86 | return config?.protocol === 'https';
|
87 | }
|
88 |
|
89 |
|
90 |
|
91 |
|
92 |
|
93 | function assertHttpConfig(
|
94 | config?: HttpOptions | HttpsOptions,
|
95 | ): asserts config is HttpOptions {
|
96 | assert(config?.protocol == null || config?.protocol === 'http');
|
97 | }
|