@amedia/user 0.12.17 → 0.12.19

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 (56) hide show
  1. package/dist/actions/authentication.d.ts +0 -1
  2. package/dist/actions/authorization.d.ts +8 -3
  3. package/dist/clients/jupiter.d.ts +1 -1
  4. package/dist/eventHandlers/eventMap.d.ts +25 -0
  5. package/dist/eventHandlers/state.d.ts +1 -0
  6. package/dist/eventHandlers/state.spec.d.ts +4 -0
  7. package/dist/eventHandlers/storage.d.ts +1 -0
  8. package/dist/eventHandlers/storage.spec.d.ts +4 -0
  9. package/dist/eventHandlers/userAttributes.d.ts +0 -23
  10. package/dist/exceptions/PaywallError.d.ts +1 -0
  11. package/dist/index.d.ts +4 -4
  12. package/dist/index.js +1 -2
  13. package/dist/lib/PaywallUnlockRequest.d.ts +16 -0
  14. package/dist/lib/PaywallUnlockRequest.spec.d.ts +4 -0
  15. package/dist/lib/UserDataRequest.d.ts +22 -0
  16. package/dist/lib/UserDataRequest.spec.d.ts +4 -0
  17. package/dist/store/index.d.ts +1 -1
  18. package/dist/utils/log.d.ts +4 -16
  19. package/package.json +1 -1
  20. package/setupJest.js +3 -0
  21. package/src/actions/authentication.ts +0 -3
  22. package/src/actions/authorization.ts +17 -9
  23. package/src/actions/userData.spec.ts +0 -31
  24. package/src/actions/userData.ts +1 -1
  25. package/src/clients/europa.spec.ts +2 -0
  26. package/src/clients/jupiter.spec.ts +6 -32
  27. package/src/clients/jupiter.ts +29 -30
  28. package/src/clients/mercury.spec.ts +2 -0
  29. package/src/clients/nebula.spec.ts +2 -0
  30. package/src/clients/pluto.spec.ts +18 -44
  31. package/src/clients/pluto.ts +4 -14
  32. package/src/eventHandlers/eventMap.ts +29 -0
  33. package/src/eventHandlers/state.spec.ts +59 -0
  34. package/src/eventHandlers/state.ts +23 -0
  35. package/src/eventHandlers/storage.spec.ts +106 -0
  36. package/src/eventHandlers/storage.ts +35 -0
  37. package/src/eventHandlers/userAttributes.spec.ts +5 -103
  38. package/src/eventHandlers/userAttributes.ts +1 -66
  39. package/src/exceptions/PaywallError.ts +3 -0
  40. package/src/index-storage.spec.ts +5 -5
  41. package/src/index-subscription.spec.ts +21 -11
  42. package/src/index.ts +5 -6
  43. package/src/janitor/jobs/accessCookieRefresher.spec.ts +27 -19
  44. package/src/janitor/jobs/accessCookieRefresher.ts +2 -2
  45. package/src/janitor/jobs/removeUserStorage.spec.ts +4 -1
  46. package/src/janitor/jobs/removeUserStorage.ts +3 -2
  47. package/src/lib/PaywallUnlockRequest.spec.ts +343 -0
  48. package/src/lib/PaywallUnlockRequest.ts +121 -0
  49. package/src/lib/UserDataRequest.spec.ts +58 -0
  50. package/src/lib/{User.ts → UserDataRequest.ts} +45 -11
  51. package/src/store/index.ts +1 -1
  52. package/src/utils/log.ts +12 -16
  53. package/src/utils/logValidationError.ts +6 -6
  54. package/amedia-user-js.iml +0 -9
  55. package/src/lib/PaywallUnlocker.spec.ts +0 -196
  56. package/src/lib/PaywallUnlocker.ts +0 -113
