-
-
Notifications
You must be signed in to change notification settings - Fork 228
/
url.ts
293 lines (258 loc) · 8.24 KB
/
url.ts
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import convertPathToPosix from "./convert-path-to-posix";
import path, { win32 } from "path";
const forwardSlashPattern = /\//g;
const protocolPattern = /^(\w{2,}):\/\//i;
const jsonPointerSlash = /~1/g;
const jsonPointerTilde = /~0/g;
import { join } from "path";
import { isWindows } from "./is-windows";
const projectDir = join(__dirname, "..", "..");
// RegExp patterns to URL-encode special characters in local filesystem paths
const urlEncodePatterns = [/\?/g, "%3F", /#/g, "%23"];
// RegExp patterns to URL-decode special characters for local filesystem paths
const urlDecodePatterns = [/%23/g, "#", /%24/g, "$", /%26/g, "&", /%2C/g, ",", /%40/g, "@"];
export const parse = (u: string | URL) => new URL(u);
/**
* Returns resolved target URL relative to a base URL in a manner similar to that of a Web browser resolving an anchor tag HREF.
*
* @returns
*/
export function resolve(from: string, to: string) {
const fromUrl = new URL(convertPathToPosix(from), "resolve:https://");
const resolvedUrl = new URL(convertPathToPosix(to), fromUrl);
if (resolvedUrl.protocol === "resolve:") {
// `from` is a relative URL.
const { pathname, search, hash } = resolvedUrl;
return pathname + search + hash;
}
return resolvedUrl.toString();
}
/**
* Returns the current working directory (in Node) or the current page URL (in browsers).
*
* @returns
*/
export function cwd() {
if (typeof window !== "undefined") {
return location.href;
}
const path = process.cwd();
const lastChar = path.slice(-1);
if (lastChar === "/" || lastChar === "\\") {
return path;
} else {
return path + "/";
}
}
/**
* Returns the protocol of the given URL, or `undefined` if it has no protocol.
*
* @param path
* @returns
*/
export function getProtocol(path: string | undefined) {
const match = protocolPattern.exec(path || "");
if (match) {
return match[1].toLowerCase();
}
}
/**
* Returns the lowercased file extension of the given URL,
* or an empty string if it has no extension.
*
* @param path
* @returns
*/
export function getExtension(path: any) {
const lastDot = path.lastIndexOf(".");
if (lastDot >= 0) {
return stripQuery(path.substr(lastDot).toLowerCase());
}
return "";
}
/**
* Removes the query, if any, from the given path.
*
* @param path
* @returns
*/
export function stripQuery(path: any) {
const queryIndex = path.indexOf("?");
if (queryIndex >= 0) {
path = path.substr(0, queryIndex);
}
return path;
}
/**
* Returns the hash (URL fragment), of the given path.
* If there is no hash, then the root hash ("#") is returned.
*
* @param path
* @returns
*/
export function getHash(path: any) {
const hashIndex = path.indexOf("#");
if (hashIndex >= 0) {
return path.substr(hashIndex);
}
return "#";
}
/**
* Removes the hash (URL fragment), if any, from the given path.
*
* @param path
* @returns
*/
export function stripHash(path: any) {
const hashIndex = path.indexOf("#");
if (hashIndex >= 0) {
path = path.substr(0, hashIndex);
}
return path;
}
/**
* Determines whether the given path is an HTTP(S) URL.
*
* @param path
* @returns
*/
export function isHttp(path: any) {
const protocol = getProtocol(path);
if (protocol === "http" || protocol === "https") {
return true;
} else if (protocol === undefined) {
// There is no protocol. If we're running in a browser, then assume it's HTTP.
return typeof window !== "undefined";
} else {
// It's some other protocol, such as "ftp:https://", "mongodb:https://", etc.
return false;
}
}
/**
* Determines whether the given path is a filesystem path.
* This includes "file:https://" URLs.
*
* @param path
* @returns
*/
export function isFileSystemPath(path: string | undefined) {
// @ts-ignore
if (typeof window !== "undefined" || process.browser) {
// We're running in a browser, so assume that all paths are URLs.
// This way, even relative paths will be treated as URLs rather than as filesystem paths
return false;
}
const protocol = getProtocol(path);
return protocol === undefined || protocol === "file";
}
/**
* Converts a filesystem path to a properly-encoded URL.
*
* This is intended to handle situations where JSON Schema $Ref Parser is called
* with a filesystem path that contains characters which are not allowed in URLs.
*
* @example
* The following filesystem paths would be converted to the following URLs:
*
* <"!@#$%^&*+=?'>.json ==> %3C%22!@%23$%25%5E&*+=%3F\'%3E.json
* C:\\My Documents\\File (1).json ==> C:/My%20Documents/File%20(1).json
* file:https://Project #42/file.json ==> file:https://Project%20%2342/file.json
*
* @param path
* @returns
*/
export function fromFileSystemPath(path: any) {
// Step 1: On Windows, replace backslashes with forward slashes,
// rather than encoding them as "%5C"
if (isWindows()) {
const upperPath = path.toUpperCase();
const projectDirPosixPath = convertPathToPosix(projectDir);
const posixUpper = projectDirPosixPath.toUpperCase();
const hasProjectDir = upperPath.includes(posixUpper);
const hasProjectUri = upperPath.includes(posixUpper);
const isAbsolutePath = win32.isAbsolute(path);
if (!(hasProjectDir || hasProjectUri || isAbsolutePath)) {
path = join(projectDir, path);
}
path = convertPathToPosix(path);
}
// Step 2: `encodeURI` will take care of MOST characters
path = encodeURI(path);
// Step 3: Manually encode characters that are not encoded by `encodeURI`.
// This includes characters such as "#" and "?", which have special meaning in URLs,
// but are just normal characters in a filesystem path.
for (let i = 0; i < urlEncodePatterns.length; i += 2) {
path = path.replace(urlEncodePatterns[i], urlEncodePatterns[i + 1]);
}
return path;
}
/**
* Converts a URL to a local filesystem path.
*/
export function toFileSystemPath(path: string | undefined, keepFileProtocol?: boolean): string {
// Step 1: `decodeURI` will decode characters such as Cyrillic characters, spaces, etc.
path = decodeURI(path!);
// Step 2: Manually decode characters that are not decoded by `decodeURI`.
// This includes characters such as "#" and "?", which have special meaning in URLs,
// but are just normal characters in a filesystem path.
for (let i = 0; i < urlDecodePatterns.length; i += 2) {
path = path.replace(urlDecodePatterns[i], urlDecodePatterns[i + 1] as string);
}
// Step 3: If it's a "file:https://" URL, then format it consistently
// or convert it to a local filesystem path
let isFileUrl = path.substr(0, 7).toLowerCase() === "file:https://";
if (isFileUrl) {
// Strip-off the protocol, and the initial "/", if there is one
path = path[7] === "/" ? path.substr(8) : path.substr(7);
// insert a colon (":") after the drive letter on Windows
if (isWindows() && path[1] === "/") {
path = path[0] + ":" + path.substr(1);
}
if (keepFileProtocol) {
// Return the consistently-formatted "file:https://" URL
path = "file:https:///" + path;
} else {
// Convert the "file:https://" URL to a local filesystem path.
// On Windows, it will start with something like "C:/".
// On Posix, it will start with "/"
isFileUrl = false;
path = isWindows() ? path : "/" + path;
}
}
// Step 4: Normalize Windows paths (unless it's a "file:https://" URL)
if (isWindows() && !isFileUrl) {
// Replace forward slashes with backslashes
path = path.replace(forwardSlashPattern, "\\");
// Capitalize the drive letter
if (path.substr(1, 2) === ":\\") {
path = path[0].toUpperCase() + path.substr(1);
}
}
return path;
}
/**
* Converts a $ref pointer to a valid JSON Path.
*
* @param pointer
* @returns
*/
export function safePointerToPath(pointer: any) {
if (pointer.length <= 1 || pointer[0] !== "#" || pointer[1] !== "/") {
return [];
}
return pointer
.slice(2)
.split("/")
.map((value: any) => {
return decodeURIComponent(value).replace(jsonPointerSlash, "/").replace(jsonPointerTilde, "~");
});
}
export function relative(from: string, to: string) {
if (!isFileSystemPath(from) || !isFileSystemPath(to)) {
return resolve(from, to);
}
const fromDir = path.dirname(stripHash(from));
const toPath = stripHash(to);
const result = path.relative(fromDir, toPath);
return result + getHash(to);
}