swup 3.0.0-rc.3 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/Swup.cjs +1 -1
  2. package/dist/Swup.cjs.map +1 -1
  3. package/dist/Swup.modern.js +1 -1
  4. package/dist/Swup.modern.js.map +1 -1
  5. package/dist/Swup.module.js +1 -1
  6. package/dist/Swup.module.js.map +1 -1
  7. package/dist/Swup.umd.js +1 -1
  8. package/dist/Swup.umd.js.map +1 -1
  9. package/dist/types/Swup.d.ts +14 -14
  10. package/dist/types/__test__/index.test.d.ts +1 -0
  11. package/dist/types/helpers/Location.d.ts +0 -10
  12. package/dist/types/helpers/fetch.d.ts +2 -2
  13. package/dist/types/helpers.d.ts +10 -11
  14. package/dist/types/index.d.ts +5 -4
  15. package/dist/types/modules/Cache.d.ts +2 -2
  16. package/dist/types/modules/enterPage.d.ts +1 -1
  17. package/dist/types/modules/fetchPage.d.ts +3 -3
  18. package/dist/types/modules/getAnimationPromises.d.ts +1 -1
  19. package/dist/types/modules/getPageData.d.ts +2 -2
  20. package/dist/types/modules/leavePage.d.ts +2 -2
  21. package/dist/types/modules/loadPage.d.ts +1 -1
  22. package/dist/types/modules/off.d.ts +2 -2
  23. package/dist/types/modules/on.d.ts +1 -1
  24. package/dist/types/modules/plugins.d.ts +5 -3
  25. package/dist/types/modules/renderPage.d.ts +2 -2
  26. package/dist/types/modules/triggerEvent.d.ts +2 -2
  27. package/dist/types/modules/updateTransition.d.ts +1 -1
  28. package/dist/types/utils.d.ts +1 -1
  29. package/package.json +16 -8
  30. package/readme.md +2 -2
  31. package/src/Swup.ts +21 -21
  32. package/src/__test__/index.test.ts +36 -0
  33. package/src/helpers/Location.ts +0 -10
  34. package/src/helpers/classify.ts +1 -1
  35. package/src/helpers/createHistoryRecord.ts +1 -1
  36. package/src/helpers/fetch.ts +2 -2
  37. package/src/helpers/getDataFromHtml.ts +1 -1
  38. package/src/helpers/markSwupElements.ts +1 -1
  39. package/src/helpers/updateHistoryRecord.ts +1 -1
  40. package/src/helpers.ts +10 -11
  41. package/src/index.ts +5 -4
  42. package/src/modules/Cache.ts +3 -3
  43. package/src/modules/enterPage.ts +2 -2
  44. package/src/modules/fetchPage.ts +4 -4
  45. package/src/modules/getAnchorElement.ts +1 -1
  46. package/src/modules/getAnimationPromises.ts +2 -2
  47. package/src/modules/getPageData.ts +3 -3
  48. package/src/modules/leavePage.ts +2 -2
  49. package/src/modules/loadPage.ts +3 -3
  50. package/src/modules/off.ts +2 -2
  51. package/src/modules/on.ts +1 -1
  52. package/src/modules/plugins.ts +13 -5
  53. package/src/modules/renderPage.ts +3 -3
  54. package/src/modules/triggerEvent.ts +2 -2
  55. package/src/modules/updateTransition.ts +1 -1
  56. package/src/utils.ts +1 -1
  57. package/dist/helpers.cjs +0 -2
  58. package/dist/helpers.cjs.map +0 -1
  59. package/dist/helpers.modern.js +0 -2
  60. package/dist/helpers.modern.js.map +0 -1
  61. package/dist/helpers.module.js +0 -2
  62. package/dist/helpers.module.js.map +0 -1
  63. package/dist/types/helpers/index.d.ts +0 -11
  64. package/dist/types/helpers/versionSatisfies.d.ts +0 -11
  65. package/dist/utils.cjs +0 -2
  66. package/dist/utils.cjs.map +0 -1
  67. package/dist/utils.modern.js +0 -2
  68. package/dist/utils.modern.js.map +0 -1
  69. package/dist/utils.module.js +0 -2
  70. package/dist/utils.module.js.map +0 -1
  71. package/src/helpers/versionSatisfies.ts +0 -44
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "swup",
3
3
  "amdName": "Swup",
4
- "version": "3.0.0-rc.3",
4
+ "version": "3.0.0",
5
5
  "description": "Complete, flexible, extensible, and easy-to-use page transition library for your server-side rendered website.",
6
6
  "type": "module",
7
7
  "source": "src/Swup.ts",
@@ -25,12 +25,15 @@
25
25
  "lint:prettier": "prettier 'src/**/*.ts'",
26
26
  "prepublish": "npm run build",
27
27
  "postinstall": "opencollective-postinstall || true",
28
- "ci": "start-server-and-test test:start 8274 cy:run:record",
29
- "test": "start-server-and-test test:start 8274 cy:run",
30
- "test:dev": "start-server-and-test test:start 8274 cy:open",
31
- "test:instrument": "nyc instrument --compact=false dist test/site/swup",
32
- "test:server": "http-server --port 8274 test/site",
33
- "test:start": "npm run test:instrument && npm run test:server",
28
+ "test": "npm run test:unit && npm run test:e2e",
29
+ "test:ci": "npm run test:unit && npm run test:e2e:ci",
30
+ "test:unit": "jest",
31
+ "test:e2e": "start-server-and-test test:e2e:start 8274 cy:run",
32
+ "test:e2e:ci": "start-server-and-test test:e2e:start 8274 cy:run:record",
33
+ "test:e2e:dev": "start-server-and-test test:e2e:start 8274 cy:open",
34
+ "test:e2e:instrument": "nyc instrument --compact=false dist cypress/fixtures/dist",
35
+ "test:e2e:server": "http-server --silent --port 8274 cypress/fixtures",
36
+ "test:e2e:start": "npm run test:e2e:instrument && npm run test:e2e:server",
34
37
  "cy:run": "cypress run",
35
38
  "cy:run:record": "cypress run --record",
36
39
  "cy:open": "cypress open",
@@ -53,16 +56,21 @@
53
56
  "opencollective-postinstall": "^2.0.2"
54
57
  },
55
58
  "devDependencies": {
59
+ "@babel/preset-typescript": "^7.18.6",
56
60
  "@cypress/code-coverage": "^3.10.0",
57
61
  "@swup/prettier-config": "^1.0.0",
62
+ "@types/jest": "^29.2.5",
58
63
  "cypress": "^12.3.0",
59
64
  "http-server": "^14.1.1",
65
+ "husky": "^8.0.0",
60
66
  "istanbul-lib-coverage": "^3.2.0",
67
+ "jest": "^29.3.1",
68
+ "jest-environment-jsdom": "^29.3.1",
61
69
  "microbundle": "^0.15.0",
62
70
  "nyc": "^15.1.0",
63
71
  "prettier": "^2.8.2",
64
72
  "start-server-and-test": "^1.14.0",
65
- "husky": "^8.0.0"
73
+ "ts-jest": "^29.0.5"
66
74
  },