@@ -0,0 +1,343 @@
1
+ /**
2
+ * @jest-environment jsdom
3
+ */
4
+
5
+ import fetch from 'jest-fetch-mock';
6
+ import PaywallUnlockRequest from './PaywallUnlockRequest';
7
+ import * as authorization from '../actions/authorization';
8
+ import * as location from '../utils/location';
9
+ import * as autologin from '../autologin';
10
+ import store from '../store';
11
+ import PaywallError from '../exceptions/PaywallError';
12
+ import { setRootElement } from '../utils/customEventWrapper';
13
+ import { listenForUserAttributeRequests } from '../eventHandlers/userAttributes';
14
+ import { listenForStateRequests } from '../eventHandlers/state';
15
+ import restoreAllMocks = jest.restoreAllMocks;
16
+ import spyOn = jest.spyOn;
17
+
18
+ beforeEach(() => {
19
+ restoreAllMocks();
20
+ fetch.resetMocks();
21
+ store.clear();
22
+
23
+ // We cannot use window as our event root during testing
24
+ // since tests are executed in parallel.
25
+ setRootElement(new Document());
26
+
27
+ // Also, since we keep creating new root elements, we also
28
+ // need to attach to these new roots.
29
+ listenForStateRequests();
30
+ listenForUserAttributeRequests();
31
+ });
32
+
33
+ function itShouldNotReload() {
34
+ it('should not reload', () => {
35
+ expect(location.reload).not.toHaveBeenCalled();
36
+ });
37
+ }
38
+
39
+ function itShouldNotRedirect() {
40
+ it('should not redirect', () => {
41
+ expect(location.replace).not.toHaveBeenCalled();
42
+ });
43
+ }
44
+
45
+ function itShouldNotAttemptActivation() {
46
+ it('should not attempt activation', () => {
47
+ expect(authorization.activate).not.toHaveBeenCalled();
48
+ });
49
+ }
50
+
51
+ function itShouldAttemptActivationWithAccessFeatures(accessFeatures: string[]) {
52
+ it('should attempt activation with access features', () => {
53
+ expect(authorization.activate).toHaveBeenCalledWith(accessFeatures);
54
+ });
55
+ }
56
+
57
+ describe('PaywallUnlocker', () => {
58
+ beforeEach(() => {
59
+ spyOn(autologin, 'attemptAutologin').mockResolvedValue();
60
+ spyOn(authorization, 'setHasTriedToUnlockPaywall');
61
+ spyOn(authorization, 'activate');
62
+ spyOn(location, 'reload').mockReturnValue();
63
+ spyOn(location, 'replace').mockReturnValue();
64
+ });
65
+
66
+ describe('When already tried to unlock', () => {
67
+ beforeEach(() => {
68
+ spyOn(authorization, 'hasRecentlyTriedToUnlockPaywall').mockReturnValue(
69
+ true
70
+ );
71
+ });
72
+ it('should throw exception', () => {
73
+ expect(new PaywallUnlockRequest().tryUnlock()).rejects.toThrow(
74
+ new PaywallError(
75
+ 'Unlock check already performed.',
76
+ PaywallError.ERROR_RELOADED_NO_ACCESS
77
+ )
78
+ );
79
+ });
80
+ });
81
+
82
+ describe('When not logged in', () => {
83
+ let unlockResponse;
84
+ beforeEach(async () => {
85
+ store.set('state', { isLoggedIn: false });
86
+ unlockResponse = await new PaywallUnlockRequest().tryUnlock();
87
+ });
88
+
89
+ it('should attempt autologin', async () => {
90
+ expect(autologin.attemptAutologin).toHaveBeenCalledTimes(1);
91
+ });
92
+
93
+ it('should return no access', () => {
94
+ expect(unlockResponse).toEqual({
95
+ isLoggedIn: false,
96
+ hasAccess: false,
97
+ accessFeatures: [],
98
+ });
99
+ });
100
+
101
+ itShouldNotRedirect();
102
+ itShouldNotReload();
103
+ });
104
+
105
+ describe('When loggen in', () => {
106
+ beforeEach(() => {
107
+ store.set('state', { isLoggedIn: true });
108
+ });
109
+
110
+ it('should not attempt autologin', () => {
111
+ expect(autologin.attemptAutologin).not.toHaveBeenCalled();
112
+ });
113
+
114
+ itShouldNotRedirect();
115
+ itShouldNotReload();
116
+
117
+ describe('when has access', () => {
118
+ let unlockResponse;
119
+ beforeEach(async () => {
120
+ store.merge('userAttributes', { access: ['newspaper'] });
121
+ spyOn(authorization, 'setAccessCookies').mockResolvedValue({
122
+ success: true,
123
+ accessFeatures: ['newspaper'],
124
+ });
125
+
126
+ unlockResponse = await new PaywallUnlockRequest().tryUnlock();
127
+ });
128
+
129
+ it('should store that we tried', () => {
130
+ expect(authorization.setHasTriedToUnlockPaywall).toHaveBeenCalled();
131
+ });
132
+
133
+ it('should give access with access features', () => {
134
+ expect(unlockResponse).toEqual({
135
+ isLoggedIn: true,
136
+ hasAccess: true,
137
+ accessFeatures: ['newspaper'],
138
+ });
139
+ });
140
+
141
+ itShouldNotAttemptActivation();
142
+ itShouldNotRedirect();
143
+ itShouldNotReload();
144
+ });
145
+
146
+ describe('when no access', () => {
147
+ describe('and activation give access', () => {
148
+ let unlockResponse;
149
+ beforeEach(() => {
150
+ spyOn(authorization, 'setAccessCookies')
151
+ .mockResolvedValueOnce({
152
+ success: true,
153
+ accessFeatures: [],
154
+ })
155
+ .mockResolvedValueOnce({
156
+ success: true,
157
+ accessFeatures: ['newspaper'],
158
+ });
159
+ spyOn(authorization, 'activate').mockResolvedValue(true);
160
+ });
161
+
162
+ describe('with no post access actions', () => {
163
+ beforeEach(async () => {
164
+ unlockResponse = await new PaywallUnlockRequest().tryUnlock();
165
+ });
166
+
167
+ it('should give access with access features', () => {
168
+ expect(unlockResponse).toEqual({
169
+ isLoggedIn: true,
170
+ hasAccess: true,
171
+ accessFeatures: ['newspaper'],
172
+ });
173
+ });
174
+
175
+ itShouldAttemptActivationWithAccessFeatures(['newspaper']);
176
+ itShouldNotRedirect();
177
+ itShouldNotReload();
178
+ });
179
+
180
+ describe('with redirect requested', () => {
181
+ beforeEach(async () => {
182
+ unlockResponse = await new PaywallUnlockRequest()
183
+ .redirectOnAccess('https://redirect.pls')
184
+ .tryUnlock();
185
+ });
186
+
187
+ it('should give access with access features', () => {
188
+ expect(unlockResponse).toEqual({
189
+ isLoggedIn: true,
190
+ hasAccess: true,
191
+ accessFeatures: ['newspaper'],
192
+ });
193
+ });
194
+
195
+ it('should navigate to expected url', () => {
196
+ expect(location.replace).toHaveBeenCalledWith(
197
+ 'https://redirect.pls'
198
+ );
199
+ });
200
+
201
+ itShouldAttemptActivationWithAccessFeatures(['newspaper']);
202
+ itShouldNotReload();
203
+ });
204
+
205
+ describe('with reload requested', () => {
206
+ beforeEach(async () => {
207
+ unlockResponse = await new PaywallUnlockRequest()
208
+ .reloadOnAccess()
209
+ .tryUnlock();
210
+ });
211
+
212
+ it('should give access with access features', () => {
213
+ expect(unlockResponse).toEqual({
214
+ isLoggedIn: true,
215
+ hasAccess: true,
216
+ accessFeatures: ['newspaper'],
217
+ });
218
+ });
219
+
220
+ it('should reload on access', () => {
221
+ expect(location.reload).toHaveBeenCalled();
222
+ });
223
+
224
+ itShouldAttemptActivationWithAccessFeatures(['newspaper']);
225
+ itShouldNotRedirect();
226
+ });
227
+ });
228
+
229
+ describe('and activation does not give access', () => {
230
+ let unlockResponse;
231
+ beforeEach(async () => {
232
+ spyOn(authorization, 'setAccessCookies').mockResolvedValueOnce({
233
+ success: true,
234
+ accessFeatures: [],
235
+ });
236
+ spyOn(authorization, 'activate').mockResolvedValue(false);
237
+ unlockResponse = await new PaywallUnlockRequest().tryUnlock();
238
+ });
239
+
240
+ it('should not give access', () => {
241
+ expect(unlockResponse).toEqual({
242
+ isLoggedIn: true,
243
+ hasAccess: false,
244
+ accessFeatures: [],
245
+ });
246
+ });
247
+
248
+ itShouldAttemptActivationWithAccessFeatures(['newspaper']);
249
+ itShouldNotRedirect();
250
+ itShouldNotReload();
251
+ });
252
+
253
+ describe("and activation don't give enough access", () => {
254
+ let unlockResponse;
255
+ beforeEach(async () => {
256
+ spyOn(authorization, 'setAccessCookies').mockResolvedValueOnce({
257
+ success: true,
258
+ accessFeatures: ['newspaper'],
259
+ });
260
+ spyOn(authorization, 'activate').mockResolvedValue(false);
261
+ unlockResponse = await new PaywallUnlockRequest()
262
+ .withAccessFeatures(['plussalt'])
263
+ .tryUnlock();
264
+ });
265
+
266
+ it('should not give access, but return users access features', () => {
267
+ expect(unlockResponse).toEqual({
268
+ isLoggedIn: true,
269
+ hasAccess: false,
270
+ accessFeatures: ['newspaper'],
271
+ });
272
+ });
273
+
274
+ itShouldAttemptActivationWithAccessFeatures(['plussalt']);
275
+ itShouldNotRedirect();
276
+ itShouldNotReload();
277
+ });
278
+ });
279
+
280
+ describe('when setting access cookies fails', () => {
281
+ let paywallError;
282
+ beforeEach(async () => {
283
+ spyOn(authorization, 'setAccessCookies').mockResolvedValue({
284
+ success: false,
285
+ accessFeatures: [],
286
+ });
287
+ try {
288
+ await new PaywallUnlockRequest().tryUnlock();
289
+ } catch (error) {
290
+ paywallError = error;
291
+ }
292
+ });
293
+
294
+ it('should throw error', () => {
295
+ expect(paywallError).toEqual(
296
+ new PaywallError(
297
+ 'Could not set access cookies',
298
+ PaywallError.ERROR_ENABLING_ACCESS_FAILED
299
+ )
300
+ );
301
+ });
302
+
303
+ itShouldNotAttemptActivation();
304
+ itShouldNotRedirect();
305
+ itShouldNotReload();
306
+ });
307
+
308
+ describe('when internal system disagree about users access', () => {
309
+ let paywallError;
310
+ beforeEach(async () => {
311
+ spyOn(authorization, 'setAccessCookies')
312
+ .mockResolvedValueOnce({
313
+ success: true,
314
+ accessFeatures: ['newspaper'],
315
+ })
316
+ .mockResolvedValueOnce({
317
+ success: true,
318
+ accessFeatures: ['newspaper'], // Notice not changed
319
+ });
320
+ spyOn(authorization, 'activate').mockResolvedValue(true);
321
+ try {
322
+ await new PaywallUnlockRequest()
323
+ .withAccessFeatures(['plussalt'])
324
+ .tryUnlock();
325
+ } catch (error) {
326
+ paywallError = error;
327
+ }
328
+ });
329
+
330
+ it('should throw error about bad access state', () => {
331
+ expect(paywallError).toEqual(
332
+ new PaywallError(
333
+ 'New subscription was attached and checked successfully, but internal systems disagree about current newspaper access.',
334
+ PaywallError.ERROR_NO_ACCESS_AFTER_SUCCESSFUL_ACTIVATION_WITH_REQUESTED_ACCESS_FEATURES
335
+ )
336
+ );
337
+ });
338
+
339
+ itShouldNotReload();
340
+ itShouldNotRedirect();
341
+ });
342
+ });
343
+ });
@@ -0,0 +1,121 @@
1
+ import {
2
+ activate,
3
+ hasAccess,
4
+ hasRecentlyTriedToUnlockPaywall,
5
+ setAccessCookies,
6
+ setHasTriedToUnlockPaywall,
7
+ } from '../actions/authorization';
8
+ import { getCurrentPublicationDomain } from '../utils/url';
9
+ import * as location from '../utils/location';
10
+ import PaywallError from '../exceptions/PaywallError';
11
+ import UserDataRequest from './UserDataRequest';
12
+ import { attemptAutologin } from '../autologin';
13
+
14
+ type UnlockResponse = {
15
+ isLoggedIn: boolean;
16
+ hasAccess: boolean;
17
+ accessFeatures: string[];
18
+ };
19
+
20
+ class PaywallUnlockRequest {
21
+ private requestedAccessFeatures: string[] = ['newspaper'];
22
+
23
+ private reload: boolean = false;
24
+
25
+ private requestedUrl: string | undefined;
26
+
27
+ public withAccessFeatures(accessFeatures: string[]): this {
28
+ this.requestedAccessFeatures = accessFeatures;
29
+ return this;
30
+ }
31
+
32
+ public reloadOnAccess(): this {
33
+ this.reload = true;
34
+ return this;
35
+ }
36
+
37
+ public redirectOnAccess(requestedUrl: string): this {
38
+ this.requestedUrl = requestedUrl;
39
+ return this;
40
+ }
41
+
42
+ public async tryUnlock(): Promise<UnlockResponse> {
43
+ // Ensures we don't get stuck in a reload/redirect loop
44
+ if (hasRecentlyTriedToUnlockPaywall()) {
45
+ throw new PaywallError(
46
+ 'Unlock check already performed.',
47
+ PaywallError.ERROR_RELOADED_NO_ACCESS
48
+ );
49
+ }
50
+
51
+ const {
52
+ state: { isLoggedIn },
53
+ } = await new UserDataRequest().fetch();
54
+ if (!isLoggedIn) {
55
+ // Will attempt one or more strategies for creating a first party session
56
+ // Redirects/reloads might occur
57
+ await attemptAutologin();
58
+ return {
59
+ isLoggedIn: false,
60
+ hasAccess: false,
61
+ accessFeatures: [],
62
+ };
63
+ }
64
+
65
+ let accessFeatures = await this.setAccessCookiesAndGetAccessFeatures();
66
+ if (!hasAccess(accessFeatures, this.requestedAccessFeatures)) {
67
+ /**
68
+ * TODO: This introduces a bug for plussalt where a new user won't get access features, since activation fails.
69
+ * TODO: The user should get {
70
+ * isLoggedIn: true,
71
+ * hasAccess: false,
72
+ * accessFeatures: ['newspaper'],
73
+ * }
74
+ * TODO: The solution will be that activate returns access features as well after checking so we can return them.
75
+ */
76
+ // Check if we actually have a valid subscription that's not properly connected to the user yet
77
+ if (await activate(this.requestedAccessFeatures)) {
78
+ accessFeatures = await this.setAccessCookiesAndGetAccessFeatures();
79
+ if (!hasAccess(accessFeatures, this.requestedAccessFeatures)) {
80
+ throw new PaywallError(
81
+ 'New subscription was attached and checked successfully, but internal systems disagree about current newspaper access.',
82
+ PaywallError.ERROR_NO_ACCESS_AFTER_SUCCESSFUL_ACTIVATION_WITH_REQUESTED_ACCESS_FEATURES
83
+ );
84
+ }
85
+ } else {
86
+ return {
87
+ isLoggedIn: true,
88
+ hasAccess: false,
89
+ accessFeatures,
90
+ };
91
+ }
92
+ }
93
+ if (this.reload) {
94
+ location.reload();
95
+ }
96
+ if (this.requestedUrl) {
97
+ location.replace(this.requestedUrl);
98
+ }
99
+ return {
100
+ isLoggedIn: true,
101
+ hasAccess: true,
102
+ accessFeatures,
103
+ };
104
+ }
105
+
106
+ // eslint-disable-next-line class-methods-use-this
107
+ private setAccessCookiesAndGetAccessFeatures() {
108
+ return setAccessCookies(getCurrentPublicationDomain()).then((response) => {
109
+ if (!response.success) {
110
+ throw new PaywallError(
111
+ 'Could not set access cookies',
112
+ PaywallError.ERROR_ENABLING_ACCESS_FAILED
113
+ );
114
+ }
115
+ setHasTriedToUnlockPaywall();
116
+ return response.accessFeatures;
117
+ });
118
+ }
119
+ }
120
+
121
+ export default PaywallUnlockRequest;
@@ -0,0 +1,58 @@
1
+ /**
2
+ * @jest-environment jsdom
3
+ */
4
+
5
+ import store from '../store';
6
+ import UserDataRequest from './UserDataRequest';
7
+ import { listenForStateRequests } from '../eventHandlers/state';
8
+ import { listenForStorageRequests } from '../eventHandlers/storage';
9
+ import { listenForUserAttributeRequests } from '../eventHandlers/userAttributes';
10
+ import { setRootElement } from '../utils/customEventWrapper';
11
+ import * as pluto from '../clients/pluto';
12
+ import restoreAllMocks = jest.restoreAllMocks;
13
+
14
+ beforeEach(() => {
15
+ restoreAllMocks();
16
+ store.clear();
17
+
18
+ // We cannot use window as our event root during testing
19
+ // since tests are executed in parallel.
20
+ setRootElement(new Document());
21
+ jest.spyOn(pluto, 'getCurrentSession').mockResolvedValue({});
22
+
23
+ // Also, since we keep creating new root elements, we also
24
+ // need to attach to these new roots.
25
+ listenForStateRequests();
26
+ listenForStorageRequests();
27
+ listenForUserAttributeRequests();
28
+ });
29
+
30
+ describe('UserDataRequest', () => {
31
+ beforeEach(() => {});
32
+ describe('when subscribing', () => {});
33
+ describe('when fetching', () => {
34
+ describe('and not logged in', () => {
35
+ let fetchResponse;
36
+ beforeEach(async () => {
37
+ store.set('state', { isLoggedIn: false });
38
+
39
+ try {
40
+ fetchResponse = await new UserDataRequest()
41
+ .withAttributes(['name'])
42
+ .fetch();
43
+ } catch (e) {
44
+ console.log('wat', e);
45
+ }
46
+ });
47
+
48
+ it('should respond immediately since we are not logged in', () => {
49
+ expect(fetchResponse).toEqual({
50
+ state: {
51
+ isLoggedIn: false,
52
+ },
53
+ attributes: {},
54
+ });
55
+ });
56
+ });
57
+ });
58
+ });
@@ -1,9 +1,21 @@
1
1
  import { State, UserAttributes } from '../types';
