summaryrefslogtreecommitdiff
path: root/lib/epub.js/src/utils/url.js
blob: 3cc8c04dca3c7ce146850a8aba33b486e9dde82a (plain)
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
import Path from "./path";
import path from "path-webpack";

/**
 * creates a Url object for parsing and manipulation of a url string
 * @param	{string} urlString	a url string (relative or absolute)
 * @param	{string} [baseString] optional base for the url,
 * default to window.location.href
 */
class Url {
	constructor(urlString, baseString) {
		var absolute = (urlString.indexOf("://") > -1);
		var pathname = urlString;
		var basePath;

		this.Url = undefined;
		this.href = urlString;
		this.protocol = "";
		this.origin = "";
		this.hash = "";
		this.hash = "";
		this.search = "";
		this.base = baseString;

		if (!absolute &&
				baseString !== false &&
				typeof(baseString) !== "string" &&
				window && window.location) {
			this.base = window.location.href;
		}

		// URL Polyfill doesn't throw an error if base is empty
		if (absolute || this.base) {
			try {
				if (this.base) { // Safari doesn't like an undefined base
					this.Url = new URL(urlString, this.base);
				} else {
					this.Url = new URL(urlString);
				}
				this.href = this.Url.href;

				this.protocol = this.Url.protocol;
				this.origin = this.Url.origin;
				this.hash = this.Url.hash;
				this.search = this.Url.search;

				pathname = this.Url.pathname + (this.Url.search ? this.Url.search : '');
			} catch (e) {
				// Skip URL parsing
				this.Url = undefined;
				// resolve the pathname from the base
				if (this.base) {
					basePath = new Path(this.base);
					pathname = basePath.resolve(pathname);
				}
			}
		}

		this.Path = new Path(pathname);

		this.directory = this.Path.directory;
		this.filename = this.Path.filename;
		this.extension = this.Path.extension;

	}

	/**
	 * @returns {Path}
	 */
	path () {
		return this.Path;
	}

	/**
	 * Resolves a relative path to a absolute url
	 * @param {string} what
	 * @returns {string} url
	 */
	resolve (what) {
		var isAbsolute = (what.indexOf("://") > -1);
		var fullpath;

		if (isAbsolute) {
			return what;
		}

		fullpath = path.resolve(this.directory, what);
		return this.origin + fullpath;
	}

	/**
	 * Resolve a path relative to the url
	 * @param {string} what
	 * @returns {string} path
	 */
	relative (what) {
		return path.relative(what, this.directory);
	}

	/**
	 * @returns {string}
	 */
	toString () {
		return this.href;
	}
}

export default Url;