67
75
  "collective": {
68
76
  "type": "opencollective",
package/readme.md CHANGED
@@ -6,10 +6,10 @@
6
6
 
7
7
  <p align="center">
8
8
  <a href="https://www.npmjs.com/package/swup"><img src="https://img.shields.io/npm/v/swup.svg" alt="npm version"></a>
9
- <a href="https://bundlephobia.com/package/swup"><img src="https://img.shields.io/bundlephobia/minzip/swup.svg" alt="Bundle size"></a>
9
+ <a href="https://bundlephobia.com/package/swup"><img src="https://img.shields.io/bundlephobia/minzip/swup?label=size" alt="Bundle size"></a>
10
10
  <a href="https://github.com/gmrchk/swup/blob/master/LICENSE"><img src="https://img.shields.io/github/license/gmrchk/swup.svg" alt="License"></a>
11
11
  <a href="https://www.npmjs.com/package/swup"><img src="https://img.shields.io/npm/dt/swup.svg" alt="npm downloads"></a>
12
- <a href="https://circleci.com/gh/swup/swup"><img src="https://circleci.com/gh/swup/swup.svg?style=shield" alt="Build status"></a>
12
+ <a href="https://github.com/swup/swup/actions/workflows/e2e-tests.yml"><img src="https://img.shields.io/github/actions/workflow/status/swup/swup/e2e-tests.yml?branch=master&label=tests" alt="Test status"></a>
13
13
  </p>
14
14
 
15
15
  <br>
package/src/Swup.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import delegate from 'delegate-it';
2
2
 
3
- import version from './config/version.js';
3
+ import version from './config/version';
4
4
 
5
5
  import {
6
6
  cleanupAnimationClasses,
@@ -9,26 +9,26 @@ import {
9
9
  Location,
10
10
  markSwupElements,
11
11
  updateHistoryRecord
12
- } from './helpers.js';
13
- import { Unsubscribe } from './helpers/delegateEvent.js';
14
-
15
- import { Cache } from './modules/Cache.js';
16
- import { enterPage } from './modules/enterPage.js';
17
- import { getAnchorElement } from './modules/getAnchorElement.js';
18
- import { getAnimationPromises } from './modules/getAnimationPromises.js';
19
- import { getPageData } from './modules/getPageData.js';
20
- import { fetchPage } from './modules/fetchPage.js';
21
- import { leavePage } from './modules/leavePage.js';
22
- import { loadPage } from './modules/loadPage.js';
23
- import { replaceContent } from './modules/replaceContent.js';
24
- import { off } from './modules/off.js';
25
- import { on, Handlers } from './modules/on.js';
26
- import { use, unuse, findPlugin, Plugin } from './modules/plugins.js';
27
- import { renderPage } from './modules/renderPage.js';
28
- import { triggerEvent } from './modules/triggerEvent.js';
29
- import { updateTransition } from './modules/updateTransition.js';
30
-
31
- import { queryAll } from './utils.js';
12
+ } from './helpers';
13
+ import { Unsubscribe } from './helpers/delegateEvent';
14
+
15
+ import { Cache } from './modules/Cache';
16
+ import { enterPage } from './modules/enterPage';
17
+ import { getAnchorElement } from './modules/getAnchorElement';
18
+ import { getAnimationPromises } from './modules/getAnimationPromises';
19
+ import { getPageData } from './modules/getPageData';
20
+ import { fetchPage } from './modules/fetchPage';
21
+ import { leavePage } from './modules/leavePage';
22
+ import { loadPage } from './modules/loadPage';
23
+ import { replaceContent } from './modules/replaceContent';
24
+ import { off } from './modules/off';
25
+ import { on, Handlers } from './modules/on';
26
+ import { use, unuse, findPlugin, Plugin } from './modules/plugins';
27
+ import { renderPage } from './modules/renderPage';
28
+ import { triggerEvent } from './modules/triggerEvent';
29
+ import { updateTransition } from './modules/updateTransition';
30
+
31
+ import { queryAll } from './utils';
32
32
 
33
33
  export type Transition = {
34
34
  from?: string;
@@ -0,0 +1,36 @@
1
+ import Swup, { Options, Plugin } from '../index';
2
+
3
+ console.log = jest.fn();
4
+ console.warn = jest.fn();
5
+ console.error = jest.fn();
6
+
7
+ describe('exports', () => {
8
+ it('exports Swup, and Options/Plugin types', () => {
9
+ class SwupPlugin implements Plugin {
10
+ name = 'SwupPlugin';
11
+ isSwupPlugin = true as const;
12
+ mount = () => {};
13
+ unmount = () => {};
14
+ }
15
+
16
+ const options: Partial<Options> = {
17
+ animateHistoryBrowsing: false,
18
+ animationSelector: '[class*="transition-"]',
19
+ cache: true,
20
+ containers: ['#swup'],
21
+ ignoreVisit: (href, { el } = {}) => !!el?.closest('[data-no-swup]'),
22
+ linkSelector: 'a[href]',
23
+ plugins: [new SwupPlugin()],
24
+ resolveUrl: (url) => url,
25
+ requestHeaders: {
26
+ 'X-Requested-With': 'swup',
27
+ Accept: 'text/html, application/xhtml+xml'
28
+ },
29
+ skipPopStateHandling: (event) => event.state?.source !== 'swup'
30
+ };
31
+
32
+ const swup = new Swup(options);
33
+
34
+ expect(swup.version).not.toBeUndefined();
35
+ });
36
+ });
@@ -2,16 +2,6 @@
2
2
  * A helper for creating a Location from either an element
3
3
  * or a URL object/string
4
4
  *
5
- * Note: this could be implemented as a class inheriting from URL
6
- * Except: Babel will add tons of boilerplate for ES6 classes + getters
7
- * So for now it's implemented as an augmented URL object with custom getter
8
- *
9
- * class Location extends URL {
10
- * get url() {
11
- * return this.pathname + this.search;
12
- * }
13
- * }
14
- *
15
5
  */
16
6
 
17
7
  export class Location extends URL {
@@ -6,6 +6,6 @@ export const classify = (text: string, fallback?: string): string => {
6
6
  .replace(/[\s/_.]+/g, '-') // replace spaces and _./ with '-'
7
7
  .replace(/[^\w-]+/g, '') // remove all non-word chars
8
8
  .replace(/--+/g, '-') // replace repeating '-' with single '-'
9
- .replace(/^-+|-+$/, ''); // trim '-' from edges
9
+ .replace(/^-+|-+$/g, ''); // trim '-' from edges
10
10
  return output || fallback || '';
11
11
  };
@@ -1,4 +1,4 @@
1
- import { getCurrentUrl } from './getCurrentUrl.js';
1
+ import { getCurrentUrl } from './getCurrentUrl';
2
2
 
3
3
  export const createHistoryRecord = (
4
4
  url: string,
@@ -1,5 +1,5 @@
1
- import { TransitionOptions } from '../modules/loadPage.js';
2
- import { Options } from '../Swup.js';
1
+ import { TransitionOptions } from '../modules/loadPage';
2
+ import { Options } from '../Swup';
3
3
 
4
4
  export const fetch = (
5
5
  options: TransitionOptions & { headers: Options['requestHeaders'] },
@@ -1,4 +1,4 @@
1
- import { query, queryAll } from '../utils.js';
1
+ import { query, queryAll } from '../utils';
2
2
 
3
3
  export type PageHtmlData = {
4
4
  title: string;
@@ -1,4 +1,4 @@
1
- import { query, queryAll } from '../utils.js';
1
+ import { query, queryAll } from '../utils';
2
2
 
3
3
  export const markSwupElements = (element: Element, containers: string[]): void => {
4
4
  let blocks = 0;
@@ -1,4 +1,4 @@
1
- import { getCurrentUrl } from './getCurrentUrl.js';
1
+ import { getCurrentUrl } from './getCurrentUrl';
2
2
 
3
3
  export const updateHistoryRecord = (
4
4
  url: string | null = null,
package/src/helpers.ts CHANGED
@@ -1,14 +1,13 @@
1
1
  // Re-export all helpers to allow custom package export path
2
2
  // e.g. import { getPageData } from 'swup/helpers'
3
3
 
4
- export { classify } from './helpers/classify.js';
5
- export { createHistoryRecord } from './helpers/createHistoryRecord.js';
6
- export { updateHistoryRecord } from './helpers/updateHistoryRecord.js';
7
- export { delegateEvent } from './helpers/delegateEvent.js';
8
- export { getDataFromHtml } from './helpers/getDataFromHtml.js';
9
- export { fetch } from './helpers/fetch.js';
10
- export { getCurrentUrl } from './helpers/getCurrentUrl.js';
11
- export { Location } from './helpers/Location.js';
12
- export { markSwupElements } from './helpers/markSwupElements.js';
13
- export { cleanupAnimationClasses } from './helpers/cleanupAnimationClasses.js';
14
- export { versionSatisfies } from './helpers/versionSatisfies.js';
4
+ export { classify } from './helpers/classify';
5
+ export { createHistoryRecord } from './helpers/createHistoryRecord';
6
+ export { updateHistoryRecord } from './helpers/updateHistoryRecord';
7
+ export { delegateEvent } from './helpers/delegateEvent';
8
+ export { getDataFromHtml } from './helpers/getDataFromHtml';
9
+ export { fetch } from './helpers/fetch';
10
+ export { getCurrentUrl } from './helpers/getCurrentUrl';
11
+ export { Location } from './helpers/Location';
12
+ export { markSwupElements } from './helpers/markSwupElements';
13
+ export { cleanupAnimationClasses } from './helpers/cleanupAnimationClasses';
package/src/index.ts CHANGED
@@ -1,8 +1,9 @@
1
- import Swup, { Options } from './Swup.js';
1
+ import Swup, { Options } from './Swup';
2
+ import { Plugin } from './modules/plugins';
2
3
 
3
4
  export default Swup;
4
5
 
5
- export * from './helpers.js';
6
- export * from './utils.js';
6
+ export * from './helpers';
7
+ export * from './utils';
7
8
 
8
- export type { Options };
9
+ export type { Options, Plugin };
@@ -1,6 +1,6 @@
1
- import { getCurrentUrl, Location } from '../helpers.js';
2
- import Swup from '../Swup.js';
3
- import { PageData } from './getPageData.js';
1
+ import { getCurrentUrl, Location } from '../helpers';
2
+ import Swup from '../Swup';
3
+ import { PageData } from './getPageData';
4
4
 
5
5
  export interface PageRecord extends PageData {
6
6
  url: string;
@@ -1,5 +1,5 @@
1
- import { nextTick } from '../utils.js';
2
- import Swup from '../Swup.js';
1
+ import { nextTick } from '../utils';
2
+ import Swup from '../Swup';
3
3
 
4
4
  export const enterPage = function (
5
5
  this: Swup,
@@ -1,7 +1,7 @@
1
- import Swup from '../Swup.js';
2
- import { fetch } from '../helpers.js';
3
- import { TransitionOptions } from './loadPage.js';
4
- import { PageRecord } from './Cache.js';
1
+ import Swup from '../Swup';
2
+ import { fetch } from '../helpers';
3
+ import { TransitionOptions } from './loadPage';
4
+ import { PageRecord } from './Cache';
5
5
 
6
6
  export function fetchPage(this: Swup, data: TransitionOptions): Promise<PageRecord> {
7
7
  const headers = this.options.requestHeaders;
@@ -1,4 +1,4 @@
1
- import { escapeCssIdentifier, query } from '../utils.js';
1
+ import { escapeCssIdentifier, query } from '../utils';
2
2
 
3
3
  export const getAnchorElement = (hash: string): Element | null => {
4
4
  if (!hash) {
@@ -1,5 +1,5 @@
1
- import { queryAll, toMs } from '../utils.js';
2
- import Swup from '../Swup.js';
1
+ import { queryAll, toMs } from '../utils';
2
+ import Swup from '../Swup';
3
3
 
4
4
  // Transition property/event sniffing
5
5
  let transitionProp = 'transition';
@@ -1,6 +1,6 @@
1
- import { getDataFromHtml } from '../helpers.js';
2
- import Swup from '../Swup.js';
3
- import { PageHtmlData } from '../helpers/getDataFromHtml.js';
1
+ import { getDataFromHtml } from '../helpers';
2
+ import Swup from '../Swup';
3
+ import { PageHtmlData } from '../helpers/getDataFromHtml';
4
4
 
5
5
  export type PageData = PageHtmlData & {
6
6
  responseURL: string;
@@ -1,5 +1,5 @@
1
- import Swup from '../Swup.js';
2
- import { TransitionOptions } from './loadPage.js';
1
+ import Swup from '../Swup';
2
+ import { TransitionOptions } from './loadPage';
3
3
 
4
4
  export const leavePage = function (
5
5
  this: Swup,
@@ -1,6 +1,6 @@
1
- import { classify, createHistoryRecord, getCurrentUrl } from '../helpers.js';
2
- import Swup from '../Swup.js';
3
- import { PageRecord } from './Cache.js';
1
+ import { classify, createHistoryRecord, getCurrentUrl } from '../helpers';
2
+ import Swup from '../Swup';
3
+ import { PageRecord } from './Cache';
4
4
 
5
5
  export type TransitionOptions = {
6
6
  url: string;
@@ -1,5 +1,5 @@
1
- import Swup from '../Swup.js';
2
- import { EventType, Handler } from './on.js';
1
+ import Swup from '../Swup';
2
+ import { EventType, Handler } from './on';
3
3
 
4
4
  export const off = function off(this: Swup, event?: EventType, handler?: Handler) {
5
5
  if (event && handler) {
package/src/modules/on.ts CHANGED
@@ -1,4 +1,4 @@
1
- import Swup from '../Swup.js';
1
+ import Swup from '../Swup';
2
2
 
3
3
  export type EventType =
4
4
  | 'animationInDone'
@@ -1,21 +1,29 @@
1
- import Swup from '../Swup.js';
1
+ import Swup from '../Swup';
2
2
 
3
- // this should probably just be imported from @swup/plugin, but it doesn't have type defs now
4
3
  export type Plugin = {
5
4
  name: string;
5
+ isSwupPlugin: true;
6
6
  mount: () => void;
7
7
  unmount: () => void;
8
- isSwupPlugin: true;
8
+
9
+ // the instance is assigned later on after passing to swup
9
10
  swup?: Swup;
10
11
 
11
12
  // these are possibly undefined for backward compatibility
13
+ version?: string;
14
+ requires?: Record<string, string>;
12
15
  _beforeMount?: () => void;
13
16
  _afterUnmount?: () => void;
14
17
  _checkRequirements?: () => boolean;
15
18
  };
16
19
 
17
- export const use = function (this: Swup, plugin: Plugin) {
18
- if (!plugin.isSwupPlugin) {
20
+ const isSwupPlugin = (maybeInvalidPlugin: unknown): maybeInvalidPlugin is Plugin => {
21
+ // @ts-ignore
22
+ return maybeInvalidPlugin?.isSwupPlugin;
23
+ };
24
+
25
+ export const use = function (this: Swup, plugin: unknown) {
26
+ if (!isSwupPlugin(plugin)) {
19
27
  console.error('Not a swup plugin instance', plugin);
20
28
  return;
21
29
  }
@@ -1,6 +1,6 @@
1
- import { Location, updateHistoryRecord, getCurrentUrl } from '../helpers.js';
2
- import Swup from '../Swup.js';
3
- import { PageRecord } from './Cache.js';
1
+ import { Location, updateHistoryRecord, getCurrentUrl } from '../helpers';
2
+ import Swup from '../Swup';
3
+ import { PageRecord } from './Cache';
4
4
 
5
5
  export const renderPage = function (
6
6
  this: Swup,
@@ -1,5 +1,5 @@
1
- import { EventType } from './on.js';
2
- import Swup from '../Swup.js';
1
+ import { EventType } from './on';
2
+ import Swup from '../Swup';
3
3
 
4
4
  export const triggerEvent = function (
5
5
  this: Swup,
@@ -1,4 +1,4 @@
1
- import Swup from '../Swup.js';
1
+ import Swup from '../Swup';
2
2
 
3
3
  export const updateTransition = function (
4
4
  this: Swup,
package/src/utils.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  // Re-export all utils to allow custom package export path
2
2
  // e.g. import { queryAll } from 'swup/utils'
3
3
 
4
- export * from './utils/index.js';
4
+ export * from './utils/index';
package/dist/helpers.cjs DELETED
@@ -1,2 +0,0 @@
1
- function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var t=/*#__PURE__*/e(require("delegate-it"));const n=function(e){let{hash:t}=void 0===e?{}:e;return location.pathname+location.search+(t?location.hash:"")},o=function(e,t){return void 0===t&&(t=document),t.querySelector(e)},r=function(e,t){return void 0===t&&(t=document),Array.from(t.querySelectorAll(e))};class a extends URL{constructor(e,t){void 0===t&&(t=document.baseURI),super(e.toString(),t)}get url(){return this.pathname+this.search}static fromElement(e){const t=e.getAttribute("href")||e.getAttribute("xlink:href");return new a(t)}static fromUrl(e){return new a(e)}}const s=e=>/^to-/.test(e)||["is-changing","is-rendering","is-popstate"].includes(e),c=e=>String(e).split(".").concat(["0","0"]).slice(0,3).join(".");exports.Location=a,exports.classify=(e,t)=>String(e).toLowerCase().replace(/[\s/_.]+/g,"-").replace(/[^\w-]+/g,"").replace(/--+/g,"-").replace(/^-+|-+$/,"")||t||"",exports.cleanupAnimationClasses=()=>{const e=document.documentElement.className.split(" ").filter(s);document.documentElement.classList.remove(...e)},exports.createHistoryRecord=function(e,t){void 0===t&&(t={});const o={url:e=e||n({hash:!0}),random:Math.random(),source:"swup",...t};history.pushState(o,"",e)},exports.delegateEvent=function(e,n,o,r){let{base:a=document,...s}=void 0===r?{}:r;const c=t.default(a,e,n,o,s);return{destroy:()=>c.destroy()}},exports.fetch=(e,t)=>{const n={url:window.location.pathname+window.location.search,method:"GET",data:null,headers:{}},{url:o,method:r,headers:a,data:s}={...n,...e},c=new XMLHttpRequest;return c.onreadystatechange=function(){4===c.readyState&&t(c)},c.open(r,o,!0),Object.entries(a).forEach(e=>{let[t,n]=e;c.setRequestHeader(t,n)}),c.send(s),c},exports.getCurrentUrl=n,exports.getDataFromHtml=(e,t)=>{var n,a;let s=document.createElement("html");s.innerHTML=e;let c=[];t.forEach(e=>{if(null==o(e,s))return console.warn("[swup] Container "+e+" not found on page."),null;r(e).length!==r(e,s).length&&console.warn("[swup] Mismatched number of containers found on new page."),r(e).forEach((t,n)=>{r(e,s)[n].setAttribute("data-swup",String(c.length)),c.push(r(e,s)[n].outerHTML)})});const i=(null==(n=o("title",s))?void 0:n.innerText)||"",l=null==(a=o("body",s))?void 0:a.className;return s.innerHTML="",s=null,{title:i,pageClass:l,blocks:c,originalContent:e}},exports.markSwupElements=(e,t)=>{let n=0;t.forEach(t=>{null==o(t,e)?console.warn("[swup] Container "+t+" not found on page."):r(t).forEach((o,a)=>{r(t,e)[a].setAttribute("data-swup",String(n)),n++})})},exports.updateHistoryRecord=function(e,t){void 0===e&&(e=null),void 0===t&&(t={}),e=e||n({hash:!0});const o={...history.state,url:e,random:Math.random(),source:"swup",...t};history.replaceState(o,"",e)},exports.versionSatisfies=(e,t)=>t.every(t=>{const[,n,o]=t.match(/^([\D]+)?(.*)$/)||[];var r,a;return((e,t)=>{const n={"":e=>0===e,">":e=>e>0,">=":e=>e>=0,"<":e=>e<0,"<=":e=>e<=0};return(n[t]||n[""])(e)})((a=o,r=c(r=e),a=c(a),r.localeCompare(a,void 0,{numeric:!0})),n||">=")});
2
- //# sourceMappingURL=helpers.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"helpers.cjs","sources":["../src/helpers/classify.ts","../src/helpers/getCurrentUrl.ts","../src/utils/index.ts","../src/helpers/Location.ts","../src/helpers/markSwupElements.ts","../src/helpers/cleanupAnimationClasses.ts","../src/helpers/versionSatisfies.ts","../src/helpers/createHistoryRecord.ts","../src/helpers/delegateEvent.ts","../src/helpers/fetch.ts","../src/helpers/getDataFromHtml.ts","../src/helpers/updateHistoryRecord.ts"],"sourcesContent":["const classify = (text: string, fallback?: string): string => {\n\tconst output = String(text)\n\t\t.toLowerCase()\n\t\t// .normalize('NFD') // split an accented letter in the base letter and the acent\n\t\t// .replace(/[\\u0300-\\u036f]/g, '') // remove all previously split accents\n\t\t.replace(/[\\s/_.]+/g, '-') // replace spaces and _./ with '-'\n\t\t.replace(/[^\\w-]+/g, '') // remove all non-word chars\n\t\t.replace(/--+/g, '-') // replace repeating '-' with single '-'\n\t\t.replace(/^-+|-+$/, ''); // trim '-' from edges\n\treturn output || fallback || '';\n};\n\nexport default classify;\n","const getCurrentUrl = ({ hash }: { hash?: boolean } = {}): string => {\n\treturn location.pathname + location.search + (hash ? location.hash : '');\n};\n\nexport default getCurrentUrl;\n","export const query = (selector: string, context: Document | Element = document) => {\n\treturn context.querySelector<HTMLElement>(selector);\n};\n\nexport const queryAll = (\n\tselector: string,\n\tcontext: Document | Element = document\n): HTMLElement[] => {\n\treturn Array.from(context.querySelectorAll(selector));\n};\n\nexport const nextTick = (callback: () => void) => {\n\trequestAnimationFrame(() => {\n\t\trequestAnimationFrame(() => {\n\t\t\tcallback();\n\t\t});\n\t});\n};\n\nexport const escapeCssIdentifier = (ident: string) => {\n\t// @ts-ignore this is for support check, so it's correct that TS complains\n\tif (window.CSS && window.CSS.escape) {\n\t\treturn CSS.escape(ident);\n\t} else {\n\t\treturn ident;\n\t}\n};\n\n// Fix for Chrome below v61 formatting CSS floats with comma in some locales\nexport const toMs = (s: string) => {\n\treturn Number(s.slice(0, -1).replace(',', '.')) * 1000;\n};\n","/**\n * A helper for creating a Location from either an element\n * or a URL object/string\n *\n * Note: this could be implemented as a class inheriting from URL\n * Except: Babel will add tons of boilerplate for ES6 classes + getters\n * So for now it's implemented as an augmented URL object with custom getter\n *\n * class Location extends URL {\n * get url() {\n *\t return this.pathname + this.search;\n * }\n * }\n *\n */\n\nexport default class Location extends URL {\n\tconstructor(url: string, base: string = document.baseURI) {\n\t\tsuper(url.toString(), base);\n\t}\n\n\tget url() {\n\t\treturn this.pathname + this.search;\n\t}\n\n\t/**\n\t * Instantiate a Location from an element's href attribute\n\t * @param {Element} el\n\t * @return new Location instance\n\t */\n\tstatic fromElement(el: HTMLAnchorElement): Location {\n\t\tconst href = el.getAttribute('href') || el.getAttribute('xlink:href');\n\t\treturn new Location(href!);\n\t}\n\n\t/**\n\t * Instantiate a Location from a URL object or string\n\t * @param {URL|string} url\n\t * @return new Location instance\n\t */\n\tstatic fromUrl(url: string): Location {\n\t\treturn new Location(url);\n\t}\n}\n","import { query, queryAll } from '../utils.js';\n\nconst markSwupElements = (element: Element, containers: string[]): void => {\n\tlet blocks = 0;\n\n\tcontainers.forEach((selector) => {\n\t\tif (query(selector, element) == null) {\n\t\t\tconsole.warn(`[swup] Container ${selector} not found on page.`);\n\t\t} else {\n\t\t\tqueryAll(selector).forEach((item: Element, index: number) => {\n\t\t\t\tqueryAll(selector, element)[index].setAttribute('data-swup', String(blocks));\n\t\t\t\tblocks++;\n\t\t\t});\n\t\t}\n\t});\n};\n\nexport default markSwupElements;\n","const isSwupClass = (className: string): boolean =>\n\t/^to-/.test(className) || ['is-changing', 'is-rendering', 'is-popstate'].includes(className);\n\nconst cleanupAnimationClasses = (): void => {\n\tconst htmlClasses = document.documentElement.className.split(' ');\n\tconst removeClasses = htmlClasses.filter(isSwupClass);\n\tdocument.documentElement.classList.remove(...removeClasses);\n};\n\nexport default cleanupAnimationClasses;\n","type Comparator = '>' | '>=' | '<' | '<=';\n\n// Fill versions to exactly 3 decimals\nconst normalizeVersion = (version: string): string => {\n\treturn String(version).split('.').concat(['0', '0']).slice(0, 3).join('.');\n};\n\n// Numerically compare version strings after normalizing them\nconst compareVersion = (a: string, b: string): number => {\n\ta = normalizeVersion(a);\n\tb = normalizeVersion(b);\n\treturn a.localeCompare(b, undefined, { numeric: true });\n};\n\n// Apply a comparator (equals, greater-than, etc) by its symbol to a sort comparison\nconst applyComparator = (comparisonResult: number, comparator: Comparator) => {\n\tconst comparators = {\n\t\t'': (r: number) => r === 0,\n\t\t'>': (r: number) => r > 0,\n\t\t'>=': (r: number) => r >= 0,\n\t\t'<': (r: number) => r < 0,\n\t\t'<=': (r: number) => r <= 0\n\t};\n\tconst comparatorFn = comparators[comparator] || comparators[''];\n\treturn comparatorFn(comparisonResult);\n};\n\n/**\n * Check if a version satisfies all given version requirements\n *\n * versionSatisfies('2.1.0', ['>=2', '<4']) // true\n * versionSatisfies('2.1.0', ['5']) // false\n *\n * @param {string} installed Installed version\n * @param {Array.<string>} requirements Array of requirements that must be satisfied\n * @returns boolean\n */\nexport const versionSatisfies = (installed: string, requirements: string[]) => {\n\treturn requirements.every((required) => {\n\t\tconst [, comparator, version] = required.match(/^([\\D]+)?(.*)$/) || [];\n\t\tconst comparisonResult = compareVersion(installed, version);\n\t\treturn applyComparator(comparisonResult, (comparator as Comparator) || '>=');\n\t});\n};\n\nexport default versionSatisfies;\n","import { default as getCurrentUrl } from './getCurrentUrl.js';\n\nconst createHistoryRecord = (url: string, customData: Record<string, unknown> = {}): void => {\n\turl = url || getCurrentUrl({ hash: true });\n\tconst data = {\n\t\turl,\n\t\trandom: Math.random(),\n\t\tsource: 'swup',\n\t\t...customData\n\t};\n\thistory.pushState(data, '', url);\n};\n\nexport default createHistoryRecord;\n","import delegate, { EventType } from 'delegate-it';\nimport { ParseSelector } from 'typed-query-selector/parser';\n\nexport type Unsubscribe = {\n\tdestroy: () => void;\n};\nconst delegateEvent = <Selector extends string, TEvent extends EventType>(\n\tselector: Selector,\n\ttype: TEvent,\n\tcallback: delegate.EventHandler<GlobalEventHandlersEventMap[TEvent]>,\n\t{ base = document, ...eventOptions } = {}\n): Unsubscribe => {\n\tconst delegation = delegate<string, ParseSelector<Selector, HTMLElement>, TEvent>(\n\t\tbase,\n\t\tselector,\n\t\ttype,\n\t\tcallback,\n\t\teventOptions\n\t);\n\treturn { destroy: () => delegation.destroy() };\n};\n\nexport default delegateEvent;\n","import { TransitionOptions } from '../modules/loadPage.js';\nimport { Options } from '../Swup.js';\n\nconst fetch = (\n\toptions: TransitionOptions & { headers: Options['requestHeaders'] },\n\tcallback: (request: XMLHttpRequest) => void\n): XMLHttpRequest => {\n\tconst defaults = {\n\t\turl: window.location.pathname + window.location.search,\n\t\tmethod: 'GET',\n\t\tdata: null,\n\t\theaders: {}\n\t};\n\n\tconst { url, method, headers, data } = { ...defaults, ...options };\n\n\tconst request = new XMLHttpRequest();\n\n\trequest.onreadystatechange = function () {\n\t\tif (request.readyState === 4) {\n\t\t\t// if (request.status === 500) {} else {}\n\t\t\tcallback(request);\n\t\t}\n\t};\n\n\trequest.open(method, url, true);\n\tObject.entries(headers).forEach(([key, header]) => {\n\t\trequest.setRequestHeader(key, header);\n\t});\n\trequest.send(data);\n\n\treturn request;\n};\n\nexport default fetch;\n","import { query, queryAll } from '../utils.js';\n\nexport type PageHtmlData = {\n\ttitle: string;\n\toriginalContent: string;\n\tblocks: string[];\n\tpageClass?: string;\n};\n\nconst getDataFromHtml = (html: string, containers: string[]): PageHtmlData => {\n\tlet fakeDom = document.createElement('html');\n\tfakeDom.innerHTML = html;\n\tlet blocks: string[] = [];\n\n\tcontainers.forEach((selector) => {\n\t\tif (query(selector, fakeDom) == null) {\n\t\t\tconsole.warn(`[swup] Container ${selector} not found on page.`);\n\t\t\treturn null;\n\t\t} else {\n\t\t\tif (queryAll(selector).length !== queryAll(selector, fakeDom).length) {\n\t\t\t\tconsole.warn(`[swup] Mismatched number of containers found on new page.`);\n\t\t\t}\n\t\t\tqueryAll(selector).forEach((item, index) => {\n\t\t\t\tqueryAll(selector, fakeDom)[index].setAttribute('data-swup', String(blocks.length));\n\t\t\t\tblocks.push(queryAll(selector, fakeDom)[index].outerHTML);\n\t\t\t});\n\t\t}\n\t});\n\n\tconst title = query('title', fakeDom)?.innerText || '';\n\tconst pageClass = query('body', fakeDom)?.className;\n\n\t// to prevent memory leaks\n\tfakeDom.innerHTML = '';\n\t// @ts-ignore don't want to type it as possible null, since it's created at the top of the function always\n\tfakeDom = null;\n\n\treturn { title, pageClass, blocks, originalContent: html };\n};\n\nexport default getDataFromHtml;\n","import { default as getCurrentUrl } from './getCurrentUrl.js';\n\nconst updateHistoryRecord = (\n\turl: string | null = null,\n\tcustomData: Record<string, unknown> = {}\n): void => {\n\turl = url || getCurrentUrl({ hash: true });\n\tconst data = {\n\t\t...history.state,\n\t\turl,\n\t\trandom: Math.random(),\n\t\tsource: 'swup',\n\t\t...customData\n\t};\n\thistory.replaceState(data, '', url);\n};\n\nexport default updateHistoryRecord;\n"],"names":["classify","getCurrentUrl","_temp","hash","pathname","location","search","query","selector","context","document","querySelector","queryAll","Array","from","querySelectorAll","Location","constructor","url","base","baseURI","super","toString","this","static","el","getAttribute","href","markSwupElements","isSwupClass","className","test","includes","normalizeVersion","version","String","split","concat","slice","join","text","fallback","toLowerCase","replace","removeClasses","documentElement","filter","classList","remove","customData","data","random","Math","source","history","pushState","type","callback","eventOptions","delegate","destroy","delegation","options","defaults","window","method","headers","request","XMLHttpRequest","onreadystatechange","readyState","open","Object","entries","forEach","_ref","key","header","setRequestHeader","send","html","containers","_query","_query2","createElement","fakeDom","innerHTML","blocks","console","warn","length","item","index","setAttribute","push","outerHTML","title","innerText","pageClass","originalContent","element","state","replaceState","installed","requirements","every","required","comparator","match","a","b","comparisonResult","comparators","r","applyComparator","localeCompare","undefined","numeric"],"mappings":"qHAAMA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AA6B,KAAI"}
@@ -1,2 +0,0 @@
1
- import e from"delegate-it";const t=(e,t)=>String(e).toLowerCase().replace(/[\s/_.]+/g,"-").replace(/[^\w-]+/g,"").replace(/--+/g,"-").replace(/^-+|-+$/,"")||t||"";function n(){return n=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},n.apply(this,arguments)}const r=({hash:e}={})=>location.pathname+location.search+(e?location.hash:""),o=(e,t={})=>{const o=n({url:e=e||r({hash:!0}),random:Math.random(),source:"swup"},t);history.pushState(o,"",e)},a=(e=null,t={})=>{e=e||r({hash:!0});const o=n({},history.state,{url:e,random:Math.random(),source:"swup"},t);history.replaceState(o,"",e)},s=["base"],c=(t,n,r,o={})=>{let{base:a=document}=o,c=function(e,t){if(null==e)return{};var n,r,o={},a=Object.keys(e);for(r=0;r<a.length;r++)t.indexOf(n=a[r])>=0||(o[n]=e[n]);return o}(o,s);const l=e(a,t,n,r,c);return{destroy:()=>l.destroy()}},l=(e,t=document)=>t.querySelector(e),u=(e,t=document)=>Array.from(t.querySelectorAll(e)),i=(e,t)=>{var n,r;let o=document.createElement("html");o.innerHTML=e;let a=[];t.forEach(e=>{if(null==l(e,o))return console.warn(`[swup] Container ${e} not found on page.`),null;u(e).length!==u(e,o).length&&console.warn("[swup] Mismatched number of containers found on new page."),u(e).forEach((t,n)=>{u(e,o)[n].setAttribute("data-swup",String(a.length)),a.push(u(e,o)[n].outerHTML)})});const s=(null==(n=l("title",o))?void 0:n.innerText)||"",c=null==(r=l("body",o))?void 0:r.className;return o.innerHTML="",o=null,{title:s,pageClass:c,blocks:a,originalContent:e}},h=(e,t)=>{const r={url:window.location.pathname+window.location.search,method:"GET",data:null,headers:{}},{url:o,method:a,headers:s,data:c}=n({},r,e),l=new XMLHttpRequest;return l.onreadystatechange=function(){4===l.readyState&&t(l)},l.open(a,o,!0),Object.entries(s).forEach(([e,t])=>{l.setRequestHeader(e,t)}),l.send(c),l};class d extends URL{constructor(e,t=document.baseURI){super(e.toString(),t)}get url(){return this.pathname+this.search}static fromElement(e){const t=e.getAttribute("href")||e.getAttribute("xlink:href");return new d(t)}static fromUrl(e){return new d(e)}}const m=(e,t)=>{let n=0;t.forEach(t=>{null==l(t,e)?console.warn(`[swup] Container ${t} not found on page.`):u(t).forEach((r,o)=>{u(t,e)[o].setAttribute("data-swup",String(n)),n++})})},p=e=>/^to-/.test(e)||["is-changing","is-rendering","is-popstate"].includes(e),g=()=>{const e=document.documentElement.className.split(" ").filter(p);document.documentElement.classList.remove(...e)},f=e=>String(e).split(".").concat(["0","0"]).slice(0,3).join("."),w=(e,t)=>t.every(t=>{const[,n,r]=t.match(/^([\D]+)?(.*)$/)||[];var o,a;return((e,t)=>{const n={"":e=>0===e,">":e=>e>0,">=":e=>e>=0,"<":e=>e<0,"<=":e=>e<=0};return(n[t]||n[""])(e)})((a=r,o=f(o=e),a=f(a),o.localeCompare(a,void 0,{numeric:!0})),n||">=")});export{d as Location,t as classify,g as cleanupAnimationClasses,o as createHistoryRecord,c as delegateEvent,h as fetch,r as getCurrentUrl,i as getDataFromHtml,m as markSwupElements,a as updateHistoryRecord,w as versionSatisfies};
2
- //# sourceMappingURL=helpers.modern.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"helpers.modern.js","sources":["../src/helpers/classify.ts","../src/helpers/getCurrentUrl.ts","../src/helpers/createHistoryRecord.ts","../src/helpers/updateHistoryRecord.ts","../src/helpers/delegateEvent.ts","../src/utils/index.ts","../src/helpers/getDataFromHtml.ts","../src/helpers/fetch.ts","../src/helpers/Location.ts","../src/helpers/markSwupElements.ts","../src/helpers/cleanupAnimationClasses.ts","../src/helpers/versionSatisfies.ts"],"sourcesContent":["const classify = (text: string, fallback?: string): string => {\n\tconst output = String(text)\n\t\t.toLowerCase()\n\t\t// .normalize('NFD') // split an accented letter in the base letter and the acent\n\t\t// .replace(/[\\u0300-\\u036f]/g, '') // remove all previously split accents\n\t\t.replace(/[\\s/_.]+/g, '-') // replace spaces and _./ with '-'\n\t\t.replace(/[^\\w-]+/g, '') // remove all non-word chars\n\t\t.replace(/--+/g, '-') // replace repeating '-' with single '-'\n\t\t.replace(/^-+|-+$/, ''); // trim '-' from edges\n\treturn output || fallback || '';\n};\n\nexport default classify;\n","const getCurrentUrl = ({ hash }: { hash?: boolean } = {}): string => {\n\treturn location.pathname + location.search + (hash ? location.hash : '');\n};\n\nexport default getCurrentUrl;\n","import { default as getCurrentUrl } from './getCurrentUrl.js';\n\nconst createHistoryRecord = (url: string, customData: Record<string, unknown> = {}): void => {\n\turl = url || getCurrentUrl({ hash: true });\n\tconst data = {\n\t\turl,\n\t\trandom: Math.random(),\n\t\tsource: 'swup',\n\t\t...customData\n\t};\n\thistory.pushState(data, '', url);\n};\n\nexport default createHistoryRecord;\n","import { default as getCurrentUrl } from './getCurrentUrl.js';\n\nconst updateHistoryRecord = (\n\turl: string | null = null,\n\tcustomData: Record<string, unknown> = {}\n): void => {\n\turl = url || getCurrentUrl({ hash: true });\n\tconst data = {\n\t\t...history.state,\n\t\turl,\n\t\trandom: Math.random(),\n\t\tsource: 'swup',\n\t\t...customData\n\t};\n\thistory.replaceState(data, '', url);\n};\n\nexport default updateHistoryRecord;\n","import delegate, { EventType } from 'delegate-it';\nimport { ParseSelector } from 'typed-query-selector/parser';\n\nexport type Unsubscribe = {\n\tdestroy: () => void;\n};\nconst delegateEvent = <Selector extends string, TEvent extends EventType>(\n\tselector: Selector,\n\ttype: TEvent,\n\tcallback: delegate.EventHandler<GlobalEventHandlersEventMap[TEvent]>,\n\t{ base = document, ...eventOptions } = {}\n): Unsubscribe => {\n\tconst delegation = delegate<string, ParseSelector<Selector, HTMLElement>, TEvent>(\n\t\tbase,\n\t\tselector,\n\t\ttype,\n\t\tcallback,\n\t\teventOptions\n\t);\n\treturn { destroy: () => delegation.destroy() };\n};\n\nexport default delegateEvent;\n","export const query = (selector: string, context: Document | Element = document) => {\n\treturn context.querySelector<HTMLElement>(selector);\n};\n\nexport const queryAll = (\n\tselector: string,\n\tcontext: Document | Element = document\n): HTMLElement[] => {\n\treturn Array.from(context.querySelectorAll(selector));\n};\n\nexport const nextTick = (callback: () => void) => {\n\trequestAnimationFrame(() => {\n\t\trequestAnimationFrame(() => {\n\t\t\tcallback();\n\t\t});\n\t});\n};\n\nexport const escapeCssIdentifier = (ident: string) => {\n\t// @ts-ignore this is for support check, so it's correct that TS complains\n\tif (window.CSS && window.CSS.escape) {\n\t\treturn CSS.escape(ident);\n\t} else {\n\t\treturn ident;\n\t}\n};\n\n// Fix for Chrome below v61 formatting CSS floats with comma in some locales\nexport const toMs = (s: string) => {\n\treturn Number(s.slice(0, -1).replace(',', '.')) * 1000;\n};\n","import { query, queryAll } from '../utils.js';\n\nexport type PageHtmlData = {\n\ttitle: string;\n\toriginalContent: string;\n\tblocks: string[];\n\tpageClass?: string;\n};\n\nconst getDataFromHtml = (html: string, containers: string[]): PageHtmlData => {\n\tlet fakeDom = document.createElement('html');\n\tfakeDom.innerHTML = html;\n\tlet blocks: string[] = [];\n\n\tcontainers.forEach((selector) => {\n\t\tif (query(selector, fakeDom) == null) {\n\t\t\tconsole.warn(`[swup] Container ${selector} not found on page.`);\n\t\t\treturn null;\n\t\t} else {\n\t\t\tif (queryAll(selector).length !== queryAll(selector, fakeDom).length) {\n\t\t\t\tconsole.warn(`[swup] Mismatched number of containers found on new page.`);\n\t\t\t}\n\t\t\tqueryAll(selector).forEach((item, index) => {\n\t\t\t\tqueryAll(selector, fakeDom)[index].setAttribute('data-swup', String(blocks.length));\n\t\t\t\tblocks.push(queryAll(selector, fakeDom)[index].outerHTML);\n\t\t\t});\n\t\t}\n\t});\n\n\tconst title = query('title', fakeDom)?.innerText || '';\n\tconst pageClass = query('body', fakeDom)?.className;\n\n\t// to prevent memory leaks\n\tfakeDom.innerHTML = '';\n\t// @ts-ignore don't want to type it as possible null, since it's created at the top of the function always\n\tfakeDom = null;\n\n\treturn { title, pageClass, blocks, originalContent: html };\n};\n\nexport default getDataFromHtml;\n","import { TransitionOptions } from '../modules/loadPage.js';\nimport { Options } from '../Swup.js';\n\nconst fetch = (\n\toptions: TransitionOptions & { headers: Options['requestHeaders'] },\n\tcallback: (request: XMLHttpRequest) => void\n): XMLHttpRequest => {\n\tconst defaults = {\n\t\turl: window.location.pathname + window.location.search,\n\t\tmethod: 'GET',\n\t\tdata: null,\n\t\theaders: {}\n\t};\n\n\tconst { url, method, headers, data } = { ...defaults, ...options };\n\n\tconst request = new XMLHttpRequest();\n\n\trequest.onreadystatechange = function () {\n\t\tif (request.readyState === 4) {\n\t\t\t// if (request.status === 500) {} else {}\n\t\t\tcallback(request);\n\t\t}\n\t};\n\n\trequest.open(method, url, true);\n\tObject.entries(headers).forEach(([key, header]) => {\n\t\trequest.setRequestHeader(key, header);\n\t});\n\trequest.send(data);\n\n\treturn request;\n};\n\nexport default fetch;\n","/**\n * A helper for creating a Location from either an element\n * or a URL object/string\n *\n * Note: this could be implemented as a class inheriting from URL\n * Except: Babel will add tons of boilerplate for ES6 classes + getters\n * So for now it's implemented as an augmented URL object with custom getter\n *\n * class Location extends URL {\n * get url() {\n *\t return this.pathname + this.search;\n * }\n * }\n *\n */\n\nexport default class Location extends URL {\n\tconstructor(url: string, base: string = document.baseURI) {\n\t\tsuper(url.toString(), base);\n\t}\n\n\tget url() {\n\t\treturn this.pathname + this.search;\n\t}\n\n\t/**\n\t * Instantiate a Location from an element's href attribute\n\t * @param {Element} el\n\t * @return new Location instance\n\t */\n\tstatic fromElement(el: HTMLAnchorElement): Location {\n\t\tconst href = el.getAttribute('href') || el.getAttribute('xlink:href');\n\t\treturn new Location(href!);\n\t}\n\n\t/**\n\t * Instantiate a Location from a URL object or string\n\t * @param {URL|string} url\n\t * @return new Location instance\n\t */\n\tstatic fromUrl(url: string): Location {\n\t\treturn new Location(url);\n\t}\n}\n","import { query, queryAll } from '../utils.js';\n\nconst markSwupElements = (element: Element, containers: string[]): void => {\n\tlet blocks = 0;\n\n\tcontainers.forEach((selector) => {\n\t\tif (query(selector, element) == null) {\n\t\t\tconsole.warn(`[swup] Container ${selector} not found on page.`);\n\t\t} else {\n\t\t\tqueryAll(selector).forEach((item: Element, index: number) => {\n\t\t\t\tqueryAll(selector, element)[index].setAttribute('data-swup', String(blocks));\n\t\t\t\tblocks++;\n\t\t\t});\n\t\t}\n\t});\n};\n\nexport default markSwupElements;\n","const isSwupClass = (className: string): boolean =>\n\t/^to-/.test(className) || ['is-changing', 'is-rendering', 'is-popstate'].includes(className);\n\nconst cleanupAnimationClasses = (): void => {\n\tconst htmlClasses = document.documentElement.className.split(' ');\n\tconst removeClasses = htmlClasses.filter(isSwupClass);\n\tdocument.documentElement.classList.remove(...removeClasses);\n};\n\nexport default cleanupAnimationClasses;\n","type Comparator = '>' | '>=' | '<' | '<=';\n\n// Fill versions to exactly 3 decimals\nconst normalizeVersion = (version: string): string => {\n\treturn String(version).split('.').concat(['0', '0']).slice(0, 3).join('.');\n};\n\n// Numerically compare version strings after normalizing them\nconst compareVersion = (a: string, b: string): number => {\n\ta = normalizeVersion(a);\n\tb = normalizeVersion(b);\n\treturn a.localeCompare(b, undefined, { numeric: true });\n};\n\n// Apply a comparator (equals, greater-than, etc) by its symbol to a sort comparison\nconst applyComparator = (comparisonResult: number, comparator: Comparator) => {\n\tconst comparators = {\n\t\t'': (r: number) => r === 0,\n\t\t'>': (r: number) => r > 0,\n\t\t'>=': (r: number) => r >= 0,\n\t\t'<': (r: number) => r < 0,\n\t\t'<=': (r: number) => r <= 0\n\t};\n\tconst comparatorFn = comparators[comparator] || comparators[''];\n\treturn comparatorFn(comparisonResult);\n};\n\n/**\n * Check if a version satisfies all given version requirements\n *\n * versionSatisfies('2.1.0', ['>=2', '<4']) // true\n * versionSatisfies('2.1.0', ['5']) // false\n *\n * @param {string} installed Installed version\n * @param {Array.<string>} requirements Array of requirements that must be satisfied\n * @returns boolean\n */\nexport const versionSatisfies = (installed: string, requirements: string[]) => {\n\treturn requirements.every((required) => {\n\t\tconst [, comparator, version] = required.match(/^([\\D]+)?(.*)$/) || [];\n\t\tconst comparisonResult = compareVersion(installed, version);\n\t\treturn applyComparator(comparisonResult, (comparator as Comparator) || '>=');\n\t});\n};\n\nexport default versionSatisfies;\n"],"names":["classify","text","fallback","String","toLowerCase","replace","getCurrentUrl","hash","pathname","location","search","createHistoryRecord","url","customData","data","random","Math","source","history","pushState","updateHistoryRecord","_extends","state","replaceState","delegateEvent","selector","type","callback","_ref","base","document","eventOptions","_objectWithoutPropertiesLoose","_excluded","delegate","destroy","delegation","query","context","querySelector","queryAll","Array","from","querySelectorAll","getDataFromHtml","html","containers","fakeDom","createElement","innerHTML","blocks","forEach","console","warn","length","item","index","setAttribute","push","outerHTML","title","_query","innerText","_query2","className","pageClass","originalContent","fetch","options","defaults","window","method","headers","request","XMLHttpRequest","onreadystatechange","readyState","open","Object","entries","key","header","setRequestHeader","send","Location","URL","constructor","baseURI","super","toString","this","static","el","href","getAttribute","markSwupElements","element","isSwupClass","test","includes","cleanupAnimationClasses","removeClasses","documentElement","split","filter","classList","remove","normalizeVersion","version","concat","slice","join","versionSatisfies","installed","requirements","every","required","comparator","match","a","b","comparisonResult","comparators","r","applyComparator","localeCompare","undefined","numeric"],"mappings":"2BAAMA,MAAAA,EAAW,CAACC,EAAcC,IAChBC,OAAOF,GACpBG,cAGAC,QAAQ,YAAa,KACrBA,QAAQ,WAAY,IACpBA,QAAQ,OAAQ,KAChBA,QAAQ,UAAW,KACJH,GAAY,uOCTxBI,MAAaA,EAAG,EAAGC,QAA6B,CAAE,aACvCC,SAAWC,SAASC,QAAUH,EAAOE,SAASF,KAAO,ICChEI,EAAsB,CAACC,EAAaC,EAAsC,CAAA,KAE/E,MAAMC,EACLF,EAAAA,CAAAA,IAFDA,EAAMA,GAAON,EAAc,CAAEC,MAAM,IAGlCQ,OAAQC,KAAKD,SACbE,OAAQ,QACLJ,GAEJK,QAAQC,UAAUL,EAAM,GAAIF,E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E,SAASwE,gBAAgBG,UAAUC,UAAUL,EAC9C,ECJMM,EAAoBC,GAClBzG,OAAOyG,GAASL,MAAM,KAAKM,OAAO,CAAC,IAAK,MAAMC,MAAM,EAAG,GAAGC,KAAK,KAiC1CC,EAAG,CAACC,EAAmBC,IAC5CA,EAAaC,MAAOC,IAC1B,OAASC,EAAYT,GAAWQ,EAASE,MAAM,mBAAqB,GA/B/C,IAACC,EAAWC,EAiCjC,MA1BsB,EAACC,EAA0BJ,KAClD,MAAMK,EAAc,CACnB,GAAKC,GAAoB,IAANA,EACnB,IAAMA,GAAcA,EAAI,EACxB,KAAOA,GAAcA,GAAK,EAC1B,IAAMA,GAAcA,EAAI,EACxB,KAAOA,GAAcA,GAAK,GAG3B,OADqBD,EAAYL,IAAeK,EAAY,KACxCD,EAAgB,EAiB5BG,EAjC0BJ,EAgCkBZ,EA/BpDW,EAAIZ,EADmBY,EAgCkBN,GA9BzCO,EAAIb,EAAiBa,GACbD,EAACM,cAAcL,OAAGM,EAAW,CAAEC,SAAS,KA8BLV,GAA6B,KAAI"}
@@ -1,2 +0,0 @@
1
- import t from"delegate-it";const e=(t,e)=>String(t).toLowerCase().replace(/[\s/_.]+/g,"-").replace(/[^\w-]+/g,"").replace(/--+/g,"-").replace(/^-+|-+$/,"")||e||"",n=function(t){let{hash:e}=void 0===t?{}:t;return location.pathname+location.search+(e?location.hash:"")},o=function(t,e){void 0===e&&(e={});const o={url:t=t||n({hash:!0}),random:Math.random(),source:"swup",...e};history.pushState(o,"",t)},r=function(t,e){void 0===t&&(t=null),void 0===e&&(e={}),t=t||n({hash:!0});const o={...history.state,url:t,random:Math.random(),source:"swup",...e};history.replaceState(o,"",t)},a=function(e,n,o,r){let{base:a=document,...s}=void 0===r?{}:r;const c=t(a,e,n,o,s);return{destroy:()=>c.destroy()}},s=function(t,e){return void 0===e&&(e=document),e.querySelector(t)},c=function(t,e){return void 0===e&&(e=document),Array.from(e.querySelectorAll(t))},l=(t,e)=>{var n,o;let r=document.createElement("html");r.innerHTML=t;let a=[];e.forEach(t=>{if(null==s(t,r))return console.warn("[swup] Container "+t+" not found on page."),null;c(t).length!==c(t,r).length&&console.warn("[swup] Mismatched number of containers found on new page."),c(t).forEach((e,n)=>{c(t,r)[n].setAttribute("data-swup",String(a.length)),a.push(c(t,r)[n].outerHTML)})});const l=(null==(n=s("title",r))?void 0:n.innerText)||"",i=null==(o=s("body",r))?void 0:o.className;return r.innerHTML="",r=null,{title:l,pageClass:i,blocks:a,originalContent:t}},i=(t,e)=>{const n={url:window.location.pathname+window.location.search,method:"GET",data:null,headers:{}},{url:o,method:r,headers:a,data:s}={...n,...t},c=new XMLHttpRequest;return c.onreadystatechange=function(){4===c.readyState&&e(c)},c.open(r,o,!0),Object.entries(a).forEach(t=>{let[e,n]=t;c.setRequestHeader(e,n)}),c.send(s),c};class u extends URL{constructor(t,e){void 0===e&&(e=document.baseURI),super(t.toString(),e)}get url(){return this.pathname+this.search}static fromElement(t){const e=t.getAttribute("href")||t.getAttribute("xlink:href");return new u(e)}static fromUrl(t){return new u(t)}}const d=(t,e)=>{let n=0;e.forEach(e=>{null==s(e,t)?console.warn("[swup] Container "+e+" not found on page."):c(e).forEach((o,r)=>{c(e,t)[r].setAttribute("data-swup",String(n)),n++})})},h=t=>/^to-/.test(t)||["is-changing","is-rendering","is-popstate"].includes(t),m=()=>{const t=document.documentElement.className.split(" ").filter(h);document.documentElement.classList.remove(...t)},p=t=>String(t).split(".").concat(["0","0"]).slice(0,3).join("."),f=(t,e)=>e.every(e=>{const[,n,o]=e.match(/^([\D]+)?(.*)$/)||[];var r,a;return((t,e)=>{const n={"":t=>0===t,">":t=>t>0,">=":t=>t>=0,"<":t=>t<0,"<=":t=>t<=0};return(n[e]||n[""])(t)})((a=o,r=p(r=t),a=p(a),r.localeCompare(a,void 0,{numeric:!0})),n||">=")});export{u as Location,e as classify,m as cleanupAnimationClasses,o as createHistoryRecord,a as delegateEvent,i as fetch,n as getCurrentUrl,l as getDataFromHtml,d as markSwupElements,r as updateHistoryRecord,f as versionSatisfies};
2
- //# sourceMappingURL=helpers.module.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"helpers.module.js","sources":["../src/helpers/classify.ts","../src/helpers/getCurrentUrl.ts","../src/helpers/createHistoryRecord.ts","../src/helpers/updateHistoryRecord.ts","../src/helpers/delegateEvent.ts","../src/utils/index.ts","../src/helpers/getDataFromHtml.ts","../src/helpers/fetch.ts","../src/helpers/Location.ts","../src/helpers/markSwupElements.ts","../src/helpers/cleanupAnimationClasses.ts","../src/helpers/versionSatisfies.ts"],"sourcesContent":["const classify = (text: string, fallback?: string): string => {\n\tconst output = String(text)\n\t\t.toLowerCase()\n\t\t// .normalize('NFD') // split an accented letter in the base letter and the acent\n\t\t// .replace(/[\\u0300-\\u036f]/g, '') // remove all previously split accents\n\t\t.replace(/[\\s/_.]+/g, '-') // replace spaces and _./ with '-'\n\t\t.replace(/[^\\w-]+/g, '') // remove all non-word chars\n\t\t.replace(/--+/g, '-') // replace repeating '-' with single '-'\n\t\t.replace(/^-+|-+$/, ''); // trim '-' from edges\n\treturn output || fallback || '';\n};\n\nexport default classify;\n","const getCurrentUrl = ({ hash }: { hash?: boolean } = {}): string => {\n\treturn location.pathname + location.search + (hash ? location.hash : '');\n};\n\nexport default getCurrentUrl;\n","import { default as getCurrentUrl } from './getCurrentUrl.js';\n\nconst createHistoryRecord = (url: string, customData: Record<string, unknown> = {}): void => {\n\turl = url || getCurrentUrl({ hash: true });\n\tconst data = {\n\t\turl,\n\t\trandom: Math.random(),\n\t\tsource: 'swup',\n\t\t...customData\n\t};\n\thistory.pushState(data, '', url);\n};\n\nexport default createHistoryRecord;\n","import { default as getCurrentUrl } from './getCurrentUrl.js';\n\nconst updateHistoryRecord = (\n\turl: string | null = null,\n\tcustomData: Record<string, unknown> = {}\n): void => {\n\turl = url || getCurrentUrl({ hash: true });\n\tconst data = {\n\t\t...history.state,\n\t\turl,\n\t\trandom: Math.random(),\n\t\tsource: 'swup',\n\t\t...customData\n\t};\n\thistory.replaceState(data, '', url);\n};\n\nexport default updateHistoryRecord;\n","import delegate, { EventType } from 'delegate-it';\nimport { ParseSelector } from 'typed-query-selector/parser';\n\nexport type Unsubscribe = {\n\tdestroy: () => void;\n};\nconst delegateEvent = <Selector extends string, TEvent extends EventType>(\n\tselector: Selector,\n\ttype: TEvent,\n\tcallback: delegate.EventHandler<GlobalEventHandlersEventMap[TEvent]>,\n\t{ base = document, ...eventOptions } = {}\n): Unsubscribe => {\n\tconst delegation = delegate<string, ParseSelector<Selector, HTMLElement>, TEvent>(\n\t\tbase,\n\t\tselector,\n\t\ttype,\n\t\tcallback,\n\t\teventOptions\n\t);\n\treturn { destroy: () => delegation.destroy() };\n};\n\nexport default delegateEvent;\n","export const query = (selector: string, context: Document | Element = document) => {\n\treturn context.querySelector<HTMLElement>(selector);\n};\n\nexport const queryAll = (\n\tselector: string,\n\tcontext: Document | Element = document\n): HTMLElement[] => {\n\treturn Array.from(context.querySelectorAll(selector));\n};\n\nexport const nextTick = (callback: () => void) => {\n\trequestAnimationFrame(() => {\n\t\trequestAnimationFrame(() => {\n\t\t\tcallback();\n\t\t});\n\t});\n};\n\nexport const escapeCssIdentifier = (ident: string) => {\n\t// @ts-ignore this is for support check, so it's correct that TS complains\n\tif (window.CSS && window.CSS.escape) {\n\t\treturn CSS.escape(ident);\n\t} else {\n\t\treturn ident;\n\t}\n};\n\n// Fix for Chrome below v61 formatting CSS floats with comma in some locales\nexport const toMs = (s: string) => {\n\treturn Number(s.slice(0, -1).replace(',', '.')) * 1000;\n};\n","import { query, queryAll } from '../utils.js';\n\nexport type PageHtmlData = {\n\ttitle: string;\n\toriginalContent: string;\n\tblocks: string[];\n\tpageClass?: string;\n};\n\nconst getDataFromHtml = (html: string, containers: string[]): PageHtmlData => {\n\tlet fakeDom = document.createElement('html');\n\tfakeDom.innerHTML = html;\n\tlet blocks: string[] = [];\n\n\tcontainers.forEach((selector) => {\n\t\tif (query(selector, fakeDom) == null) {\n\t\t\tconsole.warn(`[swup] Container ${selector} not found on page.`);\n\t\t\treturn null;\n\t\t} else {\n\t\t\tif (queryAll(selector).length !== queryAll(selector, fakeDom).length) {\n\t\t\t\tconsole.warn(`[swup] Mismatched number of containers found on new page.`);\n\t\t\t}\n\t\t\tqueryAll(selector).forEach((item, index) => {\n\t\t\t\tqueryAll(selector, fakeDom)[index].setAttribute('data-swup', String(blocks.length));\n\t\t\t\tblocks.push(queryAll(selector, fakeDom)[index].outerHTML);\n\t\t\t});\n\t\t}\n\t});\n\n\tconst title = query('title', fakeDom)?.innerText || '';\n\tconst pageClass = query('body', fakeDom)?.className;\n\n\t// to prevent memory leaks\n\tfakeDom.innerHTML = '';\n\t// @ts-ignore don't want to type it as possible null, since it's created at the top of the function always\n\tfakeDom = null;\n\n\treturn { title, pageClass, blocks, originalContent: html };\n};\n\nexport default getDataFromHtml;\n","import { TransitionOptions } from '../modules/loadPage.js';\nimport { Options } from '../Swup.js';\n\nconst fetch = (\n\toptions: TransitionOptions & { headers: Options['requestHeaders'] },\n\tcallback: (request: XMLHttpRequest) => void\n): XMLHttpRequest => {\n\tconst defaults = {\n\t\turl: window.location.pathname + window.location.search,\n\t\tmethod: 'GET',\n\t\tdata: null,\n\t\theaders: {}\n\t};\n\n\tconst { url, method, headers, data } = { ...defaults, ...options };\n\n\tconst request = new XMLHttpRequest();\n\n\trequest.onreadystatechange = function () {\n\t\tif (request.readyState === 4) {\n\t\t\t// if (request.status === 500) {} else {}\n\t\t\tcallback(request);\n\t\t}\n\t};\n\n\trequest.open(method, url, true);\n\tObject.entries(headers).forEach(([key, header]) => {\n\t\trequest.setRequestHeader(key, header);\n\t});\n\trequest.send(data);\n\n\treturn request;\n};\n\nexport default fetch;\n","/**\n * A helper for creating a Location from either an element\n * or a URL object/string\n *\n * Note: this could be implemented as a class inheriting from URL\n * Except: Babel will add tons of boilerplate for ES6 classes + getters\n * So for now it's implemented as an augmented URL object with custom getter\n *\n * class Location extends URL {\n * get url() {\n *\t return this.pathname + this.search;\n * }\n * }\n *\n */\n\nexport default class Location extends URL {\n\tconstructor(url: string, base: string = document.baseURI) {\n\t\tsuper(url.toString(), base);\n\t}\n\n\tget url() {\n\t\treturn this.pathname + this.search;\n\t}\n\n\t/**\n\t * Instantiate a Location from an element's href attribute\n\t * @param {Element} el\n\t * @return new Location instance\n\t */\n\tstatic fromElement(el: HTMLAnchorElement): Location {\n\t\tconst href = el.getAttribute('href') || el.getAttribute('xlink:href');\n\t\treturn new Location(href!);\n\t}\n\n\t/**\n\t * Instantiate a Location from a URL object or string\n\t * @param {URL|string} url\n\t * @return new Location instance\n\t */\n\tstatic fromUrl(url: string): Location {\n\t\treturn new Location(url);\n\t}\n}\n","import { query, queryAll } from '../utils.js';\n\nconst markSwupElements = (element: Element, containers: string[]): void => {\n\tlet blocks = 0;\n\n\tcontainers.forEach((selector) => {\n\t\tif (query(selector, element) == null) {\n\t\t\tconsole.warn(`[swup] Container ${selector} not found on page.`);\n\t\t} else {\n\t\t\tqueryAll(selector).forEach((item: Element, index: number) => {\n\t\t\t\tqueryAll(selector, element)[index].setAttribute('data-swup', String(blocks));\n\t\t\t\tblocks++;\n\t\t\t});\n\t\t}\n\t});\n};\n\nexport default markSwupElements;\n","const isSwupClass = (className: string): boolean =>\n\t/^to-/.test(className) || ['is-changing', 'is-rendering', 'is-popstate'].includes(className);\n\nconst cleanupAnimationClasses = (): void => {\n\tconst htmlClasses = document.documentElement.className.split(' ');\n\tconst removeClasses = htmlClasses.filter(isSwupClass);\n\tdocument.documentElement.classList.remove(...removeClasses);\n};\n\nexport default cleanupAnimationClasses;\n","type Comparator = '>' | '>=' | '<' | '<=';\n\n// Fill versions to exactly 3 decimals\nconst normalizeVersion = (version: string): string => {\n\treturn String(version).split('.').concat(['0', '0']).slice(0, 3).join('.');\n};\n\n// Numerically compare version strings after normalizing them\nconst compareVersion = (a: string, b: string): number => {\n\ta = normalizeVersion(a);\n\tb = normalizeVersion(b);\n\treturn a.localeCompare(b, undefined, { numeric: true });\n};\n\n// Apply a comparator (equals, greater-than, etc) by its symbol to a sort comparison\nconst applyComparator = (comparisonResult: number, comparator: Comparator) => {\n\tconst comparators = {\n\t\t'': (r: number) => r === 0,\n\t\t'>': (r: number) => r > 0,\n\t\t'>=': (r: number) => r >= 0,\n\t\t'<': (r: number) => r < 0,\n\t\t'<=': (r: number) => r <= 0\n\t};\n\tconst comparatorFn = comparators[comparator] || comparators[''];\n\treturn comparatorFn(comparisonResult);\n};\n\n/**\n * Check if a version satisfies all given version requirements\n *\n * versionSatisfies('2.1.0', ['>=2', '<4']) // true\n * versionSatisfies('2.1.0', ['5']) // false\n *\n * @param {string} installed Installed version\n * @param {Array.<string>} requirements Array of requirements that must be satisfied\n * @returns boolean\n */\nexport const versionSatisfies = (installed: string, requirements: string[]) => {\n\treturn requirements.every((required) => {\n\t\tconst [, comparator, version] = required.match(/^([\\D]+)?(.*)$/) || [];\n\t\tconst comparisonResult = compareVersion(installed, version);\n\t\treturn applyComparator(comparisonResult, (comparator as Comparator) || '>=');\n\t});\n};\n\nexport default versionSatisfies;\n"],"names":["classify","text","fallback","String","toLowerCase","replace","getCurrentUrl","_temp","hash","pathname","location","search","createHistoryRecord","url","customData","data","random","Math","source","history","pushState","updateHistoryRecord","state","replaceState","delegateEvent","selector","type","callback","base","document","eventOptions","delegate","destroy","delegation","query","context","querySelector","queryAll","Array","from","querySelectorAll","html","containers","_query","_query2","createElement","fakeDom","innerHTML","blocks","forEach","console","warn","length","item","index","setAttribute","push","outerHTML","title","innerText","className","pageClass","originalContent","fetch","options","defaults","window","method","headers","request","XMLHttpRequest","onreadystatechange","readyState","open","Object","entries","_ref","key","header","setRequestHeader","send","Location","constructor","baseURI","super","toString","this","static","el","getAttribute","href","markSwupElements","element","isSwupClass","test","includes","cleanupAnimationClasses","removeClasses","documentElement","split","filter","classList","remove","normalizeVersion","version","concat","slice","join","versionSatisfies","installed","requirements","every","required","comparator","match","a","b","comparisonResult","comparators","r","applyComparator","localeCompare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Ba,GACbD,EAACM,cAAcL,OAAGM,EAAW,CAAEC,SAAS,KA8BLV,GAA6B,KAAI"}
@@ -1,11 +0,0 @@
1
- export { default as classify } from './classify.js';
2
- export { default as createHistoryRecord } from './createHistoryRecord.js';
3
- export { default as updateHistoryRecord } from './updateHistoryRecord.js';
4
- export { default as delegateEvent } from './delegateEvent.js';
5
- export { default as getDataFromHtml } from './getDataFromHtml.js';
6
- export { default as fetch } from './fetch.js';
7
- export { default as getCurrentUrl } from './getCurrentUrl.js';
8
- export { default as Location } from './Location.js';
9
- export { default as markSwupElements } from './markSwupElements.js';
10
- export { default as cleanupAnimationClasses } from './cleanupAnimationClasses.js';
11
- export { default as versionSatisfies } from './versionSatisfies.js';