2
2
  import { dispatch, listenForAllEvents } from '../utils/customEventWrapper';
3
- import { AmediaUserEvents } from '../eventHandlers/userAttributes';
3
+ import { AmediaUserEvents } from '../eventHandlers/eventMap';
4
4
  import { deepEquals } from '../utils/deepEquals';
5
5
 
6
- class User<
6
+ function isMissingData(requestedKeys?: string[], data?: Object) {
7
+ if (requestedKeys && requestedKeys.length > 0) {
8
+ if (data && Object.keys(data).length > 0) {
9
+ return (
10
+ requestedKeys.filter((a) => !Object.keys(data).includes(a)).length > 0
11
+ );
12
+ }
13
+ return true;
14
+ }
15
+ return false;
16
+ }
17
+
18
+ class UserDataRequest<
7
19
  UA extends UserAttributes,
8
20
  S extends { [index: string]: unknown },
9
21
  Attributes extends Array<keyof UA>,
@@ -18,7 +30,7 @@ class User<
18
30
  withAttributes<NewAttributes extends Array<keyof UA>>(
19
31
  attributes: NewAttributes
20
32
  ) {
21
- return new User<
33
+ return new UserDataRequest<
22
34
  UA,
23
35
  S,
24
36
  Array<Attributes[number] & NewAttributes[number]>,
@@ -32,10 +44,8 @@ class User<
32
44
  );
