upgrade.mjs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. /**
  2. * @license Angular v20.1.0
  3. * (c) 2010-2025 Google LLC. https://angular.io/
  4. * License: MIT
  5. */
  6. import * as i0 from '@angular/core';
  7. import { ɵisPromise as _isPromise, InjectionToken, Inject, Optional, NgModule } from '@angular/core';
  8. import { ReplaySubject } from 'rxjs';
  9. import { UpgradeModule } from '@angular/upgrade/static';
  10. import { Location, PlatformLocation, LocationStrategy, APP_BASE_HREF, PathLocationStrategy } from './location.mjs';
  11. import { CommonModule, HashLocationStrategy } from './common_module.mjs';
  12. function deepEqual(a, b) {
  13. if (a === b) {
  14. return true;
  15. }
  16. else if (!a || !b) {
  17. return false;
  18. }
  19. else {
  20. try {
  21. if (a.prototype !== b.prototype || (Array.isArray(a) && Array.isArray(b))) {
  22. return false;
  23. }
  24. return JSON.stringify(a) === JSON.stringify(b);
  25. }
  26. catch (e) {
  27. return false;
  28. }
  29. }
  30. }
  31. function isAnchor(el) {
  32. return el.href !== undefined;
  33. }
  34. const PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/;
  35. const DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/;
  36. const IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  37. const DEFAULT_PORTS = {
  38. 'http:': 80,
  39. 'https:': 443,
  40. 'ftp:': 21,
  41. };
  42. /**
  43. * Location service that provides a drop-in replacement for the $location service
  44. * provided in AngularJS.
  45. *
  46. * @see [Using the Angular Unified Location Service](guide/upgrade#using-the-unified-angular-location-service)
  47. *
  48. * @publicApi
  49. */
  50. class $locationShim {
  51. location;
  52. platformLocation;
  53. urlCodec;
  54. locationStrategy;
  55. initializing = true;
  56. updateBrowser = false;
  57. $$absUrl = '';
  58. $$url = '';
  59. $$protocol;
  60. $$host = '';
  61. $$port;
  62. $$replace = false;
  63. $$path = '';
  64. $$search = '';
  65. $$hash = '';
  66. $$state;
  67. $$changeListeners = [];
  68. cachedState = null;
  69. urlChanges = new ReplaySubject(1);
  70. removeOnUrlChangeFn;
  71. constructor($injector, location, platformLocation, urlCodec, locationStrategy) {
  72. this.location = location;
  73. this.platformLocation = platformLocation;
  74. this.urlCodec = urlCodec;
  75. this.locationStrategy = locationStrategy;
  76. const initialUrl = this.browserUrl();
  77. let parsedUrl = this.urlCodec.parse(initialUrl);
  78. if (typeof parsedUrl === 'string') {
  79. throw 'Invalid URL';
  80. }
  81. this.$$protocol = parsedUrl.protocol;
  82. this.$$host = parsedUrl.hostname;
  83. this.$$port = parseInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  84. this.$$parseLinkUrl(initialUrl, initialUrl);
  85. this.cacheState();
  86. this.$$state = this.browserState();
  87. this.removeOnUrlChangeFn = this.location.onUrlChange((newUrl, newState) => {
  88. this.urlChanges.next({ newUrl, newState });
  89. });
  90. if (_isPromise($injector)) {
  91. $injector.then(($i) => this.initialize($i));
  92. }
  93. else {
  94. this.initialize($injector);
  95. }
  96. }
  97. initialize($injector) {
  98. const $rootScope = $injector.get('$rootScope');
  99. const $rootElement = $injector.get('$rootElement');
  100. $rootElement.on('click', (event) => {
  101. if (event.ctrlKey ||
  102. event.metaKey ||
  103. event.shiftKey ||
  104. event.which === 2 ||
  105. event.button === 2) {
  106. return;
  107. }
  108. let elm = event.target;
  109. // traverse the DOM up to find first A tag
  110. while (elm && elm.nodeName.toLowerCase() !== 'a') {
  111. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  112. if (elm === $rootElement[0] || !(elm = elm.parentNode)) {
  113. return;
  114. }
  115. }
  116. if (!isAnchor(elm)) {
  117. return;
  118. }
  119. const absHref = elm.href;
  120. const relHref = elm.getAttribute('href');
  121. // Ignore when url is started with javascript: or mailto:
  122. if (IGNORE_URI_REGEXP.test(absHref)) {
  123. return;
  124. }
  125. if (absHref && !elm.getAttribute('target') && !event.isDefaultPrevented()) {
  126. if (this.$$parseLinkUrl(absHref, relHref)) {
  127. // We do a preventDefault for all urls that are part of the AngularJS application,
  128. // in html5mode and also without, so that we are able to abort navigation without
  129. // getting double entries in the location history.
  130. event.preventDefault();
  131. // update location manually
  132. if (this.absUrl() !== this.browserUrl()) {
  133. $rootScope.$apply();
  134. }
  135. }
  136. }
  137. });
  138. this.urlChanges.subscribe(({ newUrl, newState }) => {
  139. const oldUrl = this.absUrl();
  140. const oldState = this.$$state;
  141. this.$$parse(newUrl);
  142. newUrl = this.absUrl();
  143. this.$$state = newState;
  144. const defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, newState, oldState).defaultPrevented;
  145. // if the location was changed by a `$locationChangeStart` handler then stop
  146. // processing this location change
  147. if (this.absUrl() !== newUrl)
  148. return;
  149. // If default was prevented, set back to old state. This is the state that was locally
  150. // cached in the $location service.
  151. if (defaultPrevented) {
  152. this.$$parse(oldUrl);
  153. this.state(oldState);
  154. this.setBrowserUrlWithFallback(oldUrl, false, oldState);
  155. this.$$notifyChangeListeners(this.url(), this.$$state, oldUrl, oldState);
  156. }
  157. else {
  158. this.initializing = false;
  159. $rootScope.$broadcast('$locationChangeSuccess', newUrl, oldUrl, newState, oldState);
  160. this.resetBrowserUpdate();
  161. }
  162. if (!$rootScope.$$phase) {
  163. $rootScope.$digest();
  164. }
  165. });
  166. // Synchronize the browser's URL and state with the application.
  167. // Note: There is no need to save the `$watch` return value (deregister listener)
  168. // into a variable because `$scope.$$watchers` is automatically cleaned up when
  169. // the root scope is destroyed.
  170. $rootScope.$watch(() => {
  171. if (this.initializing || this.updateBrowser) {
  172. this.updateBrowser = false;
  173. const oldUrl = this.browserUrl();
  174. const newUrl = this.absUrl();
  175. const oldState = this.browserState();
  176. let currentReplace = this.$$replace;
  177. const urlOrStateChanged = !this.urlCodec.areEqual(oldUrl, newUrl) || oldState !== this.$$state;
  178. // Fire location changes one time to on initialization. This must be done on the
  179. // next tick (thus inside $evalAsync()) in order for listeners to be registered
  180. // before the event fires. Mimicing behavior from $locationWatch:
  181. // https://github.com/angular/angular.js/blob/master/src/ng/location.js#L983
  182. if (this.initializing || urlOrStateChanged) {
  183. this.initializing = false;
  184. $rootScope.$evalAsync(() => {
  185. // Get the new URL again since it could have changed due to async update
  186. const newUrl = this.absUrl();
  187. const defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, this.$$state, oldState).defaultPrevented;
  188. // if the location was changed by a `$locationChangeStart` handler then stop
  189. // processing this location change
  190. if (this.absUrl() !== newUrl)
  191. return;
  192. if (defaultPrevented) {
  193. this.$$parse(oldUrl);
  194. this.$$state = oldState;
  195. }
  196. else {
  197. // This block doesn't run when initializing because it's going to perform the update
  198. // to the URL which shouldn't be needed when initializing.
  199. if (urlOrStateChanged) {
  200. this.setBrowserUrlWithFallback(newUrl, currentReplace, oldState === this.$$state ? null : this.$$state);
  201. this.$$replace = false;
  202. }
  203. $rootScope.$broadcast('$locationChangeSuccess', newUrl, oldUrl, this.$$state, oldState);
  204. if (urlOrStateChanged) {
  205. this.$$notifyChangeListeners(this.url(), this.$$state, oldUrl, oldState);
  206. }
  207. }
  208. });
  209. }
  210. }
  211. this.$$replace = false;
  212. });
  213. $rootScope.$on('$destroy', () => {
  214. this.removeOnUrlChangeFn();
  215. // Complete the subject to release all active observers when the root
  216. // scope is destroyed. Before this change, we subscribed to the `urlChanges`
  217. // subject, and the subscriber captured `this`, leading to a memory leak
  218. // after the root scope was destroyed.
  219. this.urlChanges.complete();
  220. });
  221. }
  222. resetBrowserUpdate() {
  223. this.$$replace = false;
  224. this.$$state = this.browserState();
  225. this.updateBrowser = false;
  226. this.lastBrowserUrl = this.browserUrl();
  227. }
  228. lastHistoryState;
  229. lastBrowserUrl = '';
  230. browserUrl(url, replace, state) {
  231. // In modern browsers `history.state` is `null` by default; treating it separately
  232. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  233. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  234. if (typeof state === 'undefined') {
  235. state = null;
  236. }
  237. // setter
  238. if (url) {
  239. let sameState = this.lastHistoryState === state;
  240. // Normalize the inputted URL
  241. url = this.urlCodec.parse(url).href;
  242. // Don't change anything if previous and current URLs and states match.
  243. if (this.lastBrowserUrl === url && sameState) {
  244. return this;
  245. }
  246. this.lastBrowserUrl = url;
  247. this.lastHistoryState = state;
  248. // Remove server base from URL as the Angular APIs for updating URL require
  249. // it to be the path+.
  250. url = this.stripBaseUrl(this.getServerBase(), url) || url;
  251. // Set the URL
  252. if (replace) {
  253. this.locationStrategy.replaceState(state, '', url, '');
  254. }
  255. else {
  256. this.locationStrategy.pushState(state, '', url, '');
  257. }
  258. this.cacheState();
  259. return this;
  260. // getter
  261. }
  262. else {
  263. return this.platformLocation.href;
  264. }
  265. }
  266. // This variable should be used *only* inside the cacheState function.
  267. lastCachedState = null;
  268. cacheState() {
  269. // This should be the only place in $browser where `history.state` is read.
  270. this.cachedState = this.platformLocation.getState();
  271. if (typeof this.cachedState === 'undefined') {
  272. this.cachedState = null;
  273. }
  274. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  275. if (deepEqual(this.cachedState, this.lastCachedState)) {
  276. this.cachedState = this.lastCachedState;
  277. }
  278. this.lastCachedState = this.cachedState;
  279. this.lastHistoryState = this.cachedState;
  280. }
  281. /**
  282. * This function emulates the $browser.state() function from AngularJS. It will cause
  283. * history.state to be cached unless changed with deep equality check.
  284. */
  285. browserState() {
  286. return this.cachedState;
  287. }
  288. stripBaseUrl(base, url) {
  289. if (url.startsWith(base)) {
  290. return url.slice(base.length);
  291. }
  292. return undefined;
  293. }
  294. getServerBase() {
  295. const { protocol, hostname, port } = this.platformLocation;
  296. const baseHref = this.locationStrategy.getBaseHref();
  297. let url = `${protocol}//${hostname}${port ? ':' + port : ''}${baseHref || '/'}`;
  298. return url.endsWith('/') ? url : url + '/';
  299. }
  300. parseAppUrl(url) {
  301. if (DOUBLE_SLASH_REGEX.test(url)) {
  302. throw new Error(`Bad Path - URL cannot start with double slashes: ${url}`);
  303. }
  304. let prefixed = url.charAt(0) !== '/';
  305. if (prefixed) {
  306. url = '/' + url;
  307. }
  308. let match = this.urlCodec.parse(url, this.getServerBase());
  309. if (typeof match === 'string') {
  310. throw new Error(`Bad URL - Cannot parse URL: ${url}`);
  311. }
  312. let path = prefixed && match.pathname.charAt(0) === '/' ? match.pathname.substring(1) : match.pathname;
  313. this.$$path = this.urlCodec.decodePath(path);
  314. this.$$search = this.urlCodec.decodeSearch(match.search);
  315. this.$$hash = this.urlCodec.decodeHash(match.hash);
  316. // make sure path starts with '/';
  317. if (this.$$path && this.$$path.charAt(0) !== '/') {
  318. this.$$path = '/' + this.$$path;
  319. }
  320. }
  321. /**
  322. * Registers listeners for URL changes. This API is used to catch updates performed by the
  323. * AngularJS framework. These changes are a subset of the `$locationChangeStart` and
  324. * `$locationChangeSuccess` events which fire when AngularJS updates its internally-referenced
  325. * version of the browser URL.
  326. *
  327. * It's possible for `$locationChange` events to happen, but for the browser URL
  328. * (window.location) to remain unchanged. This `onChange` callback will fire only when AngularJS
  329. * actually updates the browser URL (window.location).
  330. *
  331. * @param fn The callback function that is triggered for the listener when the URL changes.
  332. * @param err The callback function that is triggered when an error occurs.
  333. */
  334. onChange(fn, err = (e) => { }) {
  335. this.$$changeListeners.push([fn, err]);
  336. }
  337. /** @internal */
  338. $$notifyChangeListeners(url = '', state, oldUrl = '', oldState) {
  339. this.$$changeListeners.forEach(([fn, err]) => {
  340. try {
  341. fn(url, state, oldUrl, oldState);
  342. }
  343. catch (e) {
  344. err(e);
  345. }
  346. });
  347. }
  348. /**
  349. * Parses the provided URL, and sets the current URL to the parsed result.
  350. *
  351. * @param url The URL string.
  352. */
  353. $$parse(url) {
  354. let pathUrl;
  355. if (url.startsWith('/')) {
  356. pathUrl = url;
  357. }
  358. else {
  359. // Remove protocol & hostname if URL starts with it
  360. pathUrl = this.stripBaseUrl(this.getServerBase(), url);
  361. }
  362. if (typeof pathUrl === 'undefined') {
  363. throw new Error(`Invalid url "${url}", missing path prefix "${this.getServerBase()}".`);
  364. }
  365. this.parseAppUrl(pathUrl);
  366. this.$$path ||= '/';
  367. this.composeUrls();
  368. }
  369. /**
  370. * Parses the provided URL and its relative URL.
  371. *
  372. * @param url The full URL string.
  373. * @param relHref A URL string relative to the full URL string.
  374. */
  375. $$parseLinkUrl(url, relHref) {
  376. // When relHref is passed, it should be a hash and is handled separately
  377. if (relHref && relHref[0] === '#') {
  378. this.hash(relHref.slice(1));
  379. return true;
  380. }
  381. let rewrittenUrl;
  382. let appUrl = this.stripBaseUrl(this.getServerBase(), url);
  383. if (typeof appUrl !== 'undefined') {
  384. rewrittenUrl = this.getServerBase() + appUrl;
  385. }
  386. else if (this.getServerBase() === url + '/') {
  387. rewrittenUrl = this.getServerBase();
  388. }
  389. // Set the URL
  390. if (rewrittenUrl) {
  391. this.$$parse(rewrittenUrl);
  392. }
  393. return !!rewrittenUrl;
  394. }
  395. setBrowserUrlWithFallback(url, replace, state) {
  396. const oldUrl = this.url();
  397. const oldState = this.$$state;
  398. try {
  399. this.browserUrl(url, replace, state);
  400. // Make sure $location.state() returns referentially identical (not just deeply equal)
  401. // state object; this makes possible quick checking if the state changed in the digest
  402. // loop. Checking deep equality would be too expensive.
  403. this.$$state = this.browserState();
  404. }
  405. catch (e) {
  406. // Restore old values if pushState fails
  407. this.url(oldUrl);
  408. this.$$state = oldState;
  409. throw e;
  410. }
  411. }
  412. composeUrls() {
  413. this.$$url = this.urlCodec.normalize(this.$$path, this.$$search, this.$$hash);
  414. this.$$absUrl = this.getServerBase() + this.$$url.slice(1); // remove '/' from front of URL
  415. this.updateBrowser = true;
  416. }
  417. /**
  418. * Retrieves the full URL representation with all segments encoded according to
  419. * rules specified in
  420. * [RFC 3986](https://tools.ietf.org/html/rfc3986).
  421. *
  422. *
  423. * ```js
  424. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  425. * let absUrl = $location.absUrl();
  426. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  427. * ```
  428. */
  429. absUrl() {
  430. return this.$$absUrl;
  431. }
  432. url(url) {
  433. if (typeof url === 'string') {
  434. if (!url.length) {
  435. url = '/';
  436. }
  437. const match = PATH_MATCH.exec(url);
  438. if (!match)
  439. return this;
  440. if (match[1] || url === '')
  441. this.path(this.urlCodec.decodePath(match[1]));
  442. if (match[2] || match[1] || url === '')
  443. this.search(match[3] || '');
  444. this.hash(match[5] || '');
  445. // Chainable method
  446. return this;
  447. }
  448. return this.$$url;
  449. }
  450. /**
  451. * Retrieves the protocol of the current URL.
  452. *
  453. * ```js
  454. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  455. * let protocol = $location.protocol();
  456. * // => "http"
  457. * ```
  458. */
  459. protocol() {
  460. return this.$$protocol;
  461. }
  462. /**
  463. * Retrieves the protocol of the current URL.
  464. *
  465. * In contrast to the non-AngularJS version `location.host` which returns `hostname:port`, this
  466. * returns the `hostname` portion only.
  467. *
  468. *
  469. * ```js
  470. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  471. * let host = $location.host();
  472. * // => "example.com"
  473. *
  474. * // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  475. * host = $location.host();
  476. * // => "example.com"
  477. * host = location.host;
  478. * // => "example.com:8080"
  479. * ```
  480. */
  481. host() {
  482. return this.$$host;
  483. }
  484. /**
  485. * Retrieves the port of the current URL.
  486. *
  487. * ```js
  488. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  489. * let port = $location.port();
  490. * // => 80
  491. * ```
  492. */
  493. port() {
  494. return this.$$port;
  495. }
  496. path(path) {
  497. if (typeof path === 'undefined') {
  498. return this.$$path;
  499. }
  500. // null path converts to empty string. Prepend with "/" if needed.
  501. path = path !== null ? path.toString() : '';
  502. path = path.charAt(0) === '/' ? path : '/' + path;
  503. this.$$path = path;
  504. this.composeUrls();
  505. return this;
  506. }
  507. search(search, paramValue) {
  508. switch (arguments.length) {
  509. case 0:
  510. return this.$$search;
  511. case 1:
  512. if (typeof search === 'string' || typeof search === 'number') {
  513. this.$$search = this.urlCodec.decodeSearch(search.toString());
  514. }
  515. else if (typeof search === 'object' && search !== null) {
  516. // Copy the object so it's never mutated
  517. search = { ...search };
  518. // remove object undefined or null properties
  519. for (const key in search) {
  520. if (search[key] == null)
  521. delete search[key];
  522. }
  523. this.$$search = search;
  524. }
  525. else {
  526. throw new Error('LocationProvider.search(): First argument must be a string or an object.');
  527. }
  528. break;
  529. default:
  530. if (typeof search === 'string') {
  531. const currentSearch = this.search();
  532. if (typeof paramValue === 'undefined' || paramValue === null) {
  533. delete currentSearch[search];
  534. return this.search(currentSearch);
  535. }
  536. else {
  537. currentSearch[search] = paramValue;
  538. return this.search(currentSearch);
  539. }
  540. }
  541. }
  542. this.composeUrls();
  543. return this;
  544. }
  545. hash(hash) {
  546. if (typeof hash === 'undefined') {
  547. return this.$$hash;
  548. }
  549. this.$$hash = hash !== null ? hash.toString() : '';
  550. this.composeUrls();
  551. return this;
  552. }
  553. /**
  554. * Changes to `$location` during the current `$digest` will replace the current
  555. * history record, instead of adding a new one.
  556. */
  557. replace() {
  558. this.$$replace = true;
  559. return this;
  560. }
  561. state(state) {
  562. if (typeof state === 'undefined') {
  563. return this.$$state;
  564. }
  565. this.$$state = state;
  566. return this;
  567. }
  568. }
  569. /**
  570. * The factory function used to create an instance of the `$locationShim` in Angular,
  571. * and provides an API-compatible `$locationProvider` for AngularJS.
  572. *
  573. * @publicApi
  574. */
  575. class $locationShimProvider {
  576. ngUpgrade;
  577. location;
  578. platformLocation;
  579. urlCodec;
  580. locationStrategy;
  581. constructor(ngUpgrade, location, platformLocation, urlCodec, locationStrategy) {
  582. this.ngUpgrade = ngUpgrade;
  583. this.location = location;
  584. this.platformLocation = platformLocation;
  585. this.urlCodec = urlCodec;
  586. this.locationStrategy = locationStrategy;
  587. }
  588. /**
  589. * Factory method that returns an instance of the $locationShim
  590. */
  591. $get() {
  592. return new $locationShim(this.ngUpgrade.$injector, this.location, this.platformLocation, this.urlCodec, this.locationStrategy);
  593. }
  594. /**
  595. * Stub method used to keep API compatible with AngularJS. This setting is configured through
  596. * the LocationUpgradeModule's `config` method in your Angular app.
  597. */
  598. hashPrefix(prefix) {
  599. throw new Error('Configure LocationUpgrade through LocationUpgradeModule.config method.');
  600. }
  601. /**
  602. * Stub method used to keep API compatible with AngularJS. This setting is configured through
  603. * the LocationUpgradeModule's `config` method in your Angular app.
  604. */
  605. html5Mode(mode) {
  606. throw new Error('Configure LocationUpgrade through LocationUpgradeModule.config method.');
  607. }
  608. }
  609. /**
  610. * A codec for encoding and decoding URL parts.
  611. *
  612. * @publicApi
  613. **/
  614. class UrlCodec {
  615. }
  616. /**
  617. * A `UrlCodec` that uses logic from AngularJS to serialize and parse URLs
  618. * and URL parameters.
  619. *
  620. * @publicApi
  621. */
  622. class AngularJSUrlCodec {
  623. // https://github.com/angular/angular.js/blob/864c7f0/src/ng/location.js#L15
  624. encodePath(path) {
  625. const segments = path.split('/');
  626. let i = segments.length;
  627. while (i--) {
  628. // decode forward slashes to prevent them from being double encoded
  629. segments[i] = encodeUriSegment(segments[i].replace(/%2F/g, '/'));
  630. }
  631. path = segments.join('/');
  632. return _stripIndexHtml(((path && path[0] !== '/' && '/') || '') + path);
  633. }
  634. // https://github.com/angular/angular.js/blob/864c7f0/src/ng/location.js#L42
  635. encodeSearch(search) {
  636. if (typeof search === 'string') {
  637. search = parseKeyValue(search);
  638. }
  639. search = toKeyValue(search);
  640. return search ? '?' + search : '';
  641. }
  642. // https://github.com/angular/angular.js/blob/864c7f0/src/ng/location.js#L44
  643. encodeHash(hash) {
  644. hash = encodeUriSegment(hash);
  645. return hash ? '#' + hash : '';
  646. }
  647. // https://github.com/angular/angular.js/blob/864c7f0/src/ng/location.js#L27
  648. decodePath(path, html5Mode = true) {
  649. const segments = path.split('/');
  650. let i = segments.length;
  651. while (i--) {
  652. segments[i] = decodeURIComponent(segments[i]);
  653. if (html5Mode) {
  654. // encode forward slashes to prevent them from being mistaken for path separators
  655. segments[i] = segments[i].replace(/\//g, '%2F');
  656. }
  657. }
  658. return segments.join('/');
  659. }
  660. // https://github.com/angular/angular.js/blob/864c7f0/src/ng/location.js#L72
  661. decodeSearch(search) {
  662. return parseKeyValue(search);
  663. }
  664. // https://github.com/angular/angular.js/blob/864c7f0/src/ng/location.js#L73
  665. decodeHash(hash) {
  666. hash = decodeURIComponent(hash);
  667. return hash[0] === '#' ? hash.substring(1) : hash;
  668. }
  669. normalize(pathOrHref, search, hash, baseUrl) {
  670. if (arguments.length === 1) {
  671. const parsed = this.parse(pathOrHref, baseUrl);
  672. if (typeof parsed === 'string') {
  673. return parsed;
  674. }
  675. const serverUrl = `${parsed.protocol}://${parsed.hostname}${parsed.port ? ':' + parsed.port : ''}`;
  676. return this.normalize(this.decodePath(parsed.pathname), this.decodeSearch(parsed.search), this.decodeHash(parsed.hash), serverUrl);
  677. }
  678. else {
  679. const encPath = this.encodePath(pathOrHref);
  680. const encSearch = (search && this.encodeSearch(search)) || '';
  681. const encHash = (hash && this.encodeHash(hash)) || '';
  682. let joinedPath = (baseUrl || '') + encPath;
  683. if (!joinedPath.length || joinedPath[0] !== '/') {
  684. joinedPath = '/' + joinedPath;
  685. }
  686. return joinedPath + encSearch + encHash;
  687. }
  688. }
  689. areEqual(valA, valB) {
  690. return this.normalize(valA) === this.normalize(valB);
  691. }
  692. // https://github.com/angular/angular.js/blob/864c7f0/src/ng/urlUtils.js#L60
  693. parse(url, base) {
  694. try {
  695. // Safari 12 throws an error when the URL constructor is called with an undefined base.
  696. const parsed = !base ? new URL(url) : new URL(url, base);
  697. return {
  698. href: parsed.href,
  699. protocol: parsed.protocol ? parsed.protocol.replace(/:$/, '') : '',
  700. host: parsed.host,
  701. search: parsed.search ? parsed.search.replace(/^\?/, '') : '',
  702. hash: parsed.hash ? parsed.hash.replace(/^#/, '') : '',
  703. hostname: parsed.hostname,
  704. port: parsed.port,
  705. pathname: parsed.pathname.charAt(0) === '/' ? parsed.pathname : '/' + parsed.pathname,
  706. };
  707. }
  708. catch (e) {
  709. throw new Error(`Invalid URL (${url}) with base (${base})`);
  710. }
  711. }
  712. }
  713. function _stripIndexHtml(url) {
  714. return url.replace(/\/index.html$/, '');
  715. }
  716. /**
  717. * Tries to decode the URI component without throwing an exception.
  718. *
  719. * @param str value potential URI component to check.
  720. * @returns the decoded URI if it can be decoded or else `undefined`.
  721. */
  722. function tryDecodeURIComponent(value) {
  723. try {
  724. return decodeURIComponent(value);
  725. }
  726. catch (e) {
  727. // Ignore any invalid uri component.
  728. return undefined;
  729. }
  730. }
  731. /**
  732. * Parses an escaped url query string into key-value pairs. Logic taken from
  733. * https://github.com/angular/angular.js/blob/864c7f0/src/Angular.js#L1382
  734. */
  735. function parseKeyValue(keyValue) {
  736. const obj = {};
  737. (keyValue || '').split('&').forEach((keyValue) => {
  738. let splitPoint, key, val;
  739. if (keyValue) {
  740. key = keyValue = keyValue.replace(/\+/g, '%20');
  741. splitPoint = keyValue.indexOf('=');
  742. if (splitPoint !== -1) {
  743. key = keyValue.substring(0, splitPoint);
  744. val = keyValue.substring(splitPoint + 1);
  745. }
  746. key = tryDecodeURIComponent(key);
  747. if (typeof key !== 'undefined') {
  748. val = typeof val !== 'undefined' ? tryDecodeURIComponent(val) : true;
  749. if (!obj.hasOwnProperty(key)) {
  750. obj[key] = val;
  751. }
  752. else if (Array.isArray(obj[key])) {
  753. obj[key].push(val);
  754. }
  755. else {
  756. obj[key] = [obj[key], val];
  757. }
  758. }
  759. }
  760. });
  761. return obj;
  762. }
  763. /**
  764. * Serializes into key-value pairs. Logic taken from
  765. * https://github.com/angular/angular.js/blob/864c7f0/src/Angular.js#L1409
  766. */
  767. function toKeyValue(obj) {
  768. const parts = [];
  769. for (const key in obj) {
  770. let value = obj[key];
  771. if (Array.isArray(value)) {
  772. value.forEach((arrayValue) => {
  773. parts.push(encodeUriQuery(key, true) +
  774. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  775. });
  776. }
  777. else {
  778. parts.push(encodeUriQuery(key, true) +
  779. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  780. }
  781. }
  782. return parts.length ? parts.join('&') : '';
  783. }
  784. /**
  785. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  786. * https://tools.ietf.org/html/rfc3986 with regards to the character set (pchar) allowed in path
  787. * segments:
  788. * segment = *pchar
  789. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  790. * pct-encoded = "%" HEXDIG HEXDIG
  791. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  792. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  793. * / "*" / "+" / "," / ";" / "="
  794. *
  795. * Logic from https://github.com/angular/angular.js/blob/864c7f0/src/Angular.js#L1437
  796. */
  797. function encodeUriSegment(val) {
  798. return encodeUriQuery(val, true).replace(/%26/g, '&').replace(/%3D/gi, '=').replace(/%2B/gi, '+');
  799. }
  800. /**
  801. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  802. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  803. * encoded per https://tools.ietf.org/html/rfc3986:
  804. * query = *( pchar / "/" / "?" )
  805. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  806. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  807. * pct-encoded = "%" HEXDIG HEXDIG
  808. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  809. * / "*" / "+" / "," / ";" / "="
  810. *
  811. * Logic from https://github.com/angular/angular.js/blob/864c7f0/src/Angular.js#L1456
  812. */
  813. function encodeUriQuery(val, pctEncodeSpaces = false) {
  814. return encodeURIComponent(val)
  815. .replace(/%40/g, '@')
  816. .replace(/%3A/gi, ':')
  817. .replace(/%24/g, '$')
  818. .replace(/%2C/gi, ',')
  819. .replace(/%3B/gi, ';')
  820. .replace(/%20/g, pctEncodeSpaces ? '%20' : '+');
  821. }
  822. /**
  823. * A provider token used to configure the location upgrade module.
  824. *
  825. * @publicApi
  826. */
  827. const LOCATION_UPGRADE_CONFIGURATION = new InjectionToken(ngDevMode ? 'LOCATION_UPGRADE_CONFIGURATION' : '');
  828. const APP_BASE_HREF_RESOLVED = new InjectionToken(ngDevMode ? 'APP_BASE_HREF_RESOLVED' : '');
  829. /**
  830. * `NgModule` used for providing and configuring Angular's Unified Location Service for upgrading.
  831. *
  832. * @see [Using the Unified Angular Location Service](https://angular.io/guide/upgrade#using-the-unified-angular-location-service)
  833. *
  834. * @publicApi
  835. */
  836. class LocationUpgradeModule {
  837. static config(config) {
  838. return {
  839. ngModule: LocationUpgradeModule,
  840. providers: [
  841. Location,
  842. {
  843. provide: $locationShim,
  844. useFactory: provide$location,
  845. deps: [UpgradeModule, Location, PlatformLocation, UrlCodec, LocationStrategy],
  846. },
  847. { provide: LOCATION_UPGRADE_CONFIGURATION, useValue: config ? config : {} },
  848. { provide: UrlCodec, useFactory: provideUrlCodec, deps: [LOCATION_UPGRADE_CONFIGURATION] },
  849. {
  850. provide: APP_BASE_HREF_RESOLVED,
  851. useFactory: provideAppBaseHref,
  852. deps: [LOCATION_UPGRADE_CONFIGURATION, [new Inject(APP_BASE_HREF), new Optional()]],
  853. },
  854. {
  855. provide: LocationStrategy,
  856. useFactory: provideLocationStrategy,
  857. deps: [PlatformLocation, APP_BASE_HREF_RESOLVED, LOCATION_UPGRADE_CONFIGURATION],
  858. },
  859. ],
  860. };
  861. }
  862. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.0", ngImport: i0, type: LocationUpgradeModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
  863. static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "20.1.0", ngImport: i0, type: LocationUpgradeModule, imports: [CommonModule] });
  864. static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "20.1.0", ngImport: i0, type: LocationUpgradeModule, imports: [CommonModule] });
  865. }
  866. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.0", ngImport: i0, type: LocationUpgradeModule, decorators: [{
  867. type: NgModule,
  868. args: [{ imports: [CommonModule] }]
  869. }] });
  870. function provideAppBaseHref(config, appBaseHref) {
  871. if (config && config.appBaseHref != null) {
  872. return config.appBaseHref;
  873. }
  874. else if (appBaseHref != null) {
  875. return appBaseHref;
  876. }
  877. return '';
  878. }
  879. function provideUrlCodec(config) {
  880. const codec = (config && config.urlCodec) || AngularJSUrlCodec;
  881. return new codec();
  882. }
  883. function provideLocationStrategy(platformLocation, baseHref, options = {}) {
  884. return options.useHash
  885. ? new HashLocationStrategy(platformLocation, baseHref)
  886. : new PathLocationStrategy(platformLocation, baseHref);
  887. }
  888. function provide$location(ngUpgrade, location, platformLocation, urlCodec, locationStrategy) {
  889. const $locationProvider = new $locationShimProvider(ngUpgrade, location, platformLocation, urlCodec, locationStrategy);
  890. return $locationProvider.$get();
  891. }
  892. export { $locationShim, $locationShimProvider, AngularJSUrlCodec, LOCATION_UPGRADE_CONFIGURATION, LocationUpgradeModule, UrlCodec };
  893. //# sourceMappingURL=upgrade.mjs.map