@amedia/user 0.14.13 → 0.14.15

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.
package/dist/user.d.ts CHANGED
@@ -328,6 +328,7 @@ declare module '@amedia/user/eventHandlers/eventMap' {
328
328
  REQUEST_STATE = "amedia-user.request-state",
329
329
  REQUEST_USER_ATTRIBUTES = "amedia-user.request-user-attributes",
330
330
  REQUEST_STORAGE_NAMESPACES = "amedia-user.request-storage-namespaces",
331
+ REQUEST_NAVIGATION = "amedia-user.request-navigation",
331
332
  SAVE_STORAGE = "amedia-user.save-storage-namespaces",
332
333
  UPDATE_STORAGE = "amedia-user.update-storage-namespaces",
333
334
  ON_ATTRIBUTES_UPDATED = "amedia-user.on-user-attributes-updated",
@@ -339,6 +340,11 @@ declare module '@amedia/user/eventHandlers/eventMap' {
339
340
  [AmediaUserEvents.REQUEST_STATE]: CustomEvent;
340
341
  [AmediaUserEvents.REQUEST_USER_ATTRIBUTES]: CustomEvent<Array<keyof UserAttributes>>;
341
342
  [AmediaUserEvents.REQUEST_STORAGE_NAMESPACES]: CustomEvent<Array<string>>;
343
+ [AmediaUserEvents.REQUEST_NAVIGATION]: CustomEvent<{
344
+ type: 'reload' | 'location';
345
+ url?: string;
346
+ replace?: boolean;
347
+ }>;
342
348
  [AmediaUserEvents.SAVE_STORAGE]: CustomEvent<{
343
349
  [namespace: string]: object;
344
350
  }>;
@@ -353,6 +359,18 @@ declare module '@amedia/user/eventHandlers/eventMap' {
353
359
  }
354
360
  }
355
361
 
362
+ }
363
+ declare module '@amedia/user/eventHandlers/navigation' {
364
+ export const internalLocationHref: (url: string) => void;
365
+ export const internalLocationReload: () => void;
366
+ export const internalLocationReplace: (url: string) => void;
367
+ export const hasWindowContext: () => boolean;
368
+ export const listenForNavigationRequests: () => void;
369
+
370
+ }
371
+ declare module '@amedia/user/eventHandlers/navigation.spec' {
372
+ export {};
373
+
356
374
  }
357
375
  declare module '@amedia/user/eventHandlers/state' {
358
376
  export const listenForStateRequests: () => void;
@@ -573,11 +591,12 @@ declare module '@amedia/user/store/index' {
573
591
  [index: string]: unknown;
574
592
  };
575
593
  };
594
+ isPoisoned: boolean;
576
595
  };
577
596
  type Listener<T> = (data: T) => void;