33
45
  }
34
46
 
35
- withStorage<NewNamespaces extends Array<string>>(
36
- ...namespace: NewNamespaces
37
- ) {
38
- return new User<
47
+ withStorage<NewNamespaces extends Array<string>>(namespaces: NewNamespaces) {
48
+ return new UserDataRequest<
39
49
  UA,
40
50
  S,
41
51
  Attributes,
@@ -45,16 +55,14 @@ class User<
45
55
  }
46
56
  >(this.attributes, [
47
57
  ...((this.namespaces || ([] as unknown)) as Namespaces),
48
- ...namespace,
58
+ ...namespaces,
49
59
  ]);
50
60
  }
51
61
 
52
62
  subscribe(onData: (data: SubscribeResponse) => void): void {
53
63
  let previousData = this.setupLocalCache();
54
-
55
64
  listenForAllEvents(AmediaUserEvents.ON_STATE_UPDATED, (evt) => {
56
65
  const state = evt.detail;
57
-
58
66
  if (
59
67
  // eslint-disable-next-line @typescript-eslint/dot-notation
60
68
  Object.keys(previousData['state']).length > 0 &&
@@ -67,6 +75,7 @@ class User<
67
75
  previousData = { ...previousData, state };
68
76
  onData(previousData);
69
77
  });
78
+ dispatch(new CustomEvent(AmediaUserEvents.REQUEST_STATE));
70
79
 
71
80
  if (Array.isArray(this.attributes) && this.attributes.length > 0) {
72
81
  listenForAllEvents(AmediaUserEvents.ON_ATTRIBUTES_UPDATED, (evt) => {
@@ -111,6 +120,31 @@ class User<
111
120
  }
112
121
  }
113
122
 
123
+ fetch(): Promise<SubscribeResponse> {
124
+ return new Promise<SubscribeResponse>((resolve) => {
125
+ this.subscribe((data: any) => {
126
+ // @ts-ignore
127
+ if (typeof data.state.isLoggedIn === 'undefined') {
128
+ return;
129
+ }
130
+ // @ts-ignore
131
+ if (data.state.isLoggedIn === false) {
132
+ resolve(data);
133
+ }
134
+
135
+ if (
136
+ // @ts-ignore
137
+ isMissingData(this.attributes, data.attributes) ||
138
+ isMissingData(this.namespaces, data.storage)
139
+ ) {
140
+ return;
141
+ }
142
+
143
+ resolve(data);
144
+ });
145
+ });
146
+ }
147
+
114
148
  private processUserAttributesEvent(evt: CustomEvent<UserAttributes>) {
115
149
  const userAttributes = evt.detail as UA;
116
150
 
@@ -160,4 +194,4 @@ class User<
160
194
  }
161
195
  }
162
196
 
163
- export default User;
197
+ export default UserDataRequest;
@@ -39,7 +39,7 @@ const set = (key: keyof StoreDataMap, value: StoreDataMap[typeof key]) => {
39
39
 
40
40
  const merge = <K extends keyof StoreDataMap>(
41
41
  key: K,
42
- value: StoreDataMap[K]
42
+ value: Partial<StoreDataMap[K]>
43
43
  ) => {
44
44
  // @ts-ignore
45
45
  set(key, deepmerge(store[key] || {}, value));
package/src/utils/log.ts CHANGED
@@ -13,23 +13,19 @@ export const setLogger = (engine: Logger) => {
13
13
  logger = engine;
14
14
  };
15
15
 
16
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
17
16
  const getLogger = () => logger || mercury;
18
17
 
19
- /* export default {
20
- debug: getLogger().debug,
21
- info: getLogger().info,
22
- warn: getLogger().warn,
23
- error: getLogger().error,
24
- }; */
25
-
26
18
  export default {
27
- // eslint-disable-next-line no-console
28
- debug: console.debug,
29
- // eslint-disable-next-line no-console
30
- info: console.info,
31
- // eslint-disable-next-line no-console
32
- warn: console.warn,
33
- // eslint-disable-next-line no-console
34
- error: console.error,
19
+ debug: (message: string | any, ...extra: any[]) => {
20
+ getLogger().debug(message, ...extra);
21
+ },
22
+ info: (message: string | any, ...extra: any[]) => {
23
+ getLogger().info(message, ...extra);
24
+ },
25
+ warn: (message: string | any, ...extra: any[]) => {
26
+ getLogger().warn(message, ...extra);
27
+ },
28
+ error: (message: string | any, ...extra: any[]) => {
29
+ getLogger().error(message, ...extra);
30
+ },
35
31
  };
@@ -6,17 +6,17 @@ export default function logValidationError(
6
6
  error: Error,
7
7
  extra?: Object
8
8
  ) {
9
+ let message: string;
9
10
  const args: any[] = [];
10
11
  if (error instanceof ValidationError) {
11
- args.push(`Invalid ${name}`, error.details);
12
+ message = `Invalid ${name}`;
13
+ args.push(error.details);
12
14
  } else {
13
- args.push(
14
- `Unknown error after validating ${name}: (${error.message}`,
15
- error
16
- );
15
+ message = `Unknown error after validating ${name}: (${error.message}`;
16
+ args.push(error);
17
17
  }
18
18
  if (extra) {
19
19
  args.push(extra);
20
20
  }
21
- log.error(...args);
21
+ log.error(message, ...args);
22
22
  }