upgrade.mjs 34 KB

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