1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | import {readFileSync} from 'fs';
|
7 | import {ServerOptions as HttpsServerOptions} from 'https';
|
8 | import {ListenOptions} from 'net';
|
9 | import * as path from 'path';
|
10 |
|
11 | const FIXTURES = path.resolve(__dirname, '../fixtures');
|
12 | const DUMMY_TLS_CONFIG = {
|
13 | key: readFileSync(path.join(FIXTURES, 'key.pem')),
|
14 | cert: readFileSync(path.join(FIXTURES, 'cert.pem')),
|
15 | };
|
16 |
|
17 | export interface HttpOptions extends ListenOptions {
|
18 | protocol?: 'http';
|
19 | }
|
20 |
|
21 | export interface HttpsOptions extends ListenOptions, HttpsServerOptions {
|
22 | protocol: 'https';
|
23 | }
|
24 |
|
25 | export type HostPort = {
|
26 | host: string;
|
27 | port: number;
|
28 | };
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 | export function givenHttpServerConfig<T extends HttpOptions | HttpsOptions>(
|
40 | customConfig?: T,
|
41 | ): HostPort & T {
|
42 | const defaults = {
|
43 | host: '127.0.0.1',
|
44 | port: 0,
|
45 | protocol: undefined,
|
46 | };
|
47 | const config = Object.assign({}, defaults, customConfig);
|
48 | if (config.host === undefined) config.host = defaults.host;
|
49 | if (config.port === undefined) config.port = defaults.port;
|
50 | if (isHttpsConfig(config)) {
|
51 | setupTlsConfig(config);
|
52 | }
|
53 | return config;
|
54 | }
|
55 |
|
56 | function setupTlsConfig(config: HttpsServerOptions) {
|
57 | if ('key' in config && 'cert' in config) return;
|
58 | if ('pfx' in config) return;
|
59 | Object.assign(config, DUMMY_TLS_CONFIG);
|
60 | }
|
61 |
|
62 | function isHttpsConfig(
|
63 | config: HttpOptions | HttpsOptions,
|
64 | ): config is HttpsOptions {
|
65 | return config && config.protocol === 'https';
|
66 | }
|