source: node_modules/@swagger-api/apidom-reference/cjs/util/url.cjs@ d24f17c

main
Last change on this file since d24f17c was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Initial commit

  • Property mode set to 100644
File size: 8.6 KB
RevLine 
[d24f17c]1"use strict";
2
3var _replaceAllInstanceProperty = require("@babel/runtime-corejs3/core-js/instance/replace-all");
4var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default;
5exports.__esModule = true;
6exports.unsanitize = exports.toFileSystemPath = exports.stripHash = exports.sanitize = exports.resolve = exports.isURI = exports.isHttpUrl = exports.isFileSystemPath = exports.hasProtocol = exports.getProtocol = exports.getHash = exports.getExtension = exports.fromFileSystemPath = exports.cwd = void 0;
7var _process = _interopRequireDefault(require("process"));
8var _ramda = require("ramda");
9var _ramdaAdjunct = require("ramda-adjunct");
10/**
11 * SPDX-FileCopyrightText: Copyright (c) 2015 James Messinger
12 *
13 * SPDX-License-Identifier: MIT
14 */
15
16const isWindows = () => (0, _ramda.pathSatisfies)((0, _ramda.test)(/^win/), ['platform'], _process.default);
17
18/**
19 * Returns the protocol of the given URL, or `undefined` if it has no protocol.
20 */
21const getProtocol = url => {
22 try {
23 const parsedUrl = new URL(url);
24 return (0, _ramdaAdjunct.trimCharsEnd)(':', parsedUrl.protocol);
25 } catch {
26 return undefined;
27 }
28};
29
30/**
31 * Returns true if given URL has protocol.
32 */
33exports.getProtocol = getProtocol;
34const hasProtocol = exports.hasProtocol = (0, _ramda.pipe)(getProtocol, _ramdaAdjunct.isNotUndefined);
35
36/**
37 * Returns the lower-cased file extension of the given URL,
38 * or an empty string if it has no extension.
39 */
40const getExtension = url => {
41 const lastDotPosition = url.lastIndexOf('.');
42 if (lastDotPosition >= 0) {
43 return url.substring(lastDotPosition).toLowerCase();
44 }
45 return '';
46};
47
48/**
49 * Determines whether the given path is a filesystem path.
50 * This includes "file://" URLs.
51 */
52exports.getExtension = getExtension;
53const isFileSystemPath = uri => {
54 // @ts-ignore
55 if (_process.default.browser) {
56 /**
57 * We're running in a browser, so assume that all paths are URLs.
58 * This way, even relative paths will be treated as URLs rather than as filesystem paths.
59 */
60 return false;
61 }
62 const protocol = getProtocol(uri);
63 return (0, _ramdaAdjunct.isUndefined)(protocol) || protocol === 'file' || /^[a-zA-Z]$/.test(protocol);
64};
65
66/**
67 * Determines whether the given URI is an HTTP(S) URL.
68 */
69exports.isFileSystemPath = isFileSystemPath;
70const isHttpUrl = url => {
71 const protocol = getProtocol(url);
72 return protocol === 'http' || protocol === 'https';
73};
74
75/**
76 * Determines whether the given URI
77 * @param uri
78 */
79exports.isHttpUrl = isHttpUrl;
80const isURI = uri => {
81 try {
82 return new URL(uri) && true;
83 } catch {
84 return false;
85 }
86};
87exports.isURI = isURI;
88/**
89 * Converts a URL to a local filesystem path.
90 */
91const toFileSystemPath = (uri, options) => {
92 // RegExp patterns to URL-decode special characters for local filesystem paths
93 const urlDecodePatterns = [/%23/g, '#', /%24/g, '$', /%26/g, '&', /%2C/g, ',', /%40/g, '@'];
94 const keepFileProtocol = (0, _ramda.propOr)(false, 'keepFileProtocol', options);
95 const isWindowsPredicate = (0, _ramda.propOr)(isWindows, 'isWindows', options);
96
97 // Step 1: `decodeURI` will decode characters such as Cyrillic characters, spaces, etc.
98 let path = decodeURI(uri);
99
100 // Step 2: Manually decode characters that are not decoded by `decodeURI`.
101 // This includes characters such as "#" and "?", which have special meaning in URLs,
102 // but are just normal characters in a filesystem path.
103 for (let i = 0; i < urlDecodePatterns.length; i += 2) {
104 // @ts-ignore
105 path = path.replace(urlDecodePatterns[i], urlDecodePatterns[i + 1]);
106 }
107
108 // Step 3: If it's a "file://" URL, then format it consistently
109 // or convert it to a local filesystem path
110 let isFileUrl = path.substring(0, 7).toLowerCase() === 'file://';
111 if (isFileUrl) {
112 // Strip-off the protocol, and the initial "/", if there is one
113 path = path[7] === '/' ? path.substring(8) : path.substring(7);
114
115 // insert a colon (":") after the drive letter on Windows
116 if (isWindowsPredicate() && path[1] === '/') {
117 path = `${path[0]}:${path.substring(1)}`;
118 }
119 if (keepFileProtocol) {
120 // Return the consistently-formatted "file://" URL
121 path = `file:///${path}`;
122 } else {
123 // Convert the "file://" URL to a local filesystem path.
124 // On Windows, it will start with something like "C:/".
125 // On Posix, it will start with "/"
126 isFileUrl = false;
127 path = isWindowsPredicate() ? path : `/${path}`;
128 }
129 }
130
131 // Step 4: Normalize Windows paths (unless it's a "file://" URL)
132 if (isWindowsPredicate() && !isFileUrl) {
133 // Replace forward slashes with backslashes
134 path = (0, _replaceAllInstanceProperty(_ramdaAdjunct))('/', '\\', path);
135
136 // Capitalize the drive letter
137 if (path.substring(1, 3) === ':\\') {
138 path = path[0].toUpperCase() + path.substring(1);
139 }
140 }
141 return path;
142};
143
144/**
145 * Converts a filesystem path to a properly-encoded URL.
146 *
147 * This is intended to handle situations where resolver is called
148 * with a filesystem path that contains characters which are not allowed in URLs.
149 *
150 * @example
151 * The following filesystem paths would be converted to the following URLs:
152 *
153 * <"!@#$%^&*+=?'>.json ==> %3C%22!@%23$%25%5E&*+=%3F\'%3E.json
154 * C:\\My Documents\\File (1).json ==> C:/My%20Documents/File%20(1).json
155 * file://Project #42/file.json ==> file://Project%20%2342/file.json
156 */
157exports.toFileSystemPath = toFileSystemPath;
158const fromFileSystemPath = uri => {
159 const urlEncodePatterns = [/\?/g, '%3F', /#/g, '%23'];
160 let path = uri;
161
162 // Step 1: On Windows, replace backslashes with forward slashes,
163 // rather than encoding them as "%5C"
164 if (isWindows()) {
165 path = path.replace(/\\/g, '/');
166 }
167
168 // Step 2: `encodeURI` will take care of MOST characters
169 path = encodeURI(path);
170
171 // Step 3: Manually encode characters that are not encoded by `encodeURI`.
172 // This includes characters such as "#" and "?", which have special meaning in URLs,
173 // but are just normal characters in a filesystem path.
174 for (let i = 0; i < urlEncodePatterns.length; i += 2) {
175 // @ts-ignore
176 path = path.replace(urlEncodePatterns[i], urlEncodePatterns[i + 1]);
177 }
178 return path;
179};
180
181/**
182 * Returns the hash (URL fragment), of the given path.
183 * If there is no hash, then the root hash ("#") is returned.
184 */
185exports.fromFileSystemPath = fromFileSystemPath;
186const getHash = uri => {
187 const hashIndex = uri.indexOf('#');
188 if (hashIndex !== -1) {
189 return uri.substring(hashIndex);
190 }
191 return '#';
192};
193
194/**
195 * Removes the hash (URL fragment), if any, from the given path.
196 */
197exports.getHash = getHash;
198const stripHash = uri => {
199 const hashIndex = uri.indexOf('#');
200 let hashStrippedUri = uri;
201 if (hashIndex >= 0) {
202 hashStrippedUri = uri.substring(0, hashIndex);
203 }
204 return hashStrippedUri;
205};
206
207/**
208 * Returns the current working directory (in Node) or the current page URL (in browsers).
209 */
210exports.stripHash = stripHash;
211const cwd = () => {
212 // @ts-ignore
213 if (_process.default.browser) {
214 return stripHash(globalThis.location.href);
215 }
216 const path = _process.default.cwd();
217 const lastChar = (0, _ramda.last)(path);
218 if (['/', '\\'].includes(lastChar)) {
219 return path;
220 }
221 return path + (isWindows() ? '\\' : '/');
222};
223
224/**
225 * Resolves a target URI relative to a base URI in a manner similar to that of a Web browser resolving an anchor tag HREF.
226 */
227exports.cwd = cwd;
228const resolve = (from, to) => {
229 const resolvedUrl = new URL(to, new URL(from, 'resolve://'));
230 if (resolvedUrl.protocol === 'resolve:') {
231 // `from` is a relative URL.
232 const {
233 pathname,
234 search,
235 hash
236 } = resolvedUrl;
237 return pathname + search + hash;
238 }
239 return resolvedUrl.toString();
240};
241
242/**
243 * Sanitizes/Encodes URI to it's url encoded form.
244 *
245 * The functional will compensate with the usecase when
246 * already sanitized URI is passed to it,
247 * by first unsatizing it and then performing sanitization again.
248 */
249exports.resolve = resolve;
250const sanitize = uri => {
251 if (isFileSystemPath(uri)) {
252 return fromFileSystemPath(toFileSystemPath(uri));
253 }
254 try {
255 return new URL(uri).toString();
256 } catch {
257 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI#encoding_for_ipv6
258 return encodeURI(decodeURI(uri)).replace(/%5B/g, '[').replace(/%5D/g, ']');
259 }
260};
261
262/**
263 * Unsanitizes/Decodes URI to it's url encoded form.
264 * This function already assumes that hash part of the URI
265 * has been removed prior to transforming it to it's sanitized form.
266 */
267exports.sanitize = sanitize;
268const unsanitize = uri => {
269 if (isFileSystemPath(uri)) {
270 return toFileSystemPath(uri);
271 }
272 return decodeURI(uri);
273};
274exports.unsanitize = unsanitize;
Note: See TracBrowser for help on using the repository browser.