Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-go / node_modules / vscode-uri / lib / esm / index.js
1 /*---------------------------------------------------------------------------------------------
2  *  Copyright (c) Microsoft Corporation. All rights reserved.
3  *  Licensed under the MIT License. See License.txt in the project root for license information.
4  *--------------------------------------------------------------------------------------------*/
5 'use strict';
6 var __extends = (this && this.__extends) || (function () {
7     var extendStatics = function (d, b) {
8         extendStatics = Object.setPrototypeOf ||
9             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
10             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11         return extendStatics(d, b);
12     };
13     return function (d, b) {
14         extendStatics(d, b);
15         function __() { this.constructor = d; }
16         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
17     };
18 })();
19 var _a;
20 var isWindows;
21 if (typeof process === 'object') {
22     isWindows = process.platform === 'win32';
23 }
24 else if (typeof navigator === 'object') {
25     var userAgent = navigator.userAgent;
26     isWindows = userAgent.indexOf('Windows') >= 0;
27 }
28 function isHighSurrogate(charCode) {
29     return (0xD800 <= charCode && charCode <= 0xDBFF);
30 }
31 function isLowSurrogate(charCode) {
32     return (0xDC00 <= charCode && charCode <= 0xDFFF);
33 }
34 function isLowerAsciiHex(code) {
35     return code >= 97 /* a */ && code <= 102 /* f */;
36 }
37 function isLowerAsciiLetter(code) {
38     return code >= 97 /* a */ && code <= 122 /* z */;
39 }
40 function isUpperAsciiLetter(code) {
41     return code >= 65 /* A */ && code <= 90 /* Z */;
42 }
43 function isAsciiLetter(code) {
44     return isLowerAsciiLetter(code) || isUpperAsciiLetter(code);
45 }
46 //#endregion
47 var _schemePattern = /^\w[\w\d+.-]*$/;
48 var _singleSlashStart = /^\//;
49 var _doubleSlashStart = /^\/\//;
50 function _validateUri(ret, _strict) {
51     // scheme, must be set
52     if (!ret.scheme && _strict) {
53         throw new Error("[UriError]: Scheme is missing: {scheme: \"\", authority: \"" + ret.authority + "\", path: \"" + ret.path + "\", query: \"" + ret.query + "\", fragment: \"" + ret.fragment + "\"}");
54     }
55     // scheme, https://tools.ietf.org/html/rfc3986#section-3.1
56     // ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
57     if (ret.scheme && !_schemePattern.test(ret.scheme)) {
58         throw new Error('[UriError]: Scheme contains illegal characters.');
59     }
60     // path, http://tools.ietf.org/html/rfc3986#section-3.3
61     // If a URI contains an authority component, then the path component
62     // must either be empty or begin with a slash ("/") character.  If a URI
63     // does not contain an authority component, then the path cannot begin
64     // with two slash characters ("//").
65     if (ret.path) {
66         if (ret.authority) {
67             if (!_singleSlashStart.test(ret.path)) {
68                 throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character');
69             }
70         }
71         else {
72             if (_doubleSlashStart.test(ret.path)) {
73                 throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")');
74             }
75         }
76     }
77 }
78 // for a while we allowed uris *without* schemes and this is the migration
79 // for them, e.g. an uri without scheme and without strict-mode warns and falls
80 // back to the file-scheme. that should cause the least carnage and still be a
81 // clear warning
82 function _schemeFix(scheme, _strict) {
83     if (!scheme && !_strict) {
84         return 'file';
85     }
86     return scheme;
87 }
88 // implements a bit of https://tools.ietf.org/html/rfc3986#section-5
89 function _referenceResolution(scheme, path) {
90     // the slash-character is our 'default base' as we don't
91     // support constructing URIs relative to other URIs. This
92     // also means that we alter and potentially break paths.
93     // see https://tools.ietf.org/html/rfc3986#section-5.1.4
94     switch (scheme) {
95         case 'https':
96         case 'http':
97         case 'file':
98             if (!path) {
99                 path = _slash;
100             }
101             else if (path[0] !== _slash) {
102                 path = _slash + path;
103             }
104             break;
105     }
106     return path;
107 }
108 var _empty = '';
109 var _slash = '/';
110 var _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
111 /**
112  * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986.
113  * This class is a simple parser which creates the basic component parts
114  * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation
115  * and encoding.
116  *
117  * ```txt
118  *       foo://example.com:8042/over/there?name=ferret#nose
119  *       \_/   \______________/\_________/ \_________/ \__/
120  *        |           |            |            |        |
121  *     scheme     authority       path        query   fragment
122  *        |   _____________________|__
123  *       / \ /                        \
124  *       urn:example:animal:ferret:nose
125  * ```
126  */
127 var URI = /** @class */ (function () {
128     /**
129      * @internal
130      */
131     function URI(schemeOrData, authority, path, query, fragment, _strict) {
132         if (_strict === void 0) { _strict = false; }
133         if (typeof schemeOrData === 'object') {
134             this.scheme = schemeOrData.scheme || _empty;
135             this.authority = schemeOrData.authority || _empty;
136             this.path = schemeOrData.path || _empty;
137             this.query = schemeOrData.query || _empty;
138             this.fragment = schemeOrData.fragment || _empty;
139             // no validation because it's this URI
140             // that creates uri components.
141             // _validateUri(this);
142         }
143         else {
144             this.scheme = _schemeFix(schemeOrData, _strict);
145             this.authority = authority || _empty;
146             this.path = _referenceResolution(this.scheme, path || _empty);
147             this.query = query || _empty;
148             this.fragment = fragment || _empty;
149             _validateUri(this, _strict);
150         }
151     }
152     URI.isUri = function (thing) {
153         if (thing instanceof URI) {
154             return true;
155         }
156         if (!thing) {
157             return false;
158         }
159         return typeof thing.authority === 'string'
160             && typeof thing.fragment === 'string'
161             && typeof thing.path === 'string'
162             && typeof thing.query === 'string'
163             && typeof thing.scheme === 'string'
164             && typeof thing.fsPath === 'function'
165             && typeof thing.with === 'function'
166             && typeof thing.toString === 'function';
167     };
168     Object.defineProperty(URI.prototype, "fsPath", {
169         // ---- filesystem path -----------------------
170         /**
171          * Returns a string representing the corresponding file system path of this URI.
172          * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the
173          * platform specific path separator.
174          *
175          * * Will *not* validate the path for invalid characters and semantics.
176          * * Will *not* look at the scheme of this URI.
177          * * The result shall *not* be used for display purposes but for accessing a file on disk.
178          *
179          *
180          * The *difference* to `URI#path` is the use of the platform specific separator and the handling
181          * of UNC paths. See the below sample of a file-uri with an authority (UNC path).
182          *
183          * ```ts
184             const u = URI.parse('file://server/c$/folder/file.txt')
185             u.authority === 'server'
186             u.path === '/shares/c$/file.txt'
187             u.fsPath === '\\server\c$\folder\file.txt'
188         ```
189          *
190          * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path,
191          * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working
192          * with URIs that represent files on disk (`file` scheme).
193          */
194         get: function () {
195             // if (this.scheme !== 'file') {
196             //  console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`);
197             // }
198             return uriToFsPath(this, false);
199         },
200         enumerable: true,
201         configurable: true
202     });
203     // ---- modify to new -------------------------
204     URI.prototype.with = function (change) {
205         if (!change) {
206             return this;
207         }
208         var scheme = change.scheme, authority = change.authority, path = change.path, query = change.query, fragment = change.fragment;
209         if (scheme === undefined) {
210             scheme = this.scheme;
211         }
212         else if (scheme === null) {
213             scheme = _empty;
214         }
215         if (authority === undefined) {
216             authority = this.authority;
217         }
218         else if (authority === null) {
219             authority = _empty;
220         }
221         if (path === undefined) {
222             path = this.path;
223         }
224         else if (path === null) {
225             path = _empty;
226         }
227         if (query === undefined) {
228             query = this.query;
229         }
230         else if (query === null) {
231             query = _empty;
232         }
233         if (fragment === undefined) {
234             fragment = this.fragment;
235         }
236         else if (fragment === null) {
237             fragment = _empty;
238         }
239         if (scheme === this.scheme
240             && authority === this.authority
241             && path === this.path
242             && query === this.query
243             && fragment === this.fragment) {
244             return this;
245         }
246         return new _URI(scheme, authority, path, query, fragment);
247     };
248     // ---- parse & validate ------------------------
249     /**
250      * Creates a new URI from a string, e.g. `http://www.msft.com/some/path`,
251      * `file:///usr/home`, or `scheme:with/path`.
252      *
253      * @param value A string which represents an URI (see `URI#toString`).
254      */
255     URI.parse = function (value, _strict) {
256         if (_strict === void 0) { _strict = false; }
257         var match = _regexp.exec(value);
258         if (!match) {
259             return new _URI(_empty, _empty, _empty, _empty, _empty);
260         }
261         return new _URI(match[2] || _empty, percentDecode(match[4] || _empty), percentDecode(match[5] || _empty), percentDecode(match[7] || _empty), percentDecode(match[9] || _empty), _strict);
262     };
263     /**
264      * Creates a new URI from a file system path, e.g. `c:\my\files`,
265      * `/usr/home`, or `\\server\share\some\path`.
266      *
267      * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument
268      * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as**
269      * `URI.parse('file://' + path)` because the path might contain characters that are
270      * interpreted (# and ?). See the following sample:
271      * ```ts
272     const good = URI.file('/coding/c#/project1');
273     good.scheme === 'file';
274     good.path === '/coding/c#/project1';
275     good.fragment === '';
276     const bad = URI.parse('file://' + '/coding/c#/project1');
277     bad.scheme === 'file';
278     bad.path === '/coding/c'; // path is now broken
279     bad.fragment === '/project1';
280     ```
281      *
282      * @param path A file system path (see `URI#fsPath`)
283      */
284     URI.file = function (path) {
285         var authority = _empty;
286         // normalize to fwd-slashes on windows,
287         // on other systems bwd-slashes are valid
288         // filename character, eg /f\oo/ba\r.txt
289         if (isWindows) {
290             path = path.replace(/\\/g, _slash);
291         }
292         // check for authority as used in UNC shares
293         // or use the path as given
294         if (path[0] === _slash && path[1] === _slash) {
295             var idx = path.indexOf(_slash, 2);
296             if (idx === -1) {
297                 authority = path.substring(2);
298                 path = _slash;
299             }
300             else {
301                 authority = path.substring(2, idx);
302                 path = path.substring(idx) || _slash;
303             }
304         }
305         return new _URI('file', authority, path, _empty, _empty);
306     };
307     URI.from = function (components) {
308         return new _URI(components.scheme, components.authority, components.path, components.query, components.fragment);
309     };
310     // /**
311     //  * Join a URI path with path fragments and normalizes the resulting path.
312     //  *
313     //  * @param uri The input URI.
314     //  * @param pathFragment The path fragment to add to the URI path.
315     //  * @returns The resulting URI.
316     //  */
317     // static joinPath(uri: URI, ...pathFragment: string[]): URI {
318     //  if (!uri.path) {
319     //          throw new Error(`[UriError]: cannot call joinPaths on URI without path`);
320     //  }
321     //  let newPath: string;
322     //  if (isWindows && uri.scheme === 'file') {
323     //          newPath = URI.file(paths.win32.join(uriToFsPath(uri, true), ...pathFragment)).path;
324     //  } else {
325     //          newPath = paths.posix.join(uri.path, ...pathFragment);
326     //  }
327     //  return uri.with({ path: newPath });
328     // }
329     // ---- printing/externalize ---------------------------
330     /**
331      * Creates a string representation for this URI. It's guaranteed that calling
332      * `URI.parse` with the result of this function creates an URI which is equal
333      * to this URI.
334      *
335      * * The result shall *not* be used for display purposes but for externalization or transport.
336      * * The result will be encoded using the percentage encoding and encoding happens mostly
337      * ignore the scheme-specific encoding rules.
338      *
339      * @param skipEncoding Do not encode the result, default is `false`
340      */
341     URI.prototype.toString = function (skipEncoding) {
342         if (skipEncoding === void 0) { skipEncoding = false; }
343         return _asFormatted(this, skipEncoding);
344     };
345     URI.prototype.toJSON = function () {
346         return this;
347     };
348     URI.revive = function (data) {
349         if (!data) {
350             return data;
351         }
352         else if (data instanceof URI) {
353             return data;
354         }
355         else {
356             var result = new _URI(data);
357             result._formatted = data.external;
358             result._fsPath = data._sep === _pathSepMarker ? data.fsPath : null;
359             return result;
360         }
361     };
362     return URI;
363 }());
364 export { URI };
365 var _pathSepMarker = isWindows ? 1 : undefined;
366 // eslint-disable-next-line @typescript-eslint/class-name-casing
367 var _URI = /** @class */ (function (_super) {
368     __extends(_URI, _super);
369     function _URI() {
370         var _this = _super !== null && _super.apply(this, arguments) || this;
371         _this._formatted = null;
372         _this._fsPath = null;
373         return _this;
374     }
375     Object.defineProperty(_URI.prototype, "fsPath", {
376         get: function () {
377             if (!this._fsPath) {
378                 this._fsPath = uriToFsPath(this, false);
379             }
380             return this._fsPath;
381         },
382         enumerable: true,
383         configurable: true
384     });
385     _URI.prototype.toString = function (skipEncoding) {
386         if (skipEncoding === void 0) { skipEncoding = false; }
387         if (!skipEncoding) {
388             if (!this._formatted) {
389                 this._formatted = _asFormatted(this, false);
390             }
391             return this._formatted;
392         }
393         else {
394             // we don't cache that
395             return _asFormatted(this, true);
396         }
397     };
398     _URI.prototype.toJSON = function () {
399         var res = {
400             $mid: 1
401         };
402         // cached state
403         if (this._fsPath) {
404             res.fsPath = this._fsPath;
405             res._sep = _pathSepMarker;
406         }
407         if (this._formatted) {
408             res.external = this._formatted;
409         }
410         // uri components
411         if (this.path) {
412             res.path = this.path;
413         }
414         if (this.scheme) {
415             res.scheme = this.scheme;
416         }
417         if (this.authority) {
418             res.authority = this.authority;
419         }
420         if (this.query) {
421             res.query = this.query;
422         }
423         if (this.fragment) {
424             res.fragment = this.fragment;
425         }
426         return res;
427     };
428     return _URI;
429 }(URI));
430 // reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2
431 var encodeTable = (_a = {},
432     _a[58 /* Colon */] = '%3A',
433     _a[47 /* Slash */] = '%2F',
434     _a[63 /* QuestionMark */] = '%3F',
435     _a[35 /* Hash */] = '%23',
436     _a[91 /* OpenSquareBracket */] = '%5B',
437     _a[93 /* CloseSquareBracket */] = '%5D',
438     _a[64 /* AtSign */] = '%40',
439     _a[33 /* ExclamationMark */] = '%21',
440     _a[36 /* DollarSign */] = '%24',
441     _a[38 /* Ampersand */] = '%26',
442     _a[39 /* SingleQuote */] = '%27',
443     _a[40 /* OpenParen */] = '%28',
444     _a[41 /* CloseParen */] = '%29',
445     _a[42 /* Asterisk */] = '%2A',
446     _a[43 /* Plus */] = '%2B',
447     _a[44 /* Comma */] = '%2C',
448     _a[59 /* Semicolon */] = '%3B',
449     _a[61 /* Equals */] = '%3D',
450     _a[32 /* Space */] = '%20',
451     _a);
452 function encodeURIComponentFast(uriComponent, allowSlash) {
453     var res = undefined;
454     var nativeEncodePos = -1;
455     for (var pos = 0; pos < uriComponent.length; pos++) {
456         var code = uriComponent.charCodeAt(pos);
457         // unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3
458         if ((code >= 97 /* a */ && code <= 122 /* z */)
459             || (code >= 65 /* A */ && code <= 90 /* Z */)
460             || (code >= 48 /* Digit0 */ && code <= 57 /* Digit9 */)
461             || code === 45 /* Dash */
462             || code === 46 /* Period */
463             || code === 95 /* Underline */
464             || code === 126 /* Tilde */
465             || (allowSlash && code === 47 /* Slash */)) {
466             // check if we are delaying native encode
467             if (nativeEncodePos !== -1) {
468                 res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
469                 nativeEncodePos = -1;
470             }
471             // check if we write into a new string (by default we try to return the param)
472             if (res !== undefined) {
473                 res += uriComponent.charAt(pos);
474             }
475         }
476         else {
477             // encoding needed, we need to allocate a new string
478             if (res === undefined) {
479                 res = uriComponent.substr(0, pos);
480             }
481             // check with default table first
482             var escaped = encodeTable[code];
483             if (escaped !== undefined) {
484                 // check if we are delaying native encode
485                 if (nativeEncodePos !== -1) {
486                     res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
487                     nativeEncodePos = -1;
488                 }
489                 // append escaped variant to result
490                 res += escaped;
491             }
492             else if (nativeEncodePos === -1) {
493                 // use native encode only when needed
494                 nativeEncodePos = pos;
495             }
496         }
497     }
498     if (nativeEncodePos !== -1) {
499         res += encodeURIComponent(uriComponent.substring(nativeEncodePos));
500     }
501     return res !== undefined ? res : uriComponent;
502 }
503 function encodeURIComponentMinimal(path) {
504     var res = undefined;
505     for (var pos = 0; pos < path.length; pos++) {
506         var code = path.charCodeAt(pos);
507         if (code === 35 /* Hash */ || code === 63 /* QuestionMark */) {
508             if (res === undefined) {
509                 res = path.substr(0, pos);
510             }
511             res += encodeTable[code];
512         }
513         else {
514             if (res !== undefined) {
515                 res += path[pos];
516             }
517         }
518     }
519     return res !== undefined ? res : path;
520 }
521 /**
522  * Compute `fsPath` for the given uri
523  */
524 export function uriToFsPath(uri, keepDriveLetterCasing) {
525     var value;
526     if (uri.authority && uri.path.length > 1 && uri.scheme === 'file') {
527         // unc path: file://shares/c$/far/boo
528         value = "//" + uri.authority + uri.path;
529     }
530     else if (uri.path.charCodeAt(0) === 47 /* Slash */
531         && (uri.path.charCodeAt(1) >= 65 /* A */ && uri.path.charCodeAt(1) <= 90 /* Z */ || uri.path.charCodeAt(1) >= 97 /* a */ && uri.path.charCodeAt(1) <= 122 /* z */)
532         && uri.path.charCodeAt(2) === 58 /* Colon */) {
533         if (!keepDriveLetterCasing) {
534             // windows drive letter: file:///c:/far/boo
535             value = uri.path[1].toLowerCase() + uri.path.substr(2);
536         }
537         else {
538             value = uri.path.substr(1);
539         }
540     }
541     else {
542         // other path
543         value = uri.path;
544     }
545     if (isWindows) {
546         value = value.replace(/\//g, '\\');
547     }
548     return value;
549 }
550 /**
551  * Create the external version of a uri
552  */
553 function _asFormatted(uri, skipEncoding) {
554     var encoder = !skipEncoding
555         ? encodeURIComponentFast
556         : encodeURIComponentMinimal;
557     var res = '';
558     var scheme = uri.scheme, authority = uri.authority, path = uri.path, query = uri.query, fragment = uri.fragment;
559     if (scheme) {
560         res += scheme;
561         res += ':';
562     }
563     if (authority || scheme === 'file') {
564         res += _slash;
565         res += _slash;
566     }
567     if (authority) {
568         var idx = authority.indexOf('@');
569         if (idx !== -1) {
570             // <user>@<auth>
571             var userinfo = authority.substr(0, idx);
572             authority = authority.substr(idx + 1);
573             idx = userinfo.indexOf(':');
574             if (idx === -1) {
575                 res += encoder(userinfo, false);
576             }
577             else {
578                 // <user>:<pass>@<auth>
579                 res += encoder(userinfo.substr(0, idx), false);
580                 res += ':';
581                 res += encoder(userinfo.substr(idx + 1), false);
582             }
583             res += '@';
584         }
585         authority = authority.toLowerCase();
586         idx = authority.indexOf(':');
587         if (idx === -1) {
588             res += encoder(authority, false);
589         }
590         else {
591             // <auth>:<port>
592             res += encoder(authority.substr(0, idx), false);
593             res += authority.substr(idx);
594         }
595     }
596     if (path) {
597         // lower-case windows drive letters in /C:/fff or C:/fff
598         if (path.length >= 3 && path.charCodeAt(0) === 47 /* Slash */ && path.charCodeAt(2) === 58 /* Colon */) {
599             var code = path.charCodeAt(1);
600             if (code >= 65 /* A */ && code <= 90 /* Z */) {
601                 path = "/" + String.fromCharCode(code + 32) + ":" + path.substr(3); // "/c:".length === 3
602             }
603         }
604         else if (path.length >= 2 && path.charCodeAt(1) === 58 /* Colon */) {
605             var code = path.charCodeAt(0);
606             if (code >= 65 /* A */ && code <= 90 /* Z */) {
607                 path = String.fromCharCode(code + 32) + ":" + path.substr(2); // "/c:".length === 3
608             }
609         }
610         // encode the rest of the path
611         res += encoder(path, true);
612     }
613     if (query) {
614         res += '?';
615         res += encoder(query, false);
616     }
617     if (fragment) {
618         res += '#';
619         res += !skipEncoding ? encodeURIComponentFast(fragment, false) : fragment;
620     }
621     return res;
622 }
623 // --- decode
624 function decodeURIComponentGraceful(str) {
625     try {
626         return decodeURIComponent(str);
627     }
628     catch (_a) {
629         if (str.length > 3) {
630             return str.substr(0, 3) + decodeURIComponentGraceful(str.substr(3));
631         }
632         else {
633             return str;
634         }
635     }
636 }
637 var _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g;
638 function percentDecode(str) {
639     if (!str.match(_rEncodedAsHex)) {
640         return str;
641     }
642     return str.replace(_rEncodedAsHex, function (match) { return decodeURIComponentGraceful(match); });
643 }