web.url.constructor.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  1. 'use strict';
  2. // TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env`
  3. require('../modules/es.string.iterator');
  4. var $ = require('../internals/export');
  5. var DESCRIPTORS = require('../internals/descriptors');
  6. var USE_NATIVE_URL = require('../internals/url-constructor-detection');
  7. var global = require('../internals/global');
  8. var bind = require('../internals/function-bind-context');
  9. var uncurryThis = require('../internals/function-uncurry-this');
  10. var defineBuiltIn = require('../internals/define-built-in');
  11. var defineBuiltInAccessor = require('../internals/define-built-in-accessor');
  12. var anInstance = require('../internals/an-instance');
  13. var hasOwn = require('../internals/has-own-property');
  14. var assign = require('../internals/object-assign');
  15. var arrayFrom = require('../internals/array-from');
  16. var arraySlice = require('../internals/array-slice-simple');
  17. var codeAt = require('../internals/string-multibyte').codeAt;
  18. var toASCII = require('../internals/string-punycode-to-ascii');
  19. var $toString = require('../internals/to-string');
  20. var setToStringTag = require('../internals/set-to-string-tag');
  21. var validateArgumentsLength = require('../internals/validate-arguments-length');
  22. var URLSearchParamsModule = require('../modules/web.url-search-params.constructor');
  23. var InternalStateModule = require('../internals/internal-state');
  24. var setInternalState = InternalStateModule.set;
  25. var getInternalURLState = InternalStateModule.getterFor('URL');
  26. var URLSearchParams = URLSearchParamsModule.URLSearchParams;
  27. var getInternalSearchParamsState = URLSearchParamsModule.getState;
  28. var NativeURL = global.URL;
  29. var TypeError = global.TypeError;
  30. var parseInt = global.parseInt;
  31. var floor = Math.floor;
  32. var pow = Math.pow;
  33. var charAt = uncurryThis(''.charAt);
  34. var exec = uncurryThis(/./.exec);
  35. var join = uncurryThis([].join);
  36. var numberToString = uncurryThis(1.0.toString);
  37. var pop = uncurryThis([].pop);
  38. var push = uncurryThis([].push);
  39. var replace = uncurryThis(''.replace);
  40. var shift = uncurryThis([].shift);
  41. var split = uncurryThis(''.split);
  42. var stringSlice = uncurryThis(''.slice);
  43. var toLowerCase = uncurryThis(''.toLowerCase);
  44. var unshift = uncurryThis([].unshift);
  45. var INVALID_AUTHORITY = 'Invalid authority';
  46. var INVALID_SCHEME = 'Invalid scheme';
  47. var INVALID_HOST = 'Invalid host';
  48. var INVALID_PORT = 'Invalid port';
  49. var ALPHA = /[a-z]/i;
  50. // eslint-disable-next-line regexp/no-obscure-range -- safe
  51. var ALPHANUMERIC = /[\d+-.a-z]/i;
  52. var DIGIT = /\d/;
  53. var HEX_START = /^0x/i;
  54. var OCT = /^[0-7]+$/;
  55. var DEC = /^\d+$/;
  56. var HEX = /^[\da-f]+$/i;
  57. /* eslint-disable regexp/no-control-character -- safe */
  58. var FORBIDDEN_HOST_CODE_POINT = /[\0\t\n\r #%/:<>?@[\\\]^|]/;
  59. var FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT = /[\0\t\n\r #/:<>?@[\\\]^|]/;
  60. var LEADING_C0_CONTROL_OR_SPACE = /^[\u0000-\u0020]+/;
  61. var TRAILING_C0_CONTROL_OR_SPACE = /(^|[^\u0000-\u0020])[\u0000-\u0020]+$/;
  62. var TAB_AND_NEW_LINE = /[\t\n\r]/g;
  63. /* eslint-enable regexp/no-control-character -- safe */
  64. var EOF;
  65. // https://url.spec.whatwg.org/#ipv4-number-parser
  66. var parseIPv4 = function (input) {
  67. var parts = split(input, '.');
  68. var partsLength, numbers, index, part, radix, number, ipv4;
  69. if (parts.length && parts[parts.length - 1] == '') {
  70. parts.length--;
  71. }
  72. partsLength = parts.length;
  73. if (partsLength > 4) return input;
  74. numbers = [];
  75. for (index = 0; index < partsLength; index++) {
  76. part = parts[index];
  77. if (part == '') return input;
  78. radix = 10;
  79. if (part.length > 1 && charAt(part, 0) == '0') {
  80. radix = exec(HEX_START, part) ? 16 : 8;
  81. part = stringSlice(part, radix == 8 ? 1 : 2);
  82. }
  83. if (part === '') {
  84. number = 0;
  85. } else {
  86. if (!exec(radix == 10 ? DEC : radix == 8 ? OCT : HEX, part)) return input;
  87. number = parseInt(part, radix);
  88. }
  89. push(numbers, number);
  90. }
  91. for (index = 0; index < partsLength; index++) {
  92. number = numbers[index];
  93. if (index == partsLength - 1) {
  94. if (number >= pow(256, 5 - partsLength)) return null;
  95. } else if (number > 255) return null;
  96. }
  97. ipv4 = pop(numbers);
  98. for (index = 0; index < numbers.length; index++) {
  99. ipv4 += numbers[index] * pow(256, 3 - index);
  100. }
  101. return ipv4;
  102. };
  103. // https://url.spec.whatwg.org/#concept-ipv6-parser
  104. // eslint-disable-next-line max-statements -- TODO
  105. var parseIPv6 = function (input) {
  106. var address = [0, 0, 0, 0, 0, 0, 0, 0];
  107. var pieceIndex = 0;
  108. var compress = null;
  109. var pointer = 0;
  110. var value, length, numbersSeen, ipv4Piece, number, swaps, swap;
  111. var chr = function () {
  112. return charAt(input, pointer);
  113. };
  114. if (chr() == ':') {
  115. if (charAt(input, 1) != ':') return;
  116. pointer += 2;
  117. pieceIndex++;
  118. compress = pieceIndex;
  119. }
  120. while (chr()) {
  121. if (pieceIndex == 8) return;
  122. if (chr() == ':') {
  123. if (compress !== null) return;
  124. pointer++;
  125. pieceIndex++;
  126. compress = pieceIndex;
  127. continue;
  128. }
  129. value = length = 0;
  130. while (length < 4 && exec(HEX, chr())) {
  131. value = value * 16 + parseInt(chr(), 16);
  132. pointer++;
  133. length++;
  134. }
  135. if (chr() == '.') {
  136. if (length == 0) return;
  137. pointer -= length;
  138. if (pieceIndex > 6) return;
  139. numbersSeen = 0;
  140. while (chr()) {
  141. ipv4Piece = null;
  142. if (numbersSeen > 0) {
  143. if (chr() == '.' && numbersSeen < 4) pointer++;
  144. else return;
  145. }
  146. if (!exec(DIGIT, chr())) return;
  147. while (exec(DIGIT, chr())) {
  148. number = parseInt(chr(), 10);
  149. if (ipv4Piece === null) ipv4Piece = number;
  150. else if (ipv4Piece == 0) return;
  151. else ipv4Piece = ipv4Piece * 10 + number;
  152. if (ipv4Piece > 255) return;
  153. pointer++;
  154. }
  155. address[pieceIndex] = address[pieceIndex] * 256 + ipv4Piece;
  156. numbersSeen++;
  157. if (numbersSeen == 2 || numbersSeen == 4) pieceIndex++;
  158. }
  159. if (numbersSeen != 4) return;
  160. break;
  161. } else if (chr() == ':') {
  162. pointer++;
  163. if (!chr()) return;
  164. } else if (chr()) return;
  165. address[pieceIndex++] = value;
  166. }
  167. if (compress !== null) {
  168. swaps = pieceIndex - compress;
  169. pieceIndex = 7;
  170. while (pieceIndex != 0 && swaps > 0) {
  171. swap = address[pieceIndex];
  172. address[pieceIndex--] = address[compress + swaps - 1];
  173. address[compress + --swaps] = swap;
  174. }
  175. } else if (pieceIndex != 8) return;
  176. return address;
  177. };
  178. var findLongestZeroSequence = function (ipv6) {
  179. var maxIndex = null;
  180. var maxLength = 1;
  181. var currStart = null;
  182. var currLength = 0;
  183. var index = 0;
  184. for (; index < 8; index++) {
  185. if (ipv6[index] !== 0) {
  186. if (currLength > maxLength) {
  187. maxIndex = currStart;
  188. maxLength = currLength;
  189. }
  190. currStart = null;
  191. currLength = 0;
  192. } else {
  193. if (currStart === null) currStart = index;
  194. ++currLength;
  195. }
  196. }
  197. if (currLength > maxLength) {
  198. maxIndex = currStart;
  199. maxLength = currLength;
  200. }
  201. return maxIndex;
  202. };
  203. // https://url.spec.whatwg.org/#host-serializing
  204. var serializeHost = function (host) {
  205. var result, index, compress, ignore0;
  206. // ipv4
  207. if (typeof host == 'number') {
  208. result = [];
  209. for (index = 0; index < 4; index++) {
  210. unshift(result, host % 256);
  211. host = floor(host / 256);
  212. } return join(result, '.');
  213. // ipv6
  214. } else if (typeof host == 'object') {
  215. result = '';
  216. compress = findLongestZeroSequence(host);
  217. for (index = 0; index < 8; index++) {
  218. if (ignore0 && host[index] === 0) continue;
  219. if (ignore0) ignore0 = false;
  220. if (compress === index) {
  221. result += index ? ':' : '::';
  222. ignore0 = true;
  223. } else {
  224. result += numberToString(host[index], 16);
  225. if (index < 7) result += ':';
  226. }
  227. }
  228. return '[' + result + ']';
  229. } return host;
  230. };
  231. var C0ControlPercentEncodeSet = {};
  232. var fragmentPercentEncodeSet = assign({}, C0ControlPercentEncodeSet, {
  233. ' ': 1, '"': 1, '<': 1, '>': 1, '`': 1
  234. });
  235. var pathPercentEncodeSet = assign({}, fragmentPercentEncodeSet, {
  236. '#': 1, '?': 1, '{': 1, '}': 1
  237. });
  238. var userinfoPercentEncodeSet = assign({}, pathPercentEncodeSet, {
  239. '/': 1, ':': 1, ';': 1, '=': 1, '@': 1, '[': 1, '\\': 1, ']': 1, '^': 1, '|': 1
  240. });
  241. var percentEncode = function (chr, set) {
  242. var code = codeAt(chr, 0);
  243. return code > 0x20 && code < 0x7F && !hasOwn(set, chr) ? chr : encodeURIComponent(chr);
  244. };
  245. // https://url.spec.whatwg.org/#special-scheme
  246. var specialSchemes = {
  247. ftp: 21,
  248. file: null,
  249. http: 80,
  250. https: 443,
  251. ws: 80,
  252. wss: 443
  253. };
  254. // https://url.spec.whatwg.org/#windows-drive-letter
  255. var isWindowsDriveLetter = function (string, normalized) {
  256. var second;
  257. return string.length == 2 && exec(ALPHA, charAt(string, 0))
  258. && ((second = charAt(string, 1)) == ':' || (!normalized && second == '|'));
  259. };
  260. // https://url.spec.whatwg.org/#start-with-a-windows-drive-letter
  261. var startsWithWindowsDriveLetter = function (string) {
  262. var third;
  263. return string.length > 1 && isWindowsDriveLetter(stringSlice(string, 0, 2)) && (
  264. string.length == 2 ||
  265. ((third = charAt(string, 2)) === '/' || third === '\\' || third === '?' || third === '#')
  266. );
  267. };
  268. // https://url.spec.whatwg.org/#single-dot-path-segment
  269. var isSingleDot = function (segment) {
  270. return segment === '.' || toLowerCase(segment) === '%2e';
  271. };
  272. // https://url.spec.whatwg.org/#double-dot-path-segment
  273. var isDoubleDot = function (segment) {
  274. segment = toLowerCase(segment);
  275. return segment === '..' || segment === '%2e.' || segment === '.%2e' || segment === '%2e%2e';
  276. };
  277. // States:
  278. var SCHEME_START = {};
  279. var SCHEME = {};
  280. var NO_SCHEME = {};
  281. var SPECIAL_RELATIVE_OR_AUTHORITY = {};
  282. var PATH_OR_AUTHORITY = {};
  283. var RELATIVE = {};
  284. var RELATIVE_SLASH = {};
  285. var SPECIAL_AUTHORITY_SLASHES = {};
  286. var SPECIAL_AUTHORITY_IGNORE_SLASHES = {};
  287. var AUTHORITY = {};
  288. var HOST = {};
  289. var HOSTNAME = {};
  290. var PORT = {};
  291. var FILE = {};
  292. var FILE_SLASH = {};
  293. var FILE_HOST = {};
  294. var PATH_START = {};
  295. var PATH = {};
  296. var CANNOT_BE_A_BASE_URL_PATH = {};
  297. var QUERY = {};
  298. var FRAGMENT = {};
  299. var URLState = function (url, isBase, base) {
  300. var urlString = $toString(url);
  301. var baseState, failure, searchParams;
  302. if (isBase) {
  303. failure = this.parse(urlString);
  304. if (failure) throw TypeError(failure);
  305. this.searchParams = null;
  306. } else {
  307. if (base !== undefined) baseState = new URLState(base, true);
  308. failure = this.parse(urlString, null, baseState);
  309. if (failure) throw TypeError(failure);
  310. searchParams = getInternalSearchParamsState(new URLSearchParams());
  311. searchParams.bindURL(this);
  312. this.searchParams = searchParams;
  313. }
  314. };
  315. URLState.prototype = {
  316. type: 'URL',
  317. // https://url.spec.whatwg.org/#url-parsing
  318. // eslint-disable-next-line max-statements -- TODO
  319. parse: function (input, stateOverride, base) {
  320. var url = this;
  321. var state = stateOverride || SCHEME_START;
  322. var pointer = 0;
  323. var buffer = '';
  324. var seenAt = false;
  325. var seenBracket = false;
  326. var seenPasswordToken = false;
  327. var codePoints, chr, bufferCodePoints, failure;
  328. input = $toString(input);
  329. if (!stateOverride) {
  330. url.scheme = '';
  331. url.username = '';
  332. url.password = '';
  333. url.host = null;
  334. url.port = null;
  335. url.path = [];
  336. url.query = null;
  337. url.fragment = null;
  338. url.cannotBeABaseURL = false;
  339. input = replace(input, LEADING_C0_CONTROL_OR_SPACE, '');
  340. input = replace(input, TRAILING_C0_CONTROL_OR_SPACE, '$1');
  341. }
  342. input = replace(input, TAB_AND_NEW_LINE, '');
  343. codePoints = arrayFrom(input);
  344. while (pointer <= codePoints.length) {
  345. chr = codePoints[pointer];
  346. switch (state) {
  347. case SCHEME_START:
  348. if (chr && exec(ALPHA, chr)) {
  349. buffer += toLowerCase(chr);
  350. state = SCHEME;
  351. } else if (!stateOverride) {
  352. state = NO_SCHEME;
  353. continue;
  354. } else return INVALID_SCHEME;
  355. break;
  356. case SCHEME:
  357. if (chr && (exec(ALPHANUMERIC, chr) || chr == '+' || chr == '-' || chr == '.')) {
  358. buffer += toLowerCase(chr);
  359. } else if (chr == ':') {
  360. if (stateOverride && (
  361. (url.isSpecial() != hasOwn(specialSchemes, buffer)) ||
  362. (buffer == 'file' && (url.includesCredentials() || url.port !== null)) ||
  363. (url.scheme == 'file' && !url.host)
  364. )) return;
  365. url.scheme = buffer;
  366. if (stateOverride) {
  367. if (url.isSpecial() && specialSchemes[url.scheme] == url.port) url.port = null;
  368. return;
  369. }
  370. buffer = '';
  371. if (url.scheme == 'file') {
  372. state = FILE;
  373. } else if (url.isSpecial() && base && base.scheme == url.scheme) {
  374. state = SPECIAL_RELATIVE_OR_AUTHORITY;
  375. } else if (url.isSpecial()) {
  376. state = SPECIAL_AUTHORITY_SLASHES;
  377. } else if (codePoints[pointer + 1] == '/') {
  378. state = PATH_OR_AUTHORITY;
  379. pointer++;
  380. } else {
  381. url.cannotBeABaseURL = true;
  382. push(url.path, '');
  383. state = CANNOT_BE_A_BASE_URL_PATH;
  384. }
  385. } else if (!stateOverride) {
  386. buffer = '';
  387. state = NO_SCHEME;
  388. pointer = 0;
  389. continue;
  390. } else return INVALID_SCHEME;
  391. break;
  392. case NO_SCHEME:
  393. if (!base || (base.cannotBeABaseURL && chr != '#')) return INVALID_SCHEME;
  394. if (base.cannotBeABaseURL && chr == '#') {
  395. url.scheme = base.scheme;
  396. url.path = arraySlice(base.path);
  397. url.query = base.query;
  398. url.fragment = '';
  399. url.cannotBeABaseURL = true;
  400. state = FRAGMENT;
  401. break;
  402. }
  403. state = base.scheme == 'file' ? FILE : RELATIVE;
  404. continue;
  405. case SPECIAL_RELATIVE_OR_AUTHORITY:
  406. if (chr == '/' && codePoints[pointer + 1] == '/') {
  407. state = SPECIAL_AUTHORITY_IGNORE_SLASHES;
  408. pointer++;
  409. } else {
  410. state = RELATIVE;
  411. continue;
  412. } break;
  413. case PATH_OR_AUTHORITY:
  414. if (chr == '/') {
  415. state = AUTHORITY;
  416. break;
  417. } else {
  418. state = PATH;
  419. continue;
  420. }
  421. case RELATIVE:
  422. url.scheme = base.scheme;
  423. if (chr == EOF) {
  424. url.username = base.username;
  425. url.password = base.password;
  426. url.host = base.host;
  427. url.port = base.port;
  428. url.path = arraySlice(base.path);
  429. url.query = base.query;
  430. } else if (chr == '/' || (chr == '\\' && url.isSpecial())) {
  431. state = RELATIVE_SLASH;
  432. } else if (chr == '?') {
  433. url.username = base.username;
  434. url.password = base.password;
  435. url.host = base.host;
  436. url.port = base.port;
  437. url.path = arraySlice(base.path);
  438. url.query = '';
  439. state = QUERY;
  440. } else if (chr == '#') {
  441. url.username = base.username;
  442. url.password = base.password;
  443. url.host = base.host;
  444. url.port = base.port;
  445. url.path = arraySlice(base.path);
  446. url.query = base.query;
  447. url.fragment = '';
  448. state = FRAGMENT;
  449. } else {
  450. url.username = base.username;
  451. url.password = base.password;
  452. url.host = base.host;
  453. url.port = base.port;
  454. url.path = arraySlice(base.path);
  455. url.path.length--;
  456. state = PATH;
  457. continue;
  458. } break;
  459. case RELATIVE_SLASH:
  460. if (url.isSpecial() && (chr == '/' || chr == '\\')) {
  461. state = SPECIAL_AUTHORITY_IGNORE_SLASHES;
  462. } else if (chr == '/') {
  463. state = AUTHORITY;
  464. } else {
  465. url.username = base.username;
  466. url.password = base.password;
  467. url.host = base.host;
  468. url.port = base.port;
  469. state = PATH;
  470. continue;
  471. } break;
  472. case SPECIAL_AUTHORITY_SLASHES:
  473. state = SPECIAL_AUTHORITY_IGNORE_SLASHES;
  474. if (chr != '/' || charAt(buffer, pointer + 1) != '/') continue;
  475. pointer++;
  476. break;
  477. case SPECIAL_AUTHORITY_IGNORE_SLASHES:
  478. if (chr != '/' && chr != '\\') {
  479. state = AUTHORITY;
  480. continue;
  481. } break;
  482. case AUTHORITY:
  483. if (chr == '@') {
  484. if (seenAt) buffer = '%40' + buffer;
  485. seenAt = true;
  486. bufferCodePoints = arrayFrom(buffer);
  487. for (var i = 0; i < bufferCodePoints.length; i++) {
  488. var codePoint = bufferCodePoints[i];
  489. if (codePoint == ':' && !seenPasswordToken) {
  490. seenPasswordToken = true;
  491. continue;
  492. }
  493. var encodedCodePoints = percentEncode(codePoint, userinfoPercentEncodeSet);
  494. if (seenPasswordToken) url.password += encodedCodePoints;
  495. else url.username += encodedCodePoints;
  496. }
  497. buffer = '';
  498. } else if (
  499. chr == EOF || chr == '/' || chr == '?' || chr == '#' ||
  500. (chr == '\\' && url.isSpecial())
  501. ) {
  502. if (seenAt && buffer == '') return INVALID_AUTHORITY;
  503. pointer -= arrayFrom(buffer).length + 1;
  504. buffer = '';
  505. state = HOST;
  506. } else buffer += chr;
  507. break;
  508. case HOST:
  509. case HOSTNAME:
  510. if (stateOverride && url.scheme == 'file') {
  511. state = FILE_HOST;
  512. continue;
  513. } else if (chr == ':' && !seenBracket) {
  514. if (buffer == '') return INVALID_HOST;
  515. failure = url.parseHost(buffer);
  516. if (failure) return failure;
  517. buffer = '';
  518. state = PORT;
  519. if (stateOverride == HOSTNAME) return;
  520. } else if (
  521. chr == EOF || chr == '/' || chr == '?' || chr == '#' ||
  522. (chr == '\\' && url.isSpecial())
  523. ) {
  524. if (url.isSpecial() && buffer == '') return INVALID_HOST;
  525. if (stateOverride && buffer == '' && (url.includesCredentials() || url.port !== null)) return;
  526. failure = url.parseHost(buffer);
  527. if (failure) return failure;
  528. buffer = '';
  529. state = PATH_START;
  530. if (stateOverride) return;
  531. continue;
  532. } else {
  533. if (chr == '[') seenBracket = true;
  534. else if (chr == ']') seenBracket = false;
  535. buffer += chr;
  536. } break;
  537. case PORT:
  538. if (exec(DIGIT, chr)) {
  539. buffer += chr;
  540. } else if (
  541. chr == EOF || chr == '/' || chr == '?' || chr == '#' ||
  542. (chr == '\\' && url.isSpecial()) ||
  543. stateOverride
  544. ) {
  545. if (buffer != '') {
  546. var port = parseInt(buffer, 10);
  547. if (port > 0xFFFF) return INVALID_PORT;
  548. url.port = (url.isSpecial() && port === specialSchemes[url.scheme]) ? null : port;
  549. buffer = '';
  550. }
  551. if (stateOverride) return;
  552. state = PATH_START;
  553. continue;
  554. } else return INVALID_PORT;
  555. break;
  556. case FILE:
  557. url.scheme = 'file';
  558. if (chr == '/' || chr == '\\') state = FILE_SLASH;
  559. else if (base && base.scheme == 'file') {
  560. if (chr == EOF) {
  561. url.host = base.host;
  562. url.path = arraySlice(base.path);
  563. url.query = base.query;
  564. } else if (chr == '?') {
  565. url.host = base.host;
  566. url.path = arraySlice(base.path);
  567. url.query = '';
  568. state = QUERY;
  569. } else if (chr == '#') {
  570. url.host = base.host;
  571. url.path = arraySlice(base.path);
  572. url.query = base.query;
  573. url.fragment = '';
  574. state = FRAGMENT;
  575. } else {
  576. if (!startsWithWindowsDriveLetter(join(arraySlice(codePoints, pointer), ''))) {
  577. url.host = base.host;
  578. url.path = arraySlice(base.path);
  579. url.shortenPath();
  580. }
  581. state = PATH;
  582. continue;
  583. }
  584. } else {
  585. state = PATH;
  586. continue;
  587. } break;
  588. case FILE_SLASH:
  589. if (chr == '/' || chr == '\\') {
  590. state = FILE_HOST;
  591. break;
  592. }
  593. if (base && base.scheme == 'file' && !startsWithWindowsDriveLetter(join(arraySlice(codePoints, pointer), ''))) {
  594. if (isWindowsDriveLetter(base.path[0], true)) push(url.path, base.path[0]);
  595. else url.host = base.host;
  596. }
  597. state = PATH;
  598. continue;
  599. case FILE_HOST:
  600. if (chr == EOF || chr == '/' || chr == '\\' || chr == '?' || chr == '#') {
  601. if (!stateOverride && isWindowsDriveLetter(buffer)) {
  602. state = PATH;
  603. } else if (buffer == '') {
  604. url.host = '';
  605. if (stateOverride) return;
  606. state = PATH_START;
  607. } else {
  608. failure = url.parseHost(buffer);
  609. if (failure) return failure;
  610. if (url.host == 'localhost') url.host = '';
  611. if (stateOverride) return;
  612. buffer = '';
  613. state = PATH_START;
  614. } continue;
  615. } else buffer += chr;
  616. break;
  617. case PATH_START:
  618. if (url.isSpecial()) {
  619. state = PATH;
  620. if (chr != '/' && chr != '\\') continue;
  621. } else if (!stateOverride && chr == '?') {
  622. url.query = '';
  623. state = QUERY;
  624. } else if (!stateOverride && chr == '#') {
  625. url.fragment = '';
  626. state = FRAGMENT;
  627. } else if (chr != EOF) {
  628. state = PATH;
  629. if (chr != '/') continue;
  630. } break;
  631. case PATH:
  632. if (
  633. chr == EOF || chr == '/' ||
  634. (chr == '\\' && url.isSpecial()) ||
  635. (!stateOverride && (chr == '?' || chr == '#'))
  636. ) {
  637. if (isDoubleDot(buffer)) {
  638. url.shortenPath();
  639. if (chr != '/' && !(chr == '\\' && url.isSpecial())) {
  640. push(url.path, '');
  641. }
  642. } else if (isSingleDot(buffer)) {
  643. if (chr != '/' && !(chr == '\\' && url.isSpecial())) {
  644. push(url.path, '');
  645. }
  646. } else {
  647. if (url.scheme == 'file' && !url.path.length && isWindowsDriveLetter(buffer)) {
  648. if (url.host) url.host = '';
  649. buffer = charAt(buffer, 0) + ':'; // normalize windows drive letter
  650. }
  651. push(url.path, buffer);
  652. }
  653. buffer = '';
  654. if (url.scheme == 'file' && (chr == EOF || chr == '?' || chr == '#')) {
  655. while (url.path.length > 1 && url.path[0] === '') {
  656. shift(url.path);
  657. }
  658. }
  659. if (chr == '?') {
  660. url.query = '';
  661. state = QUERY;
  662. } else if (chr == '#') {
  663. url.fragment = '';
  664. state = FRAGMENT;
  665. }
  666. } else {
  667. buffer += percentEncode(chr, pathPercentEncodeSet);
  668. } break;
  669. case CANNOT_BE_A_BASE_URL_PATH:
  670. if (chr == '?') {
  671. url.query = '';
  672. state = QUERY;
  673. } else if (chr == '#') {
  674. url.fragment = '';
  675. state = FRAGMENT;
  676. } else if (chr != EOF) {
  677. url.path[0] += percentEncode(chr, C0ControlPercentEncodeSet);
  678. } break;
  679. case QUERY:
  680. if (!stateOverride && chr == '#') {
  681. url.fragment = '';
  682. state = FRAGMENT;
  683. } else if (chr != EOF) {
  684. if (chr == "'" && url.isSpecial()) url.query += '%27';
  685. else if (chr == '#') url.query += '%23';
  686. else url.query += percentEncode(chr, C0ControlPercentEncodeSet);
  687. } break;
  688. case FRAGMENT:
  689. if (chr != EOF) url.fragment += percentEncode(chr, fragmentPercentEncodeSet);
  690. break;
  691. }
  692. pointer++;
  693. }
  694. },
  695. // https://url.spec.whatwg.org/#host-parsing
  696. parseHost: function (input) {
  697. var result, codePoints, index;
  698. if (charAt(input, 0) == '[') {
  699. if (charAt(input, input.length - 1) != ']') return INVALID_HOST;
  700. result = parseIPv6(stringSlice(input, 1, -1));
  701. if (!result) return INVALID_HOST;
  702. this.host = result;
  703. // opaque host
  704. } else if (!this.isSpecial()) {
  705. if (exec(FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT, input)) return INVALID_HOST;
  706. result = '';
  707. codePoints = arrayFrom(input);
  708. for (index = 0; index < codePoints.length; index++) {
  709. result += percentEncode(codePoints[index], C0ControlPercentEncodeSet);
  710. }
  711. this.host = result;
  712. } else {
  713. input = toASCII(input);
  714. if (exec(FORBIDDEN_HOST_CODE_POINT, input)) return INVALID_HOST;
  715. result = parseIPv4(input);
  716. if (result === null) return INVALID_HOST;
  717. this.host = result;
  718. }
  719. },
  720. // https://url.spec.whatwg.org/#cannot-have-a-username-password-port
  721. cannotHaveUsernamePasswordPort: function () {
  722. return !this.host || this.cannotBeABaseURL || this.scheme == 'file';
  723. },
  724. // https://url.spec.whatwg.org/#include-credentials
  725. includesCredentials: function () {
  726. return this.username != '' || this.password != '';
  727. },
  728. // https://url.spec.whatwg.org/#is-special
  729. isSpecial: function () {
  730. return hasOwn(specialSchemes, this.scheme);
  731. },
  732. // https://url.spec.whatwg.org/#shorten-a-urls-path
  733. shortenPath: function () {
  734. var path = this.path;
  735. var pathSize = path.length;
  736. if (pathSize && (this.scheme != 'file' || pathSize != 1 || !isWindowsDriveLetter(path[0], true))) {
  737. path.length--;
  738. }
  739. },
  740. // https://url.spec.whatwg.org/#concept-url-serializer
  741. serialize: function () {
  742. var url = this;
  743. var scheme = url.scheme;
  744. var username = url.username;
  745. var password = url.password;
  746. var host = url.host;
  747. var port = url.port;
  748. var path = url.path;
  749. var query = url.query;
  750. var fragment = url.fragment;
  751. var output = scheme + ':';
  752. if (host !== null) {
  753. output += '//';
  754. if (url.includesCredentials()) {
  755. output += username + (password ? ':' + password : '') + '@';
  756. }
  757. output += serializeHost(host);
  758. if (port !== null) output += ':' + port;
  759. } else if (scheme == 'file') output += '//';
  760. output += url.cannotBeABaseURL ? path[0] : path.length ? '/' + join(path, '/') : '';
  761. if (query !== null) output += '?' + query;
  762. if (fragment !== null) output += '#' + fragment;
  763. return output;
  764. },
  765. // https://url.spec.whatwg.org/#dom-url-href
  766. setHref: function (href) {
  767. var failure = this.parse(href);
  768. if (failure) throw TypeError(failure);
  769. this.searchParams.update();
  770. },
  771. // https://url.spec.whatwg.org/#dom-url-origin
  772. getOrigin: function () {
  773. var scheme = this.scheme;
  774. var port = this.port;
  775. if (scheme == 'blob') try {
  776. return new URLConstructor(scheme.path[0]).origin;
  777. } catch (error) {
  778. return 'null';
  779. }
  780. if (scheme == 'file' || !this.isSpecial()) return 'null';
  781. return scheme + '://' + serializeHost(this.host) + (port !== null ? ':' + port : '');
  782. },
  783. // https://url.spec.whatwg.org/#dom-url-protocol
  784. getProtocol: function () {
  785. return this.scheme + ':';
  786. },
  787. setProtocol: function (protocol) {
  788. this.parse($toString(protocol) + ':', SCHEME_START);
  789. },
  790. // https://url.spec.whatwg.org/#dom-url-username
  791. getUsername: function () {
  792. return this.username;
  793. },
  794. setUsername: function (username) {
  795. var codePoints = arrayFrom($toString(username));
  796. if (this.cannotHaveUsernamePasswordPort()) return;
  797. this.username = '';
  798. for (var i = 0; i < codePoints.length; i++) {
  799. this.username += percentEncode(codePoints[i], userinfoPercentEncodeSet);
  800. }
  801. },
  802. // https://url.spec.whatwg.org/#dom-url-password
  803. getPassword: function () {
  804. return this.password;
  805. },
  806. setPassword: function (password) {
  807. var codePoints = arrayFrom($toString(password));
  808. if (this.cannotHaveUsernamePasswordPort()) return;
  809. this.password = '';
  810. for (var i = 0; i < codePoints.length; i++) {
  811. this.password += percentEncode(codePoints[i], userinfoPercentEncodeSet);
  812. }
  813. },
  814. // https://url.spec.whatwg.org/#dom-url-host
  815. getHost: function () {
  816. var host = this.host;
  817. var port = this.port;
  818. return host === null ? ''
  819. : port === null ? serializeHost(host)
  820. : serializeHost(host) + ':' + port;
  821. },
  822. setHost: function (host) {
  823. if (this.cannotBeABaseURL) return;
  824. this.parse(host, HOST);
  825. },
  826. // https://url.spec.whatwg.org/#dom-url-hostname
  827. getHostname: function () {
  828. var host = this.host;
  829. return host === null ? '' : serializeHost(host);
  830. },
  831. setHostname: function (hostname) {
  832. if (this.cannotBeABaseURL) return;
  833. this.parse(hostname, HOSTNAME);
  834. },
  835. // https://url.spec.whatwg.org/#dom-url-port
  836. getPort: function () {
  837. var port = this.port;
  838. return port === null ? '' : $toString(port);
  839. },
  840. setPort: function (port) {
  841. if (this.cannotHaveUsernamePasswordPort()) return;
  842. port = $toString(port);
  843. if (port == '') this.port = null;
  844. else this.parse(port, PORT);
  845. },
  846. // https://url.spec.whatwg.org/#dom-url-pathname
  847. getPathname: function () {
  848. var path = this.path;
  849. return this.cannotBeABaseURL ? path[0] : path.length ? '/' + join(path, '/') : '';
  850. },
  851. setPathname: function (pathname) {
  852. if (this.cannotBeABaseURL) return;
  853. this.path = [];
  854. this.parse(pathname, PATH_START);
  855. },
  856. // https://url.spec.whatwg.org/#dom-url-search
  857. getSearch: function () {
  858. var query = this.query;
  859. return query ? '?' + query : '';
  860. },
  861. setSearch: function (search) {
  862. search = $toString(search);
  863. if (search == '') {
  864. this.query = null;
  865. } else {
  866. if ('?' == charAt(search, 0)) search = stringSlice(search, 1);
  867. this.query = '';
  868. this.parse(search, QUERY);
  869. }
  870. this.searchParams.update();
  871. },
  872. // https://url.spec.whatwg.org/#dom-url-searchparams
  873. getSearchParams: function () {
  874. return this.searchParams.facade;
  875. },
  876. // https://url.spec.whatwg.org/#dom-url-hash
  877. getHash: function () {
  878. var fragment = this.fragment;
  879. return fragment ? '#' + fragment : '';
  880. },
  881. setHash: function (hash) {
  882. hash = $toString(hash);
  883. if (hash == '') {
  884. this.fragment = null;
  885. return;
  886. }
  887. if ('#' == charAt(hash, 0)) hash = stringSlice(hash, 1);
  888. this.fragment = '';
  889. this.parse(hash, FRAGMENT);
  890. },
  891. update: function () {
  892. this.query = this.searchParams.serialize() || null;
  893. }
  894. };
  895. // `URL` constructor
  896. // https://url.spec.whatwg.org/#url-class
  897. var URLConstructor = function URL(url /* , base */) {
  898. var that = anInstance(this, URLPrototype);
  899. var base = validateArgumentsLength(arguments.length, 1) > 1 ? arguments[1] : undefined;
  900. var state = setInternalState(that, new URLState(url, false, base));
  901. if (!DESCRIPTORS) {
  902. that.href = state.serialize();
  903. that.origin = state.getOrigin();
  904. that.protocol = state.getProtocol();
  905. that.username = state.getUsername();
  906. that.password = state.getPassword();
  907. that.host = state.getHost();
  908. that.hostname = state.getHostname();
  909. that.port = state.getPort();
  910. that.pathname = state.getPathname();
  911. that.search = state.getSearch();
  912. that.searchParams = state.getSearchParams();
  913. that.hash = state.getHash();
  914. }
  915. };
  916. var URLPrototype = URLConstructor.prototype;
  917. var accessorDescriptor = function (getter, setter) {
  918. return {
  919. get: function () {
  920. return getInternalURLState(this)[getter]();
  921. },
  922. set: setter && function (value) {
  923. return getInternalURLState(this)[setter](value);
  924. },
  925. configurable: true,
  926. enumerable: true
  927. };
  928. };
  929. if (DESCRIPTORS) {
  930. // `URL.prototype.href` accessors pair
  931. // https://url.spec.whatwg.org/#dom-url-href
  932. defineBuiltInAccessor(URLPrototype, 'href', accessorDescriptor('serialize', 'setHref'));
  933. // `URL.prototype.origin` getter
  934. // https://url.spec.whatwg.org/#dom-url-origin
  935. defineBuiltInAccessor(URLPrototype, 'origin', accessorDescriptor('getOrigin'));
  936. // `URL.prototype.protocol` accessors pair
  937. // https://url.spec.whatwg.org/#dom-url-protocol
  938. defineBuiltInAccessor(URLPrototype, 'protocol', accessorDescriptor('getProtocol', 'setProtocol'));
  939. // `URL.prototype.username` accessors pair
  940. // https://url.spec.whatwg.org/#dom-url-username
  941. defineBuiltInAccessor(URLPrototype, 'username', accessorDescriptor('getUsername', 'setUsername'));
  942. // `URL.prototype.password` accessors pair
  943. // https://url.spec.whatwg.org/#dom-url-password
  944. defineBuiltInAccessor(URLPrototype, 'password', accessorDescriptor('getPassword', 'setPassword'));
  945. // `URL.prototype.host` accessors pair
  946. // https://url.spec.whatwg.org/#dom-url-host
  947. defineBuiltInAccessor(URLPrototype, 'host', accessorDescriptor('getHost', 'setHost'));
  948. // `URL.prototype.hostname` accessors pair
  949. // https://url.spec.whatwg.org/#dom-url-hostname
  950. defineBuiltInAccessor(URLPrototype, 'hostname', accessorDescriptor('getHostname', 'setHostname'));
  951. // `URL.prototype.port` accessors pair
  952. // https://url.spec.whatwg.org/#dom-url-port
  953. defineBuiltInAccessor(URLPrototype, 'port', accessorDescriptor('getPort', 'setPort'));
  954. // `URL.prototype.pathname` accessors pair
  955. // https://url.spec.whatwg.org/#dom-url-pathname
  956. defineBuiltInAccessor(URLPrototype, 'pathname', accessorDescriptor('getPathname', 'setPathname'));
  957. // `URL.prototype.search` accessors pair
  958. // https://url.spec.whatwg.org/#dom-url-search
  959. defineBuiltInAccessor(URLPrototype, 'search', accessorDescriptor('getSearch', 'setSearch'));
  960. // `URL.prototype.searchParams` getter
  961. // https://url.spec.whatwg.org/#dom-url-searchparams
  962. defineBuiltInAccessor(URLPrototype, 'searchParams', accessorDescriptor('getSearchParams'));
  963. // `URL.prototype.hash` accessors pair
  964. // https://url.spec.whatwg.org/#dom-url-hash
  965. defineBuiltInAccessor(URLPrototype, 'hash', accessorDescriptor('getHash', 'setHash'));
  966. }
  967. // `URL.prototype.toJSON` method
  968. // https://url.spec.whatwg.org/#dom-url-tojson
  969. defineBuiltIn(URLPrototype, 'toJSON', function toJSON() {
  970. return getInternalURLState(this).serialize();
  971. }, { enumerable: true });
  972. // `URL.prototype.toString` method
  973. // https://url.spec.whatwg.org/#URL-stringification-behavior
  974. defineBuiltIn(URLPrototype, 'toString', function toString() {
  975. return getInternalURLState(this).serialize();
  976. }, { enumerable: true });
  977. if (NativeURL) {
  978. var nativeCreateObjectURL = NativeURL.createObjectURL;
  979. var nativeRevokeObjectURL = NativeURL.revokeObjectURL;
  980. // `URL.createObjectURL` method
  981. // https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
  982. if (nativeCreateObjectURL) defineBuiltIn(URLConstructor, 'createObjectURL', bind(nativeCreateObjectURL, NativeURL));
  983. // `URL.revokeObjectURL` method
  984. // https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL
  985. if (nativeRevokeObjectURL) defineBuiltIn(URLConstructor, 'revokeObjectURL', bind(nativeRevokeObjectURL, NativeURL));
  986. }
  987. setToStringTag(URLConstructor, 'URL');
  988. $({ global: true, constructor: true, forced: !USE_NATIVE_URL, sham: !DESCRIPTORS }, {
  989. URL: URLConstructor
  990. });