1 | "use strict";
|
2 |
|
3 | const getHeaders = require("./getHeaders");
|
4 | const Url = require("url");
|
5 |
|
6 | module.exports = function getLocation(request) {
|
7 | if (!request) return {};
|
8 |
|
9 | const {host: hostHeader, proto: protoHeader} = getHeaders(request);
|
10 |
|
11 | let location = makeLocationFromUri(request.uri) || makeLocationFromUrl(request.url);
|
12 | if (hostHeader) {
|
13 | location.port = undefined;
|
14 | location.host = hostHeader;
|
15 | location.hostname = undefined;
|
16 | location = makeLocationFromUrl(Url.format(location));
|
17 | }
|
18 | if (protoHeader) {
|
19 | location.protocol = `${protoHeader}:`;
|
20 | location = makeLocationFromUrl(Url.format(location));
|
21 | }
|
22 |
|
23 | return location;
|
24 |
|
25 | function makeLocationFromUrl(browserUrl) {
|
26 | return makeLocationFromUri(Url.parse(browserUrl));
|
27 | }
|
28 |
|
29 | function makeLocationFromUri(uri) {
|
30 | if (!uri) return;
|
31 | const {hash, host, hostname, href, pathname, port, protocol, search} = uri;
|
32 |
|
33 | return {
|
34 | hash,
|
35 | host,
|
36 | hostname,
|
37 | href,
|
38 | pathname,
|
39 | port,
|
40 | protocol,
|
41 | search,
|
42 | origin: `${protocol}//${host}`,
|
43 | };
|
44 | }
|
45 | };
|