578
597
  const _default: {
579
598
  merge: <K extends keyof StoreDataMap>(key: K, value: Partial<StoreDataMap[K]>) => void;
580
- set: (key: keyof StoreDataMap, value: UserAttributes | State | {
599
+ set: (key: keyof StoreDataMap, value: boolean | UserAttributes | State | {
581
600
  [namespace: string]: {
582
601
  [index: string]: unknown;
583
602
  };
@@ -639,6 +658,10 @@ declare module '@amedia/user/utils/customEventWrapper' {
639
658
  export const dispatch: <T extends Event>(event: T) => void;
640
659
  export {};
641
660
 
661
+ }
662
+ declare module '@amedia/user/utils/customEventWrapper.spec' {
663
+ export {};
664
+
642
665
  }
643
666
  declare module '@amedia/user/utils/debouncer' {
644
667
  /**
@@ -706,9 +729,13 @@ declare module '@amedia/user/utils/localhostCheck' {
706
729
  }
707
730
  declare module '@amedia/user/utils/location' {
708
731
  export const reload: () => void;
709
- export const replace: (requestedUrl: string) => void;
732
+ export const replace: (url: string) => void;
710
733
  export const navigateTo: (url: string) => void;
711
734
 
735
+ }
736
+ declare module '@amedia/user/utils/location.spec' {
737
+ export {};
738
+
712
739
  }
713
740
  declare module '@amedia/user/utils/log' {
714
741
  export type Logger = {
@@ -773,6 +800,6 @@ declare module '@amedia/user/utils/url.spec' {
773
800
 
774
801
  }
775
802
  declare module '@amedia/user' {
776
- import main = require('@amedia/user/src/index');
803
+ import main = require('@amedia/user/src');
777
804
  export = main;
778
805
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amedia/user",
3
- "version": "0.14.13",
3
+ "version": "0.14.15",
4
4
  "description": "Client lib for working with aID user and associated data",
5
5
  "repository": "https://github.com/amedia/amedia-user-js",
6
6
  "author": "Amedia Utvikling (ID og data)",
@@ -44,6 +44,8 @@
44
44
  "@types/dexie": "^1.3.1",
45
45
  "@types/jest": "^26.0.24",
46
46
  "@typescript-eslint/eslint-plugin": "^4.29.1",
47
+ "express": "^4.17.1",
48
+ "cors": "^2.8.5",
47
49
  "esbuild": "^0.12.19",
48
50
  "eslint": "^7.32.0",
49
51
  "eslint-config-airbnb-typescript": "^12.3.1",
@@ -70,7 +70,7 @@ const attemptAutologin = async (strategies: Strategies) => {
70
70
  .then((shouldPerformAutoLogin) => {
71
71
  if (shouldPerformAutoLogin) {
72
72
  if (hasAlreadyAttemptedAutoLogin()) {
73
- return Promise.resolve(false);
73
+ return false;
74
74
  }
75
75
 
76
76
  // Try to get newspaper cookie
@@ -85,19 +85,18 @@ const attemptAutologin = async (strategies: Strategies) => {
85
85
  * and will in turn cause flickering and unnecessary (and often aborted) request to
86
86
  * various backends.
87
87
  */
88
- return new Promise(() => {});
88
+ return new Promise<boolean>(() => {});
89
89
  }
90
- return Promise.resolve(true);
90
+ return true;
91
91
  });
92
92
 
93
- // eslint-disable-next-line no-await-in-loop
94
- if (!(await shouldTryMoreStrategies)) {
93
+ if (!shouldTryMoreStrategies) {
95
94
  return;
96
95
  }
97
96
  }
98
97
  };
99
98
 
100
- export const attemptAutoLoginJob = async () =>
99
+ export const attemptAutoLoginJob = () =>
101
100
  attemptAutologin([
102
101
  {
103
102
  name: 'third_party',
@@ -105,7 +104,7 @@ export const attemptAutoLoginJob = async () =>
105
104
  },
106
105
  ]);
107
106
 
108
- export const attemptPaywallAutoLogin = async () =>
107
+ export const attemptPaywallAutoLogin = () =>
109
108
  attemptAutologin([
110
109
  {
111
110
  name: 'paywall',
@@ -4,6 +4,7 @@ export enum AmediaUserEvents {
4
4
  REQUEST_STATE = 'amedia-user.request-state',
5
5
  REQUEST_USER_ATTRIBUTES = 'amedia-user.request-user-attributes',
6
6
  REQUEST_STORAGE_NAMESPACES = 'amedia-user.request-storage-namespaces',
7
+ REQUEST_NAVIGATION = 'amedia-user.request-navigation',
7
8
  SAVE_STORAGE = 'amedia-user.save-storage-namespaces',
8
9
  UPDATE_STORAGE = 'amedia-user.update-storage-namespaces',
9
10
  ON_ATTRIBUTES_UPDATED = 'amedia-user.on-user-attributes-updated',
@@ -18,6 +19,11 @@ declare global {
18
19
  Array<keyof UserAttributes>
19
20
  >;
20
21
  [AmediaUserEvents.REQUEST_STORAGE_NAMESPACES]: CustomEvent<Array<string>>;
22
+ [AmediaUserEvents.REQUEST_NAVIGATION]: CustomEvent<{
23
+ type: 'reload' | 'location';
24
+ url?: string;
25
+ replace?: boolean;
26
+ }>;
21
27
  [AmediaUserEvents.SAVE_STORAGE]: CustomEvent<{
22
28
  [namespace: string]: object;
23
29
  }>;
@@ -0,0 +1,189 @@
1
+ import store from '../store';
2
+ import log from '../utils/log';
3
+ import * as navigation from './navigation';
4
+ import { dispatch } from '../utils/customEventWrapper';
5
+ import { AmediaUserEvents } from './eventMap';
6
+
7
+ const itShouldSetLocationHrefTo = (url: string) => {
8
+ it('should set location href', () => {
9
+ expect(navigation.internalLocationHref).toHaveBeenCalledWith(url);
10
+ });
11
+ };
12
+ const itShouldNotSetLocationHref = () => {
13
+ it('should not set location href', () => {
14
+ expect(navigation.internalLocationHref).not.toHaveBeenCalled();
15
+ });
16
+ };
17
+
18
+ const itShouldReplaceLocationWith = (url: string) => {
19
+ it('should replace location', () => {
20
+ expect(navigation.internalLocationReplace).toHaveBeenCalledWith(url);
21
+ });
22
+ };
23
+ const itShouldNotReplaceLocation = () => {
24
+ it('should not replace location', () => {
25
+ expect(navigation.internalLocationReplace).not.toHaveBeenCalled();
26
+ });
27
+ };
28
+
29
+ const itShouldReload = () => {
30
+ it('should reload', () => {
31
+ expect(navigation.internalLocationReload).toHaveBeenCalled();
32
+ });
33
+ };
34
+
35
+ const itShouldNotReload = () => {
36
+ it('should not reload', () => {
37
+ expect(navigation.internalLocationReload).not.toHaveBeenCalled();
38
+ });
39
+ };
40
+
41
+ const itShouldPoisonTheWell = () => {
42
+ it('should poison the well', () => {
43
+ expect(store.get('isPoisoned')).toBeTrue();
44
+ });
45
+ };
46
+
47
+ const itShouldNotPoisonTheWell = () => {
48
+ it('should poison the well', () => {
49
+ expect(store.get('isPoisoned')).toBeFalsy();
50
+ });
51
+ };
52
+
53
+ const itShouldLogError = (message: string) => {
54
+ it('should log error', () => {
55
+ expect(log.error).toHaveBeenCalledWith(message);
56
+ });
57
+ };
58
+
59
+ const itShouldNotLogError = () => {
60
+ it('should not log error', () => {
61
+ expect(log.error).not.toHaveBeenCalled();
62
+ });
63
+ };
64
+
65
+ beforeEach(() => {
66
+ store.clear();
67
+
68
+ spyOn(log, 'error').and.stub();
69
+ spyOn(navigation, 'internalLocationHref').and.stub();
70
+ spyOn(navigation, 'internalLocationReload').and.stub();
71
+ spyOn(navigation, 'internalLocationReplace').and.stub();
72
+
73
+ navigation.listenForNavigationRequests();
74
+ });
75
+
76
+ describe('when window is not set', () => {
77
+ beforeEach(() => {
78
+ spyOn(navigation, 'hasWindowContext').and.returnValue(false);
79
+ dispatch(
80
+ new CustomEvent(AmediaUserEvents.REQUEST_NAVIGATION, {
81
+ detail: { type: 'reload' },
82
+ })
83
+ );
84
+ });
85
+
86
+ itShouldLogError(
87
+ 'Navigation attempted context without window. Be careful not to use interactive UX code in workers and other settings.'
88
+ );
89
+
90
+ itShouldNotReload();
91
+ itShouldNotSetLocationHref();
92
+ itShouldNotReplaceLocation();
93
+ itShouldNotPoisonTheWell();
94
+ });
95
+
96
+ describe('when window exists', () => {
97
+ beforeEach(() => {
98
+ spyOn(navigation, 'hasWindowContext').and.returnValue(true);
99
+ });
100
+
101
+ describe('and requesting reload', () => {
102
+ beforeEach(() => {
103
+ dispatch(
104
+ new CustomEvent(AmediaUserEvents.REQUEST_NAVIGATION, {
105
+ detail: { type: 'reload' },
106
+ })
107
+ );
108
+ });
109
+
110
+ itShouldReload();
111
+ itShouldPoisonTheWell();
112
+
113
+ itShouldNotSetLocationHref();
114
+ itShouldNotReplaceLocation();
115
+ itShouldNotLogError();
116
+ });
117
+
118
+ describe('and requesting location change', () => {
119
+ beforeEach(() => {
120
+ dispatch(
121
+ new CustomEvent(AmediaUserEvents.REQUEST_NAVIGATION, {
122
+ detail: { type: 'location', url: 'https://www.telen.no' },
123
+ })
124
+ );
125
+ });
126
+
127
+ itShouldSetLocationHrefTo('https://www.telen.no');
128
+ itShouldPoisonTheWell();
129
+
130
+ itShouldNotReload();
131
+ itShouldNotReplaceLocation();
132
+ itShouldNotLogError();
133
+ });
134
+
135
+ describe('and requesting location change but forgetting to set url', () => {
136
+ beforeEach(() => {
137
+ dispatch(
138
+ new CustomEvent(AmediaUserEvents.REQUEST_NAVIGATION, {
139
+ detail: { type: 'location' },
140
+ })
141
+ );
142
+ });
143
+
144
+ itShouldLogError(`Url required for navigation`);
145
+
146
+ itShouldNotReload();
147
+ itShouldNotSetLocationHref();
148
+ itShouldNotReplaceLocation();
149
+ itShouldNotPoisonTheWell();
150
+ });
151
+
152
+ describe('and requesting location replacing', () => {
153
+ beforeEach(() => {
154
+ dispatch(
155
+ new CustomEvent(AmediaUserEvents.REQUEST_NAVIGATION, {
156
+ detail: {
157
+ type: 'location',
158
+ url: 'https://www.telen.no',
159
+ replace: true,
160
+ },
161
+ })
162
+ );
163
+ });
164
+
165
+ itShouldReplaceLocationWith('https://www.telen.no');
166
+ itShouldPoisonTheWell();
167
+
168
+ itShouldNotReload();
169
+ itShouldNotSetLocationHref();
170
+ itShouldNotLogError();
171
+ });
172
+
173
+ describe('but using invalid action', () => {
174
+ beforeEach(() => {
175
+ dispatch(
176
+ new CustomEvent(AmediaUserEvents.REQUEST_NAVIGATION, {
177
+ detail: { type: 'invalid' },
178
+ })
179
+ );
180
+ });
181
+
182
+ itShouldLogError(`Unknown navigation type (invalid)`);
183
+
184
+ itShouldNotReload();
185
+ itShouldNotSetLocationHref();
186
+ itShouldNotReplaceLocation();
187
+ itShouldNotPoisonTheWell();
188
+ });
189
+ });
@@ -0,0 +1,58 @@
1
+ import { listenWithExclusivity } from '../utils/customEventWrapper';
2
+ import { AmediaUserEvents } from './eventMap';
3
+ import store from '../store';
4
+ import log from '../utils/log';
5
+
6
+ export const internalLocationHref = (url: string) => {
7
+ window.location.href = url;
8
+ };
9
+
10
+ export const internalLocationReload = () => window.location.reload();
11
+ export const internalLocationReplace = (url: string) =>
12
+ window.location.replace(url);
13
+
14
+ export const hasWindowContext = () => typeof window === 'undefined';
15
+
16
+ const handleNavigation = ({
17
+ detail: { type, url, replace },
18
+ }: WindowEventMap[AmediaUserEvents.REQUEST_NAVIGATION]) => {
19
+ switch (type) {
20
+ case 'location':
21
+ if (!url) {
22
+ throw new Error('Url required for navigation');
23
+ }
24
+ if (replace) {
25
+ internalLocationReplace(url);
26
+ } else {
27
+ internalLocationHref(url);
28
+ }
29
+ break;
30
+ case 'reload':
31
+ internalLocationReload();
32
+ break;
33
+ default:
34
+ throw new Error(`Unknown navigation type (${type})`);
35
+ }
36
+ };
37
+
38
+ export const listenForNavigationRequests = () =>
39
+ listenWithExclusivity(AmediaUserEvents.REQUEST_NAVIGATION, (evt) => {
40
+ if (!hasWindowContext()) {
41
+ log.error(
42
+ 'Navigation attempted context without window. Be careful not to use interactive UX code in workers and other settings.'
43
+ );
44
+ return;
45
+ }
46
+
47
+ try {
48
+ handleNavigation(evt);
49
+ /**
50
+ * This will prevent any further event dispatching.
51
+ * Effectively having requesters of data wait "forever" (the few
52
+ * milliseconds) until we navigate away
53
+ */
54
+ store.set('isPoisoned', true);
55
+ } catch (e) {
56
+ log.error(e.message);
57
+ }
58
+ });
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@ import { listenForStateRequests } from './eventHandlers/state';
7
7
  import { listenForUserAttributeRequests } from './eventHandlers/userAttributes';
8
8
  import { listenForStorageRequests } from './eventHandlers/storage';
9
9
  import getGlobalThis from './utils/getGlobalThis';
10
+ import { listenForNavigationRequests } from './eventHandlers/navigation';
10
11
 
11
12
  export { default as UserDataRequest } from './lib/UserDataRequest';
12
13
  export { default as PaywallUnlockRequest } from './lib/PaywallUnlockRequest';
@@ -37,6 +38,7 @@ export const saveStorage = (storage: { [index: string]: Object }) => {
37
38
  };
38
39
 
39
40
  if (!getGlobalThis().amediaUserTestMode) {
41
+ listenForNavigationRequests();
40
42
  listenForStateRequests();
41
43
  listenForUserAttributeRequests();
42
44
  listenForStorageRequests();
@@ -44,7 +44,7 @@ declare global {
44
44
  }
45
45
 
46
46
  // We want to ensure that the Janitor is started exactly once. The trick here is to
47
- // listen to an event end if we receive it exclusively, we know that we are the first
47
+ // listen to an event and if we receive it exclusively, we know that we are the first
48
48
  // to load this script and therefore responsible for running the Janitor once.
49
49
  export const runJanitor = async () => {
50
50
  let janitorStarted = false;
@@ -218,9 +218,12 @@ describe('PaywallUnlocker', () => {
218
218
 
219
219
  describe('with redirect requested', () => {
220
220
  beforeEach(async () => {
221
- unlockResponse = await new PaywallUnlockRequest()
221
+ new PaywallUnlockRequest()
222
222
  .redirectOnAccess('https://redirect.pls')
223
- .tryUnlock();
223
+ .tryUnlock()
224
+ .then((res) => {
225
+ unlockResponse = res;
226
+ });
224
227
  });
225
228
 
226
229
  it('should give access with access features', () => {
@@ -231,10 +234,19 @@ describe('PaywallUnlocker', () => {
231
234
  });
232
235
  });
233
236
 
234
- it('should navigate to expected url', () => {
235
- expect(location.replace).toHaveBeenCalledWith(
236
- 'https://redirect.pls'
237
- );
237
+ it('should navigate to expected url', (done) => {
238
+ /**
239
+ * This is not great.
240
+ * Since tryUnlock performs some async actions and we, by design,
241
+ * don't want to resolve tryUnlock when navigating, we have to
242
+ * wait for the next event loop to check location.
243
+ */
244
+ setTimeout(() => {
245
+ expect(location.replace).toHaveBeenCalledWith(
246
+ 'https://redirect.pls'
247
+ );
248
+ done();
249
+ }, 0);
238
250
  });
239
251
 
240
252
  itShouldAttemptActivationWithAccessFeatures(['newspaper']);
@@ -243,9 +255,12 @@ describe('PaywallUnlocker', () => {
243
255
 
244
256
  describe('with reload requested', () => {
245
257
  beforeEach(async () => {
246
- unlockResponse = await new PaywallUnlockRequest()
258
+ new PaywallUnlockRequest()
247
259
  .reloadOnAccess()
248
- .tryUnlock();
260
+ .tryUnlock()
261
+ .then((res) => {
262
+ unlockResponse = res;
263
+ });
249
264
  });
250
265
 
251
266
  it('should give access with access features', () => {
@@ -256,8 +271,11 @@ describe('PaywallUnlocker', () => {
256
271
  });
257
272
  });
258
273
 
259
- it('should reload on access', () => {
260
- expect(location.reload).toHaveBeenCalled();
274
+ it('should reload on access', (done) => {
275
+ setTimeout(() => {
276
+ expect(location.reload).toHaveBeenCalled();
277
+ done();
278
+ }, 0);
261
279
  });
262
280
 
263
281
  itShouldAttemptActivationWithAccessFeatures(['newspaper']);
@@ -6,12 +6,12 @@ import {
6
6
  setHasPerformedPaywallReload,
7
7
  } from '../actions/authorization';
8
8
  import { getCurrentSiteDomain } from '../utils/url';
9
- import * as location from '../utils/location';
10
9
  import PaywallError from '../exceptions/PaywallError';
11
10
  import UserDataRequest from './UserDataRequest';
12
11
  import { attemptPaywallAutoLogin } from '../autologin';
13
12
  import { AccessFeatures, getSitesWithAccessFeatures } from '../clients/jupiter';
14
13
  import { isRunningOnLocalhost } from '../utils/localhostCheck';
14
+ import { reload, replace } from '../utils/location';
15
15
 
16
16
  export enum AffiliationType {
17
17
  ACCESS = 'access',
@@ -26,7 +26,7 @@ export type UnlockResponse = {
26
26
 
27
27
  async function getPrimarySite(accessFeatures: string[]) {
28
28
  // This is where we should have called aid-subscription to get the user's subscriptions, but until
29
- // this is ready, we only get sites the user has acces to, and choose one of those.
29
+ // this is ready, we only get sites the user has access to, and choose one of those.
30
30
  const sites = await getSitesWithAccessFeatures({
31
31
  accessFeatures,
32
32
  excludeBundles: true,
@@ -128,12 +128,15 @@ class PaywallUnlockRequest {
128
128
 
129
129
  setHasPerformedPaywallReload(this.requestedUrl);
130
130
  if (this.reload) {
131
- location.reload();
131
+ reload();
132
132
  }
133
133
 
134
134
  if (this.requestedUrl) {
135
- location.replace(this.requestedUrl);
135
+ replace(this.requestedUrl);
136
136
  }
137
+
138
+ // Don't resolve tryUnlock promise if we're being reloaded/navigated away
139
+ return new Promise(() => {});
137
140
  }
138
141
  return {
139
142
  isLoggedIn: true,
@@ -5,6 +5,7 @@ type StoreDataMap = {
5
5
  userAttributes: UserAttributes;
6
6
  state: State;
7
7
  storage: { [namespace: string]: { [index: string]: unknown } };
8
+ isPoisoned: boolean;
8
9
  };
9
10
 
10
11
  type Listener<T> = (data: T) => void;
@@ -12,7 +13,7 @@ type Listeners<T = StoreDataMap> = {
12
13
  [key in keyof T]?: Array<Listener<T[key]>>;
13
14
  };
14
15
 
15
- const store: { [index in keyof StoreDataMap]?: StoreDataMap[index] } = {};
16
+ const store: Partial<StoreDataMap> = {};
16
17
  const listeners: Listeners = {};
17
18
 
18
19
  const emit = (key: keyof StoreDataMap): void => {
@@ -55,6 +56,7 @@ const clear = () => {
55
56
  store.state = undefined;
56
57
  store.userAttributes = undefined;
57
58
  store.storage = undefined;
59
+ store.isPoisoned = undefined;
58
60
  Object.keys(listeners).forEach((key) => {
59
61
  // @ts-ignore
60
62
  listeners[key] = [];
@@ -0,0 +1,237 @@
1
+ import store from '../store';
2
+ import {
3
+ dispatch,
4
+ listenForAllEvents,
5
+ listenWithExclusivity,
6
+ setRootElement,
7
+ } from './customEventWrapper';
8
+ import log from './log';
9
+ import { AmediaUserEvents } from '../eventHandlers/eventMap';
10
+
11
+ const itShouldNotLogError = () => {
12
+ it('should not log error', () => {
13
+ expect(log.error).not.toHaveBeenCalled();
14
+ });
15
+ };
16
+
17
+ let rootElement: Element;
18
+ beforeEach(() => {
19
+ spyOn(log, 'error').and.stub();
20
+
21
+ store.clear();
22
+
23
+ /**
24
+ * This is already set in test bootstrapping, but we need access to the
25
+ * rootElement for some tests. Cleanest to override root element a second time
26
+ */
27
+ rootElement = new Document().createElement('div');
28
+ spyOn(rootElement, 'dispatchEvent').and.callThrough();
29
+ setRootElement(rootElement);
30
+ });
31
+
32
+ describe('when calling listenWithExclusivity', () => {
33
+ describe('and we are missing root element', () => {
34
+ beforeEach(() => {
35
+ // @ts-ignore
36
+ setRootElement(null);
37
+ listenWithExclusivity(AmediaUserEvents.REQUEST_NAVIGATION, () => {});
38
+ });
39
+
40
+ it('should log error', () => {
41
+ expect(log.error).toHaveBeenCalledWith(
42
+ 'No root element to bind event to!'
43
+ );
44
+ });
45
+ });
46
+
47
+ describe('and we are poisoned', () => {
48
+ let listener: jest.Mock;
49
+ beforeEach(() => {
50
+ listener = jest.fn();
51
+ listenWithExclusivity(AmediaUserEvents.REQUEST_NAVIGATION, listener);
52
+ store.set('isPoisoned', true);
53
+ rootElement.dispatchEvent(
54
+ new CustomEvent(AmediaUserEvents.REQUEST_NAVIGATION, {
55
+ detail: { type: 'reload' },
56
+ })
57
+ );
58
+ });
59
+
60
+ it('should not call listener', () => {
61
+ expect(listener).not.toHaveBeenCalled();
62
+ });
63
+
64
+ itShouldNotLogError();
65
+ });
66
+
67
+ describe('and a single listener have been added', () => {
68
+ let listener: jest.Mock;
69
+ let event: CustomEvent;
70
+ beforeEach(() => {
71
+ listener = jest.fn();
72
+ event = new CustomEvent(AmediaUserEvents.REQUEST_NAVIGATION);
73
+ listenWithExclusivity(AmediaUserEvents.REQUEST_NAVIGATION, listener);
74
+ dispatch(event);
75
+ });
76
+
77
+ it('should call the first listener', () => {
78
+ expect(listener).toHaveBeenCalledWith(event);
79
+ });
80
+
81
+ itShouldNotLogError();
82
+ });
83
+
84
+ describe('and multiple listeners have been added', () => {
85
+ let first: jest.Mock;
86
+ let second: jest.Mock;
87
+ let event: CustomEvent;
88
+ beforeEach(() => {
89
+ first = jest.fn();
90
+ second = jest.fn();
91
+ event = new CustomEvent(AmediaUserEvents.REQUEST_NAVIGATION);
92
+ listenWithExclusivity(AmediaUserEvents.REQUEST_NAVIGATION, first);
93
+ listenWithExclusivity(AmediaUserEvents.REQUEST_NAVIGATION, second);
94
+ rootElement.dispatchEvent(event);
95
+ });
96
+
97
+ it('should call the first listener', () => {
98
+ expect(first).toHaveBeenCalledWith(event);
99
+ });
100
+
101
+ it('should not call the second listener', () => {
102
+ expect(second).not.toHaveBeenCalled();
103
+ });
104
+
105
+ itShouldNotLogError();
106
+ });
107
+ });
108
+
109
+ describe('when calling listenForAllEvents', () => {
110
+ describe('and we are missing root element', () => {
111
+ beforeEach(() => {
112
+ // @ts-ignore
113
+ setRootElement(null);
114
+ listenForAllEvents(AmediaUserEvents.REQUEST_NAVIGATION, () => {});
115
+ });
116
+
117
+ it('should log error', () => {
118
+ expect(log.error).toHaveBeenCalledWith(
119
+ 'No root element to bind event to!'
120
+ );
121
+ });
122
+ });
123
+
124
+ describe('and we are poisoned', () => {
125
+ let listener: jest.Mock;
126
+ let event: CustomEvent;
127
+ beforeEach(() => {
128
+ listener = jest.fn();
129
+ event = new CustomEvent(AmediaUserEvents.REQUEST_NAVIGATION, {
130
+ detail: { type: 'reload' },
131
+ });
132
+ listenForAllEvents(AmediaUserEvents.REQUEST_NAVIGATION, listener);
133
+ store.set('isPoisoned', true);
134
+ rootElement.dispatchEvent(event);
135
+ });
136
+
137
+ it('should ignore any poison and call listener', () => {
138
+ /**
139
+ * The reason we ignore poison here is that we almost certanly
140
+ * won't have the store to identify it anyway
141
+ */
142
+ expect(listener).toHaveBeenCalledWith(event);
143
+ });
144
+
145
+ itShouldNotLogError();
146
+ });
147
+
148
+ describe('and a single listener have been added', () => {
149
+ let listener: jest.Mock;
150
+ let event: CustomEvent;
151
+ beforeEach(() => {
152
+ listener = jest.fn();
153
+ event = new CustomEvent(AmediaUserEvents.REQUEST_NAVIGATION);
154
+ listenForAllEvents(AmediaUserEvents.REQUEST_NAVIGATION, listener);
155
+ dispatch(event);
156
+ });
157
+
158
+ it('should call the first listener', () => {
159
+ expect(listener).toHaveBeenCalledWith(event);
160
+ });
161
+
162
+ itShouldNotLogError();
163
+ });
164
+
165
+ describe('and multiple listeners have been added', () => {
166
+ let first: jest.Mock;
167
+ let second: jest.Mock;
168
+ let event: CustomEvent;
169
+ beforeEach(() => {
170
+ first = jest.fn();
171
+ second = jest.fn();
172
+ event = new CustomEvent(AmediaUserEvents.REQUEST_NAVIGATION);
173
+ listenForAllEvents(AmediaUserEvents.REQUEST_NAVIGATION, first);
174
+ listenForAllEvents(AmediaUserEvents.REQUEST_NAVIGATION, second);
175
+ rootElement.dispatchEvent(event);
176
+ });
177
+
178
+ it('should call the first listener', () => {
179
+ expect(first).toHaveBeenCalledWith(event);
180
+ });
181
+
182
+ it('should call the second listener', () => {
183
+ expect(second).toHaveBeenCalledWith(event);
184
+ });
185
+
186
+ itShouldNotLogError();
187
+ });
188
+ });
189
+
190
+ describe('when calling dispatch', () => {
191
+ describe('and we are missing root element', () => {
192
+ beforeEach(() => {
193
+ // @ts-ignore
194
+ setRootElement(null);
195
+ dispatch(
196
+ new CustomEvent(AmediaUserEvents.REQUEST_NAVIGATION, {
197
+ detail: { reload: true },
198
+ })
199
+ );
200
+ });
201
+
202
+ it('should log error', () => {
203
+ expect(log.error).toHaveBeenCalledWith(
204
+ 'No root element to dispatch event on!'
205
+ );
206
+ });
207
+ });
208
+
209
+ describe('and we are poisoned', () => {
210
+ beforeEach(() => {
211
+ store.set('isPoisoned', true);
212
+ dispatch(
213
+ new CustomEvent(AmediaUserEvents.REQUEST_NAVIGATION, {
214
+ detail: { reload: true },
215
+ })
216
+ );
217
+ });
218
+
219
+ it('should not dispatch event', () => {
220
+ expect(rootElement.dispatchEvent).not.toHaveBeenCalled();
221
+ });
222
+ });
223
+
224
+ describe('and all requirements are met', () => {
225
+ let event: CustomEvent;
226
+ beforeEach(() => {
227
+ event = new CustomEvent(AmediaUserEvents.REQUEST_NAVIGATION, {
228
+ detail: { reload: true },
229
+ });
230
+ dispatch(event);
231
+ });
232
+
233
+ it('should dispatch event', () => {
234
+ expect(rootElement.dispatchEvent).toHaveBeenCalledWith(event);
235
+ });
236
+ });
237
+ });
@@ -1,5 +1,6 @@
1
1
  import log from './log';
2
2
  import getGlobalThis from './getGlobalThis';
3
+ import store from '../store';
3
4
 
4
5
  let rootElement: Window | Element | typeof globalThis;
5
6
 
@@ -27,6 +28,15 @@ export const listenWithExclusivity = <T extends keyof WindowEventMap>(
27
28
  rootElement.addEventListener(type, (evt) => {
28
29
  // Since this lib might me loaded multiple times, we need to prevent all other processing of this event.
29
30
  evt.stopImmediatePropagation();
31
+
32
+ /**
33
+ * This will prevent any listeners from being called if we're poisoned,
34
+ * thus preventing any external calls from being started when we're
35
+ * being navigated away
36
+ */
37
+ if (store.get('isPoisoned')) {
38
+ return;
39
+ }
30
40
  listener.apply(rootElement, [evt as WindowEventMap[T]]);
31
41
  });
32
42
  };
@@ -55,5 +65,13 @@ export const dispatch = <T extends Event>(event: T) => {
55
65
  log.error('No root element to dispatch event on!');
56
66
  return;
57
67
  }
68
+ /**
69
+ * This will prevent any further event dispatching.
70
+ * Effectively having requesters of data wait "forever" (the few
71
+ * milliseconds) until we navigate away
72
+ */
73
+ if (store.get('isPoisoned')) {
74
+ return;
75
+ }
58
76
  rootElement.dispatchEvent(event);
59
77
  };
@@ -0,0 +1,61 @@
1
+ import { listenWithExclusivity } from './customEventWrapper';
2
+ import { AmediaUserEvents } from '../eventHandlers/eventMap';
3
+ import { navigateTo, reload, replace } from './location';
4
+
5
+ let handler: jest.Mock;
6
+ beforeEach(() => {
7
+ handler = jest.fn();
8
+ listenWithExclusivity(AmediaUserEvents.REQUEST_NAVIGATION, handler);
9
+ });
10
+
11
+ describe('reload', () => {
12
+ beforeEach(() => {
13
+ reload();
14
+ });
15
+
16
+ it('should execute reload handler', () => {
17
+ expect(handler).toHaveBeenCalledWith(
18
+ jasmine.objectContaining({
19
+ detail: {
20
+ type: 'reload',
21
+ },
22
+ })
23
+ );
24
+ });
25
+ });
26
+
27
+ describe('navigateTo', () => {
28
+ beforeEach(() => {
29
+ navigateTo('https://www.telen.no');
30
+ });
31
+
32
+ it('should execute reload handler', () => {
33
+ expect(handler).toHaveBeenCalledWith(
34
+ jasmine.objectContaining({
35
+ detail: {
36
+ type: 'location',
37
+ url: 'https://www.telen.no',
38
+ replace: false,
39
+ },
40
+ })
41
+ );
42
+ });
43
+ });
44
+
45
+ describe('replace', () => {
46
+ beforeEach(() => {
47
+ replace('https://www.telen.no');
48
+ });
49
+
50
+ it('should execute reload handler', () => {
51
+ expect(handler).toHaveBeenCalledWith(
52
+ jasmine.objectContaining({
53
+ detail: {
54
+ type: 'location',
55
+ url: 'https://www.telen.no',
56
+ replace: true,
57
+ },
58
+ })
59
+ );
60
+ });
61
+ });
@@ -1,31 +1,16 @@
1
- import log from './log';
1
+ import { dispatch } from './customEventWrapper';
2
+ import { AmediaUserEvents } from '../eventHandlers/eventMap';
2
3
 
3
- export const reload = () => {
4
- if (typeof window === 'undefined') {
5
- log.error(
6
- 'location.reload used in a context without window. Be careful not to use paywall logic etc. in workers and other settings.'
7
- );
8
- return;
9
- }
10
- window.location.reload();
4
+ const requestNavigation = (type: string, url?: string, replace?: boolean) => {
5
+ dispatch(
6
+ new CustomEvent(AmediaUserEvents.REQUEST_NAVIGATION, {
7
+ detail: { type, url, replace },
8
+ })
9
+ );
11
10
  };
12
11
 
13
- export const replace = (requestedUrl: string) => {
14
- if (typeof window === 'undefined') {
15
- log.error(
16
- 'location.replace used in a context without window. Be careful not to use paywall logic etc. in workers and other settings.'
17
- );
18
- return;
19
- }
20
- window.location.replace(requestedUrl);
21
- };
22
-
23
- export const navigateTo = (url: string) => {
24
- if (typeof window === 'undefined') {
25
- log.error(
26
- 'location.navigateTo used in a context without window. Be careful not to use interactive UX code in workers and other settings.'
27
- );
28
- return;
29
- }
30
- window.location.href = url;
31
- };
12
+ export const reload = () => requestNavigation('reload');
13
+ export const replace = (url: string) =>
14
+ requestNavigation('location', url, true);
15
+ export const navigateTo = (url: string) =>
16
+ requestNavigation('location', url, false);