1 | /**
|
2 | * Copyright (c) 2015-present, Facebook, Inc.
|
3 | *
|
4 | * This source code is licensed under the MIT license found in the
|
5 | * LICENSE file in the root directory of this source tree.
|
6 | */
|
7 |
|
8 | ;
|
9 |
|
10 | const { URL } = require('url');
|
11 |
|
12 | module.exports = getPublicUrlOrPath;
|
13 |
|
14 | /**
|
15 | * Returns a URL or a path with slash at the end
|
16 | * In production can be URL, abolute path, relative path
|
17 | * In development always will be an absolute path
|
18 | * In development can use `path` module functions for operations
|
19 | *
|
20 | * @param {boolean} isEnvDevelopment
|
21 | * @param {(string|undefined)} homepage a valid url or pathname
|
22 | * @param {(string|undefined)} envPublicUrl a valid url or pathname
|
23 | * @returns {string}
|
24 | */
|
25 | function getPublicUrlOrPath(isEnvDevelopment, homepage, envPublicUrl) {
|
26 | const stubDomain = 'https://create-react-app.dev';
|
27 |
|
28 | if (envPublicUrl) {
|
29 | // ensure last slash exists
|
30 | envPublicUrl = envPublicUrl.endsWith('/')
|
31 | ? envPublicUrl
|
32 | : envPublicUrl + '/';
|
33 |
|
34 | // validate if `envPublicUrl` is a URL or path like
|
35 | // `stubDomain` is ignored if `envPublicUrl` contains a domain
|
36 | const validPublicUrl = new URL(envPublicUrl, stubDomain);
|
37 |
|
38 | return isEnvDevelopment
|
39 | ? envPublicUrl.startsWith('.')
|
40 | ? '/'
|
41 | : validPublicUrl.pathname
|
42 | : // Some apps do not use client-side routing with pushState.
|
43 | // For these, "homepage" can be set to "." to enable relative asset paths.
|
44 | envPublicUrl;
|
45 | }
|
46 |
|
47 | if (homepage) {
|
48 | // strip last slash if exists
|
49 | homepage = homepage.endsWith('/') ? homepage : homepage + '/';
|
50 |
|
51 | // validate if `homepage` is a URL or path like and use just pathname
|
52 | const validHomepagePathname = new URL(homepage, stubDomain).pathname;
|
53 | return isEnvDevelopment
|
54 | ? homepage.startsWith('.')
|
55 | ? '/'
|
56 | : validHomepagePathname
|
57 | : // Some apps do not use client-side routing with pushState.
|
58 | // For these, "homepage" can be set to "." to enable relative asset paths.
|
59 | homepage.startsWith('.')
|
60 | ? homepage
|
61 | : validHomepagePathname;
|
62 | }
|
63 |
|
64 | return '/';
|
65 | }
|