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 *--------------------------------------------------------------------------------------------*/
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);
13 return function (d, b) {
15 function __() { this.constructor = d; }
16 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21 if (typeof process === 'object') {
22 isWindows = process.platform === 'win32';
24 else if (typeof navigator === 'object') {
25 var userAgent = navigator.userAgent;
26 isWindows = userAgent.indexOf('Windows') >= 0;
28 function isHighSurrogate(charCode) {
29 return (0xD800 <= charCode && charCode <= 0xDBFF);
31 function isLowSurrogate(charCode) {
32 return (0xDC00 <= charCode && charCode <= 0xDFFF);
34 function isLowerAsciiHex(code) {
35 return code >= 97 /* a */ && code <= 102 /* f */;
37 function isLowerAsciiLetter(code) {
38 return code >= 97 /* a */ && code <= 122 /* z */;
40 function isUpperAsciiLetter(code) {
41 return code >= 65 /* A */ && code <= 90 /* Z */;
43 function isAsciiLetter(code) {
44 return isLowerAsciiLetter(code) || isUpperAsciiLetter(code);
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 + "\"}");
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.');
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 ("//").
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');
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 ("//")');
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
82 function _schemeFix(scheme, _strict) {
83 if (!scheme && !_strict) {
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
101 else if (path[0] !== _slash) {
102 path = _slash + path;
110 var _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
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
118 * foo://example.com:8042/over/there?name=ferret#nose
119 * \_/ \______________/\_________/ \_________/ \__/
121 * scheme authority path query fragment
122 * | _____________________|__
124 * urn:example:animal:ferret:nose
127 var URI = /** @class */ (function () {
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);
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);
152 URI.isUri = function (thing) {
153 if (thing instanceof URI) {
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';
168 Object.defineProperty(URI.prototype, "fsPath", {
169 // ---- filesystem path -----------------------
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.
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.
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).
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'
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).
195 // if (this.scheme !== 'file') {
196 // console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`);
198 return uriToFsPath(this, false);
203 // ---- modify to new -------------------------
204 URI.prototype.with = function (change) {
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;
212 else if (scheme === null) {
215 if (authority === undefined) {
216 authority = this.authority;
218 else if (authority === null) {
221 if (path === undefined) {
224 else if (path === null) {
227 if (query === undefined) {
230 else if (query === null) {
233 if (fragment === undefined) {
234 fragment = this.fragment;
236 else if (fragment === null) {
239 if (scheme === this.scheme
240 && authority === this.authority
241 && path === this.path
242 && query === this.query
243 && fragment === this.fragment) {
246 return new _URI(scheme, authority, path, query, fragment);
248 // ---- parse & validate ------------------------
250 * Creates a new URI from a string, e.g. `http://www.msft.com/some/path`,
251 * `file:///usr/home`, or `scheme:with/path`.
253 * @param value A string which represents an URI (see `URI#toString`).
255 URI.parse = function (value, _strict) {
256 if (_strict === void 0) { _strict = false; }
257 var match = _regexp.exec(value);
259 return new _URI(_empty, _empty, _empty, _empty, _empty);
261 return new _URI(match[2] || _empty, percentDecode(match[4] || _empty), percentDecode(match[5] || _empty), percentDecode(match[7] || _empty), percentDecode(match[9] || _empty), _strict);
264 * Creates a new URI from a file system path, e.g. `c:\my\files`,
265 * `/usr/home`, or `\\server\share\some\path`.
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:
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';
282 * @param path A file system path (see `URI#fsPath`)
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
290 path = path.replace(/\\/g, _slash);
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);
297 authority = path.substring(2);
301 authority = path.substring(2, idx);
302 path = path.substring(idx) || _slash;
305 return new _URI('file', authority, path, _empty, _empty);
307 URI.from = function (components) {
308 return new _URI(components.scheme, components.authority, components.path, components.query, components.fragment);
311 // * Join a URI path with path fragments and normalizes the resulting path.
313 // * @param uri The input URI.
314 // * @param pathFragment The path fragment to add to the URI path.
315 // * @returns The resulting URI.
317 // static joinPath(uri: URI, ...pathFragment: string[]): URI {
319 // throw new Error(`[UriError]: cannot call joinPaths on URI without path`);
321 // let newPath: string;
322 // if (isWindows && uri.scheme === 'file') {
323 // newPath = URI.file(paths.win32.join(uriToFsPath(uri, true), ...pathFragment)).path;
325 // newPath = paths.posix.join(uri.path, ...pathFragment);
327 // return uri.with({ path: newPath });
329 // ---- printing/externalize ---------------------------
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
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.
339 * @param skipEncoding Do not encode the result, default is `false`
341 URI.prototype.toString = function (skipEncoding) {
342 if (skipEncoding === void 0) { skipEncoding = false; }
343 return _asFormatted(this, skipEncoding);
345 URI.prototype.toJSON = function () {
348 URI.revive = function (data) {
352 else if (data instanceof URI) {
356 var result = new _URI(data);
357 result._formatted = data.external;
358 result._fsPath = data._sep === _pathSepMarker ? data.fsPath : null;
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);
370 var _this = _super !== null && _super.apply(this, arguments) || this;
371 _this._formatted = null;
372 _this._fsPath = null;
375 Object.defineProperty(_URI.prototype, "fsPath", {
378 this._fsPath = uriToFsPath(this, false);
385 _URI.prototype.toString = function (skipEncoding) {
386 if (skipEncoding === void 0) { skipEncoding = false; }
388 if (!this._formatted) {
389 this._formatted = _asFormatted(this, false);
391 return this._formatted;
394 // we don't cache that
395 return _asFormatted(this, true);
398 _URI.prototype.toJSON = function () {
404 res.fsPath = this._fsPath;
405 res._sep = _pathSepMarker;
407 if (this._formatted) {
408 res.external = this._formatted;
412 res.path = this.path;
415 res.scheme = this.scheme;
417 if (this.authority) {
418 res.authority = this.authority;
421 res.query = this.query;
424 res.fragment = this.fragment;
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',
452 function encodeURIComponentFast(uriComponent, allowSlash) {
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;
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);
477 // encoding needed, we need to allocate a new string
478 if (res === undefined) {
479 res = uriComponent.substr(0, pos);
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;
489 // append escaped variant to result
492 else if (nativeEncodePos === -1) {
493 // use native encode only when needed
494 nativeEncodePos = pos;
498 if (nativeEncodePos !== -1) {
499 res += encodeURIComponent(uriComponent.substring(nativeEncodePos));
501 return res !== undefined ? res : uriComponent;
503 function encodeURIComponentMinimal(path) {
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);
511 res += encodeTable[code];
514 if (res !== undefined) {
519 return res !== undefined ? res : path;
522 * Compute `fsPath` for the given uri
524 export function uriToFsPath(uri, keepDriveLetterCasing) {
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;
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);
538 value = uri.path.substr(1);
546 value = value.replace(/\//g, '\\');
551 * Create the external version of a uri
553 function _asFormatted(uri, skipEncoding) {
554 var encoder = !skipEncoding
555 ? encodeURIComponentFast
556 : encodeURIComponentMinimal;
558 var scheme = uri.scheme, authority = uri.authority, path = uri.path, query = uri.query, fragment = uri.fragment;
563 if (authority || scheme === 'file') {
568 var idx = authority.indexOf('@');
571 var userinfo = authority.substr(0, idx);
572 authority = authority.substr(idx + 1);
573 idx = userinfo.indexOf(':');
575 res += encoder(userinfo, false);
578 // <user>:<pass>@<auth>
579 res += encoder(userinfo.substr(0, idx), false);
581 res += encoder(userinfo.substr(idx + 1), false);
585 authority = authority.toLowerCase();
586 idx = authority.indexOf(':');
588 res += encoder(authority, false);
592 res += encoder(authority.substr(0, idx), false);
593 res += authority.substr(idx);
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
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
610 // encode the rest of the path
611 res += encoder(path, true);
615 res += encoder(query, false);
619 res += !skipEncoding ? encodeURIComponentFast(fragment, false) : fragment;
624 function decodeURIComponentGraceful(str) {
626 return decodeURIComponent(str);
629 if (str.length > 3) {
630 return str.substr(0, 3) + decodeURIComponentGraceful(str.substr(3));
637 var _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g;
638 function percentDecode(str) {
639 if (!str.match(_rEncodedAsHex)) {
642 return str.replace(_rEncodedAsHex, function (match) { return decodeURIComponentGraceful(match); });