@amedia/user 0.13.34 → 0.13.36

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 (180) hide show
  1. package/dist/user.cjs +15 -0
  2. package/dist/{index.js.map → user.cjs.map} +3 -3
  3. package/dist/{index.d.ts → user.d.ts} +12 -0
  4. package/dist/user.js +15 -0
  5. package/dist/{index.esm.js.map → user.js.map} +3 -3
  6. package/package.json +9 -6
  7. package/.codeclimate.yml +0 -8
  8. package/.eslintignore +0 -2
  9. package/.eslintrc +0 -11
  10. package/.prettierrc.json +0 -1
  11. package/@types/amedia-frontend-rpc.d.ts +0 -11
  12. package/@types/browserid.d.ts +0 -4
  13. package/build.js +0 -28
  14. package/checkVersion.cjs +0 -12
  15. package/cloudbuild.json +0 -29
  16. package/cop.json +0 -8
  17. package/dist/actions/authentication.d.ts +0 -4
  18. package/dist/actions/authentication.spec.d.ts +0 -1
  19. package/dist/actions/authorization.d.ts +0 -14
  20. package/dist/actions/authorization.spec.d.ts +0 -4
  21. package/dist/actions/preferences.d.ts +0 -9
  22. package/dist/actions/preferences.spec.d.ts +0 -1
  23. package/dist/actions/storage.d.ts +0 -7
  24. package/dist/actions/userData.d.ts +0 -2
  25. package/dist/actions/userData.spec.d.ts +0 -1
  26. package/dist/autologin/index.d.ts +0 -7
  27. package/dist/autologin/index.spec.d.ts +0 -1
  28. package/dist/autologin/thirdPartyCookie.d.ts +0 -3
  29. package/dist/autologin/thirdPartyCookie.spec.d.ts +0 -1
  30. package/dist/cache/engines/global.d.ts +0 -24
  31. package/dist/cache/engines/global.spec.d.ts +0 -1
  32. package/dist/cache/index.d.ts +0 -11
  33. package/dist/cache/index.spec.d.ts +0 -1
  34. package/dist/cache/types.d.ts +0 -11
  35. package/dist/clients/europa.d.ts +0 -24
  36. package/dist/clients/europa.spec.d.ts +0 -1
  37. package/dist/clients/jupiter.d.ts +0 -30
  38. package/dist/clients/jupiter.spec.d.ts +0 -1
  39. package/dist/clients/mercury.d.ts +0 -3
  40. package/dist/clients/mercury.spec.d.ts +0 -1
  41. package/dist/clients/mercuryLog.d.ts +0 -8
  42. package/dist/clients/mercuryLog.spec.d.ts +0 -1
  43. package/dist/clients/nebula.d.ts +0 -2
  44. package/dist/clients/nebula.spec.d.ts +0 -1
  45. package/dist/clients/pluto.d.ts +0 -4
  46. package/dist/clients/pluto.spec.d.ts +0 -1
  47. package/dist/eventHandlers/activation.d.ts +0 -15
  48. package/dist/eventHandlers/authentication.d.ts +0 -17
  49. package/dist/eventHandlers/eventMap.d.ts +0 -29
  50. package/dist/eventHandlers/state.d.ts +0 -1
  51. package/dist/eventHandlers/state.spec.d.ts +0 -1
  52. package/dist/eventHandlers/storage.d.ts +0 -1
  53. package/dist/eventHandlers/storage.spec.d.ts +0 -1
  54. package/dist/eventHandlers/userAttributes.d.ts +0 -1
  55. package/dist/eventHandlers/userAttributes.spec.d.ts +0 -1
  56. package/dist/exceptions/PaywallError.d.ts +0 -8
  57. package/dist/index-authentcation.spec.d.ts +0 -1
  58. package/dist/index-storage.spec.d.ts +0 -1
  59. package/dist/index-subscription.spec.d.ts +0 -1
  60. package/dist/index.esm.js +0 -15
  61. package/dist/index.js +0 -15
  62. package/dist/janitor/index.d.ts +0 -10
  63. package/dist/janitor/index.spec.d.ts +0 -1
  64. package/dist/janitor/jobs/accessCookieRefresher.d.ts +0 -1
  65. package/dist/janitor/jobs/accessCookieRefresher.spec.d.ts +0 -1
  66. package/dist/janitor/jobs/daxsubCookie.d.ts +0 -3
  67. package/dist/janitor/jobs/daxsubCookie.spec.d.ts +0 -1
  68. package/dist/janitor/jobs/removeUserStorage.d.ts +0 -1
  69. package/dist/janitor/jobs/removeUserStorage.spec.d.ts +0 -1
  70. package/dist/lib/PaywallUnlockRequest.d.ts +0 -17
  71. package/dist/lib/PaywallUnlockRequest.spec.d.ts +0 -1
  72. package/dist/lib/UserDataRequest.d.ts +0 -22
  73. package/dist/lib/UserDataRequest.spec.d.ts +0 -1
  74. package/dist/lib/cookie.d.ts +0 -9
  75. package/dist/lib/rpc.d.ts +0 -6
  76. package/dist/store/index.d.ts +0 -23
  77. package/dist/store/index.spec.d.ts +0 -1
  78. package/dist/types.d.ts +0 -22
  79. package/dist/utils/customEventWrapper.d.ts +0 -19
  80. package/dist/utils/debouncer.d.ts +0 -26
  81. package/dist/utils/debouncer.spec.d.ts +0 -1
  82. package/dist/utils/deepEquals.d.ts +0 -1
  83. package/dist/utils/expectBootLogs.d.ts +0 -2
  84. package/dist/utils/getOrUpdate.d.ts +0 -6
  85. package/dist/utils/getOrUpdate.spec.d.ts +0 -1
  86. package/dist/utils/localhostCheck.d.ts +0 -1
  87. package/dist/utils/location.d.ts +0 -3
  88. package/dist/utils/log.d.ts +0 -9
  89. package/dist/utils/log.spec.d.ts +0 -1
  90. package/dist/utils/loginState.d.ts +0 -2
  91. package/dist/utils/networkError.d.ts +0 -1
  92. package/dist/utils/queue.d.ts +0 -12
  93. package/dist/utils/type.d.ts +0 -6
  94. package/dist/utils/url.d.ts +0 -6
  95. package/dist/utils/url.spec.d.ts +0 -1
  96. package/eik.json +0 -10
  97. package/global.d.ts +0 -1
  98. package/jest.config.js +0 -7
  99. package/setupJest.js +0 -1
  100. package/src/actions/authentication.spec.ts +0 -51
  101. package/src/actions/authentication.ts +0 -43
  102. package/src/actions/authorization.spec.ts +0 -369
  103. package/src/actions/authorization.ts +0 -117
  104. package/src/actions/preferences.spec.ts +0 -41
  105. package/src/actions/preferences.ts +0 -41
  106. package/src/actions/storage.ts +0 -22
  107. package/src/actions/userData.spec.ts +0 -133
  108. package/src/actions/userData.ts +0 -68
  109. package/src/autologin/index.spec.ts +0 -239
  110. package/src/autologin/index.ts +0 -92
  111. package/src/autologin/thirdPartyCookie.spec.ts +0 -95
  112. package/src/autologin/thirdPartyCookie.ts +0 -55
  113. package/src/cache/engines/global.spec.ts +0 -62
  114. package/src/cache/engines/global.ts +0 -48
  115. package/src/cache/index.spec.ts +0 -130
  116. package/src/cache/index.ts +0 -48
  117. package/src/cache/types.ts +0 -12
  118. package/src/clients/europa.spec.ts +0 -209
  119. package/src/clients/europa.ts +0 -183
  120. package/src/clients/jupiter.spec.ts +0 -179
  121. package/src/clients/jupiter.ts +0 -119
  122. package/src/clients/mercury.spec.ts +0 -59
  123. package/src/clients/mercury.ts +0 -48
  124. package/src/clients/mercuryLog.spec.ts +0 -20
  125. package/src/clients/mercuryLog.ts +0 -67
  126. package/src/clients/nebula.spec.ts +0 -70
  127. package/src/clients/nebula.ts +0 -83
  128. package/src/clients/pluto.spec.ts +0 -165
  129. package/src/clients/pluto.ts +0 -118
  130. package/src/eventHandlers/activation.ts +0 -35
  131. package/src/eventHandlers/authentication.ts +0 -34
  132. package/src/eventHandlers/eventMap.ts +0 -34
  133. package/src/eventHandlers/state.spec.ts +0 -48
  134. package/src/eventHandlers/state.ts +0 -23
  135. package/src/eventHandlers/storage.spec.ts +0 -114
  136. package/src/eventHandlers/storage.ts +0 -45
  137. package/src/eventHandlers/userAttributes.spec.ts +0 -93
  138. package/src/eventHandlers/userAttributes.ts +0 -31
  139. package/src/exceptions/PaywallError.ts +0 -16
  140. package/src/index-authentcation.spec.ts +0 -26
  141. package/src/index-storage.spec.ts +0 -144
  142. package/src/index-subscription.spec.ts +0 -213
  143. package/src/index.ts +0 -59
  144. package/src/janitor/index.spec.ts +0 -18
  145. package/src/janitor/index.ts +0 -59
  146. package/src/janitor/jobs/accessCookieRefresher.spec.ts +0 -213
  147. package/src/janitor/jobs/accessCookieRefresher.ts +0 -98
  148. package/src/janitor/jobs/daxsubCookie.spec.ts +0 -109
  149. package/src/janitor/jobs/daxsubCookie.ts +0 -38
  150. package/src/janitor/jobs/removeUserStorage.spec.ts +0 -34
  151. package/src/janitor/jobs/removeUserStorage.ts +0 -12
  152. package/src/lib/PaywallUnlockRequest.spec.ts +0 -363
  153. package/src/lib/PaywallUnlockRequest.ts +0 -143
  154. package/src/lib/UserDataRequest.spec.ts +0 -77
  155. package/src/lib/UserDataRequest.ts +0 -213
  156. package/src/lib/cookie.ts +0 -121
  157. package/src/lib/rpc.ts +0 -19
  158. package/src/store/index.spec.ts +0 -49
  159. package/src/store/index.ts +0 -64
  160. package/src/types.ts +0 -22
  161. package/src/utils/customEventWrapper.ts +0 -58
  162. package/src/utils/debouncer.spec.ts +0 -252
  163. package/src/utils/debouncer.ts +0 -123
  164. package/src/utils/deepEquals.ts +0 -42
  165. package/src/utils/expectBootLogs.ts +0 -9
  166. package/src/utils/getOrUpdate.spec.ts +0 -166
  167. package/src/utils/getOrUpdate.ts +0 -66
  168. package/src/utils/localhostCheck.ts +0 -9
  169. package/src/utils/location.ts +0 -31
  170. package/src/utils/log.spec.ts +0 -148
  171. package/src/utils/log.ts +0 -124
  172. package/src/utils/loginState.ts +0 -24
  173. package/src/utils/networkError.ts +0 -11
  174. package/src/utils/queue.ts +0 -32
  175. package/src/utils/type.ts +0 -19
  176. package/src/utils/url.spec.ts +0 -33
  177. package/src/utils/url.ts +0 -35
  178. package/testSetup.js +0 -19
  179. package/tsconfig.eslint.json +0 -24
  180. package/tsconfig.json +0 -18
@@ -1,179 +0,0 @@
1
- import fetch from 'jest-fetch-mock';
2
- import cache from '../cache';
3
- import log from '../utils/log';
4
- import {
5
- checkForAccess,
6
- getUserAccess,
7
- AccessFeatures,
8
- CheckAccessForPaper,
9
- GetVstoken,
10
- GetNonUserAccess,
11
- getNonUserAccess,
12
- } from './jupiter';
13
- import anything = jasmine.anything;
14
-
15
- beforeEach(async () => {
16
- await cache.clear();
17
- });
18
-
19
- describe('jupiter service', () => {
20
- describe('GET /check_access_for_paper', () => {
21
- const publicationDomain = 'www.rb.no';
22
- const accessFeatures: AccessFeatures = ['newspaper'];
23
-
24
- it('should check access for paper', async () => {
25
- const response: CheckAccessForPaper = {
26
- status: 'success',
27
- access: 'granted',
28
- publication: {
29
- domain: 'www.rb.no',
30
- id: 95,
31
- },
32
- access_features: ['amedia_staff', 'newspaper'],
33
- };
34
-
35
- fetch.mockResponseOnce(JSON.stringify(response));
36
-
37
- await expect(
38
- checkForAccess(publicationDomain, accessFeatures)
39
- ).resolves.toEqual({
40
- access: ['amedia_staff', 'newspaper'],
41
- });
42
-
43
- expect(fetch).toHaveBeenCalledWith(
44
- `/api/jupiter/v1/check_access_for_paper/${publicationDomain}/?require=any&access_features=${accessFeatures.join(
45
- ','
46
- )}`
47
- );
48
- });
49
-
50
- it('should deny access for user not logged in', async () => {
51
- fetch.mockResponseOnce(JSON.stringify({ status: 'no_session_found' }), {
52
- status: 400,
53
- });
54
-
55
- await expect(
56
- checkForAccess(publicationDomain, accessFeatures)
57
- ).rejects.toBeUndefined();
58
- });
59
-
60
- it('should fail on runtime validation', async () => {
61
- fetch.mockResponseOnce(JSON.stringify({ access_features: 'foo' }));
62
- log.error = jest.fn();
63
-
64
- await expect(
65
- checkForAccess(publicationDomain, accessFeatures)
66
- ).rejects.toBeUndefined();
67
- });
68
-
69
- it('should not cache when access denied', (done) => {
70
- fetch.mockResponseOnce(
71
- JSON.stringify({
72
- status: 'success',
73
- access: 'denied',
74
- publication: {
75
- domain: 'www.rb.no',
76
- id: 95,
77
- },
78
- access_features: [],
79
- })
80
- );
81
- const cacheSetSpy = spyOn(cache, 'set');
82
- expect(checkForAccess(publicationDomain, accessFeatures))
83
- .resolves.toEqual({ access: [] })
84
- .then(() => {
85
- expect(cacheSetSpy).toHaveBeenCalledWith(
86
- 'checkForAccess',
87
- anything(),
88
- 0
89
- );
90
- })
91
- .then(done);
92
- });
93
- });
94
-
95
- describe('POST /get_vstoken', () => {
96
- const publicationDomain = 'www.rb.no';
97
-
98
- it('should return vstoken', async () => {
99
- const response: GetVstoken = {
100
- status: 'success',
101
- cookie: 'ofofb:16187:amedia_staff,newspaper,plussalt:cc2c2c:rb:jupiter',
102
- access_features: ['newspaper', 'plussalt'],
103
- };
104
-
105
- fetch.mockResponseOnce(JSON.stringify(response));
106
-
107
- await expect(getUserAccess(publicationDomain)).resolves.toEqual(response);
108
-
109
- expect(fetch).toHaveBeenCalledWith(
110
- `/api/jupiter/v1/get_vstoken/${publicationDomain}`,
111
- {
112
- method: 'post',
113
- }
114
- );
115
- });
116
-
117
- it('should deny access for user not logged in', async () => {
118
- fetch.mockResponseOnce(JSON.stringify({ status: 'no_session_found' }), {
119
- status: 400,
120
- });
121
-
122
- await expect(getUserAccess(publicationDomain)).rejects.toThrow(
123
- 'Request not ok (400: Bad Request).'
124
- );
125
- });
126
-
127
- it('should fail on runtime validation', async () => {
128
- fetch.mockResponseOnce(JSON.stringify({ access_features: 'foo' }));
129
- log.error = jest.fn();
130
-
131
- await expect(getUserAccess(publicationDomain)).rejects.toThrow(
132
- 'Expected { status: "success"; cookie: string; access_features: string[]; }, but was incompatible'
133
- );
134
- });
135
- });
136
-
137
- describe('POST /non_user_access', () => {
138
- const publicationDomain = 'www.rb.no';
139
-
140
- it('should return none user access', async () => {
141
- const response: GetNonUserAccess = {
142
- status: 'success',
143
- vstoken_cookie: 'd82ab3842a:2619693230:::rb:jupiter',
144
- uuid: '',
145
- access_features: [],
146
- };
147
-
148
- fetch.mockResponseOnce(JSON.stringify(response));
149
-
150
- await expect(getNonUserAccess(publicationDomain)).resolves.toEqual(
151
- response
152
- );
153
-
154
- expect(fetch).toHaveBeenCalledWith(
155
- `/api/jupiter/v1/non_user_access/${publicationDomain}`,
156
- { method: 'post' }
157
- );
158
- });
159
-
160
- it('should deny access for user not logged in', async () => {
161
- fetch.mockResponseOnce(JSON.stringify({ status: 'no_session_found' }), {
162
- status: 400,
163
- });
164
-
165
- await expect(getNonUserAccess(publicationDomain)).rejects.toThrow(
166
- 'Request not ok (400: Bad Request).'
167
- );
168
- });
169
-
170
- it('should fail on runtime validation', async () => {
171
- fetch.mockResponseOnce(JSON.stringify({ vstoken_cookie: 3 }));
172
- log.error = jest.fn();
173
-
174
- await expect(getNonUserAccess(publicationDomain)).rejects.toThrow(
175
- 'Expected { status: "success"; vstoken_cookie: string; uuid: string; access_features: string[]; }, but was incompatible'
176
- );
177
- });
178
- });
179
- });
@@ -1,119 +0,0 @@
1
- import {
2
- Array,
3
- Literal,
4
- Number,
5
- Record,
6
- Static,
7
- String,
8
- Union,
9
- } from 'runtypes';
10
- import getOrUpdate from '../utils/getOrUpdate';
11
- import { UserAttributes } from '../types';
12
- import log from '../utils/log';
13
-
14
- export type AccessFeatures = string[];
15
-
16
- const PublicationSchema = Record({
17
- id: Number,
18
- domain: String,
19
- });
20
- export const CheckAccessForPaperSchema = Record({
21
- status: Literal('success'),
22
- access: Union(Literal('granted'), Literal('denied')),
23
- publication: PublicationSchema,
24
- access_features: Array(String),
25
- });
26
-
27
- export type CheckAccessForPaper = Static<typeof CheckAccessForPaperSchema>;
28
-
29
- const GetVstokenSchema = Record({
30
- status: Literal('success'),
31
- cookie: String,
32
- access_features: Array(String),
33
- });
34
-
35
- export type GetVstoken = Static<typeof GetVstokenSchema>;
36
-
37
- const GetNonUserAccessSchema = Record({
38
- status: Literal('success'),
39
- vstoken_cookie: String,
40
- uuid: String,
41
- access_features: Array(String),
42
- });
43
-
44
- export type GetNonUserAccess = Static<typeof GetNonUserAccessSchema>;
45
-
46
- export const checkForAccess = (
47
- publicationDomain: string,
48
- accessFeatures: AccessFeatures
49
- ): Promise<Pick<UserAttributes, 'access'>> =>
50
- getOrUpdate('checkForAccess', CheckAccessForPaperSchema, () =>
51
- fetch(
52
- `/api/jupiter/v1/check_access_for_paper/${publicationDomain}/?require=any&access_features=${accessFeatures.join(
53
- ','
54
- )}`
55
- )
56
- .then((response) => {
57
- if (!response.ok) {
58
- // TODO Handle this.
59
- throw new Error(
60
- `Request not ok (${response.status}: ${response.statusText}).`
61
- );
62
- }
63
- return response.json();
64
- })
65
- .then((json) => {
66
- try {
67
- const data = CheckAccessForPaperSchema.check(json);
68
- return {
69
- ttl: data.access === 'granted' ? 1000 * 10 : 0, // 10 seconds
70
- data,
71
- };
72
- } catch (error) {
73
- log.error(error, { json });
74
- throw error;
75
- }
76
- })
77
- ).then((data) => ({ access: data.access_features }));
78
-
79
- export const getUserAccess = (publicationDomain: string): Promise<GetVstoken> =>
80
- fetch(`/api/jupiter/v1/get_vstoken/${publicationDomain}`, { method: 'post' })
81
- .then((response) => {
82
- if (!response.ok) {
83
- throw new Error(
84
- `Request not ok (${response.status}: ${response.statusText}).`
85
- );
86
- }
87
- return response.json();
88
- })
89
- .then((json) => {
90
- try {
91
- return GetVstokenSchema.check(json);
92
- } catch (error) {
93
- log.error(error, { json });
94
- throw error;
95
- }
96
- });
97
-
98
- export const getNonUserAccess = (
99
- publicationDomain: string
100
- ): Promise<GetNonUserAccess> =>
101
- fetch(`/api/jupiter/v1/non_user_access/${publicationDomain}`, {
102
- method: 'post',
103
- })
104
- .then((response) => {
105
- if (!response.ok) {
106
- throw new Error(
107
- `Request not ok (${response.status}: ${response.statusText}).`
108
- );
109
- }
110
- return response.json();
111
- })
112
- .then((json) => {
113
- try {
114
- return GetNonUserAccessSchema.check(json);
115
- } catch (error) {
116
- log.error(error, { json });
117
- throw error;
118
- }
119
- });
@@ -1,59 +0,0 @@
1
- import fetch from 'jest-fetch-mock';
2
- import { activateSubscription, UserDeactivatedError } from './mercury';
3
-
4
- describe('activateSubscription()', () => {
5
- it('should throw error if user is deactivated', async () => {
6
- fetch.mockResponse(JSON.stringify({ status: 'user_deactivated' }), {
7
- status: 401,
8
- });
9
- await expect(activateSubscription(['newspaper'])).rejects.toThrow(
10
- UserDeactivatedError
11
- );
12
- });
13
-
14
- it('should return empty list if user not found', async () => {
15
- fetch.mockResponse(JSON.stringify({ status: 'no_session_found' }), {
16
- status: 401,
17
- });
18
- await expect(activateSubscription(['newspaper'])).resolves.toEqual([]);
19
- });
20
-
21
- it('should return list if access features even if requested access is not "granted"', async () => {
22
- fetch.mockResponse(
23
- JSON.stringify({
24
- status: 'success',
25
- access: 'denied',
26
- access_features: ['newspaper'],
27
- })
28
- );
29
- await expect(activateSubscription(['newspaper'])).resolves.toEqual([
30
- 'newspaper',
31
- ]);
32
- });
33
-
34
- it('should return list of access features even if status is not "success"', async () => {
35
- fetch.mockResponse(
36
- JSON.stringify({
37
- status: 'unknown',
38
- access: 'granted',
39
- access_features: ['newspaper'],
40
- })
41
- );
42
- await expect(activateSubscription(['newspaper'])).resolves.toEqual([
43
- 'newspaper',
44
- ]);
45
- });
46
-
47
- it('should return ["newspaper"] if status is "success" and access is "granted"', async () => {
48
- fetch.mockResponse(
49
- JSON.stringify({
50
- status: 'success',
51
- access: 'granted',
52
- access_features: ['newspaper'],
53
- })
54
- );
55
- await expect(activateSubscription(['newspaper'])).resolves.toEqual([
56
- 'newspaper',
57
- ]);
58
- });
59
- });
@@ -1,48 +0,0 @@
1
- import log from '../utils/log';
2
- import { getCurrentPublicationDomain } from '../utils/url';
3
-
4
- export class UserDeactivatedError extends Error {}
5
-
6
- const EXPECTED_ERRORS = [
7
- 'no_session_found', // Not logged in
8
- 'subscription_not_found', // No active subscription
9
- 'publication_not_subscribable', // Activation is not possible on current publication
10
- ];
11
-
12
- export const activateSubscription = async (
13
- accessFeatures: string[]
14
- ): Promise<string[]> =>
15
- fetch(
16
- `/api/mercury/v2/access/activate?publication_wwwdomain=${getCurrentPublicationDomain()}&access_features=${accessFeatures.join(
17
- ','
18
- )}`,
19
- {
20
- method: 'post',
21
- }
22
- ).then(async (response) => {
23
- const body = await response.text();
24
- let data;
25
- try {
26
- data = JSON.parse(body);
27
- } catch (error) {
28
- log.error(
29
- `Activate subscription failed. Mercury (HTTP/${response.status}: ${body})`,
30
- { error, response, accessFeatures, body }
31
- );
32
- }
33
- if (!response.ok) {
34
- // User deactivated
35
- if (data?.status === 'user_deactivated') {
36
- throw new UserDeactivatedError();
37
- }
38
- if (EXPECTED_ERRORS.includes(data?.status)) {
39
- return [];
40
- }
41
- log.error(
42
- `Activate subscription failed. Mercury (HTTP/${response.status}: ${body})`,
43
- { response, accessFeatures, body }
44
- );
45
- return [];
46
- }
47
- return data?.access_features;
48
- });
@@ -1,20 +0,0 @@
1
- import fetch from 'jest-fetch-mock';
2
- import backendLog from './mercuryLog';
3
-
4
- describe('Mercury backendlog', () => {
5
- it('should include level in url', () => {
6
- backendLog.error('jest message', {});
7
- expect(fetch).toHaveBeenCalledWith(
8
- expect.stringContaining('/error'),
9
- expect.anything()
10
- );
11
- expect(fetch).toHaveBeenCalledTimes(1);
12
- });
13
-
14
- it('should include additional context as query parameters', () => {
15
- backendLog.error('jest message', { referrer: 'https://www.rb.no/' });
16
- const formData = fetch.mock.calls[0][1]?.body as FormData;
17
-
18
- expect(formData?.get('referrer')).toEqual('https://www.rb.no/');
19
- });
20
- });
@@ -1,67 +0,0 @@
1
- import { getCurrentHostname, getCurrentUrl } from '../utils/url';
2
- import { isBoolean, isNumber, isString } from '../utils/type';
3
-
4
- type Context = Record<string, unknown>;
5
-
6
- /**
7
- * Extracted from mercury.tsx so other calls to mercury can log properly
8
- */
9
- function postLog(url: string, query: { [index: string]: any }) {
10
- const body = new FormData();
11
- Object.keys(query).forEach((key) => body.append(key, query[key]));
12
- const options: RequestInit = {
13
- method: 'POST',
14
- body,
15
- headers: {
16
- Accept: 'application/json',
17
- },
18
- };
19
- fetch(url, options).then((res) => {
20
- if (!res.ok) {
21
- // eslint-disable-next-line no-console
22
- console.error(
23
- `Failed to send log to backend: Error, status: ${res.status}, text: ${res.statusText}`
24
- );
25
- }
26
- });
27
- }
28
-
29
- const backendLog = (level: string, message: string, context: Context) => {
30
- const internalContext: Context = {};
31
- Object.keys(context).forEach((key) => {
32
- const currentContext = context[key];
33
- if (
34
- isString(currentContext) ||
35
- isNumber(currentContext) ||
36
- isBoolean(currentContext)
37
- ) {
38
- internalContext[key] = currentContext;
39
- return;
40
- }
41
- try {
42
- internalContext[key] = JSON.stringify(currentContext);
43
- } catch {
44
- internalContext[key] = currentContext;
45
- }
46
- });
47
- const extendedContext = {
48
- ...internalContext,
49
- message,
50
- url: getCurrentUrl(),
51
- domain: getCurrentHostname(),
52
- };
53
- postLog(`/api/mercury/v1/log/${level}`, extendedContext);
54
- };
55
-
56
- const log = {
57
- error: (message: string, context: Context) =>
58
- backendLog('error', message, context),
59
- warn: (message: string, context: Context) =>
60
- backendLog('warn', message, context),
61
- info: (message: string, context: Context) =>
62
- backendLog('info', message, context),
63
- debug: (message: string, context: Context) =>
64
- backendLog('debug', message, context),
65
- };
66
-
67
- export default log;
@@ -1,70 +0,0 @@
1
- import fetch from 'jest-fetch-mock';
2
- import cache from '../cache';
3
- import log from '../utils/log';
4
- import { getInfo } from './nebula';
5
-
6
- describe('nebula service', () => {
7
- beforeEach(async () => {
8
- await cache.clear();
9
- });
10
-
11
- describe('GET /info', () => {
12
- const userKey = '9ea9680f-c810-4693-a981-ca8e732a8a8f';
13
- const publicationDomain = 'www.rb.no';
14
- const browserId = 'fc0bce06-560b-48e4-92f2-840e67178516';
15
-
16
- it('should return user information', async () => {
17
- const response = {
18
- ad_segments: '1022776316,1037513379,1043845105',
19
- ad_segments_user: '1022776316,1037513379,1043845105',
20
- age: 28,
21
- age_user: 28,
22
- birth_year: '1992',
23
- birth_year_user: '1992',
24
- gender: 'M',
25
- gender_user: 'M',
26
- grunnkrets: '19030312',
27
- grunnkrets_user: '19030312',
28
- postcode: '0150',
29
- postcode_user: '0150',
30
- shared_account: false,
31
- shared_account_user: false,
32
- user_grouping_number: '34',
33
- user_grouping_number_user: '34',
34
- };
35
-
36
- fetch.mockResponseOnce(JSON.stringify(response));
37
-
38
- await expect(
39
- getInfo(publicationDomain, browserId, userKey)
40
- ).resolves.toEqual({ extraData: response });
41
-
42
- expect(fetch).toHaveBeenCalledWith(
43
- `https://services.gcloud.api.no/api/nebula/v1/info?domain=${publicationDomain}&browser_id=${browserId}&user_key=${userKey}`
44
- );
45
- });
46
-
47
- it('should fail on runtime validation if gender is boolean', async () => {
48
- fetch.mockResponseOnce(JSON.stringify({ gender: true }));
49
- log.error = jest.fn();
50
-
51
- await expect(
52
- getInfo(userKey, publicationDomain, browserId)
53
- ).rejects.toBeUndefined();
54
- });
55
-
56
- it('should pass on runtime validation if unknown property is given', async () => {
57
- const response = {
58
- fullname: 'ra. dean baskaran',
59
- age: 28,
60
- shared_account: false,
61
- };
62
-
63
- fetch.mockResponseOnce(JSON.stringify(response));
64
-
65
- await expect(
66
- getInfo(userKey, publicationDomain, browserId)
67
- ).resolves.toEqual({ extraData: response });
68
- });
69
- });
70
- });
@@ -1,83 +0,0 @@
1
- import {
2
- Static,
3
- Partial,
4
- Dictionary,
5
- Unknown,
6
- String,
7
- Number,
8
- Boolean,
9
- } from 'runtypes';
10
- import getOrUpdate from '../utils/getOrUpdate';
11
- import { UserAttributes } from '../types';
12
- import log from '../utils/log';
13
-
14
- const InfoSchema = Dictionary(Unknown, String).And(
15
- Partial({
16
- ad_segments: String,
17
- ad_segments_user: String,
18
- amedia_employee: Boolean,
19
- amedia_employee_user: Boolean,
20
- age: Number,
21
- age_user: Number,
22
- birth_year: String,
23
- birth_year_user: String,
24
- gender: String,
25
- gender_user: String,
26
- grunnkrets: String,
27
- grunnkrets_user: String,
28
- postcode: String,
29
- postcode_user: String,
30
- shared_account: Boolean,
31
- shared_account_user: Boolean,
32
- user_grouping_number: String,
33
- user_grouping_number_user: String,
34
- })
35
- );
36
-
37
- const getNebulaData = (
38
- publicationDomain: string,
39
- browserId: string,
40
- trackingKey?: string
41
- ) => {
42
- const url = new URL('https://services.gcloud.api.no/api/nebula/v1/info');
43
- url.searchParams.set('domain', publicationDomain);
44
- url.searchParams.set('browser_id', browserId);
45
- if (trackingKey) {
46
- /**
47
- * Legacy alert!
48
- * Tracking key (what we use to track what the user is doing) was previously called user_key. This caused confusion
49
- * with user_uuid (which is the real user id). user_key was since renamed
50
- * to tracking_key to
51
- * better separate the two, but nebula still likes the old name
52
- */
53
- url.searchParams.set('user_key', trackingKey);
54
- }
55
- return fetch(url.href)
56
- .then((response) => response.json())
57
- .then((json) => {
58
- try {
59
- return {
60
- ttl: 1000 * 60 * 60 * 5, // Cache 5 mins
61
- data: InfoSchema.check(json),
62
- };
63
- } catch (error) {
64
- log.error(error, { json });
65
- throw error;
66
- }
67
- });
68
- };
69
-
70
- const mapNebulaToUserData = (
71
- data: Static<typeof InfoSchema>
72
- ): Pick<UserAttributes, 'extraData'> => ({
73
- extraData: data,
74
- });
75
-
76
- export const getInfo = (
77
- publicationDomain: string,
78
- browserId: string,
79
- trackingKey?: string
80
- ): Promise<Pick<UserAttributes, 'extraData'>> =>
81
- getOrUpdate('getNebulaInfo', InfoSchema, () =>
82
- getNebulaData(publicationDomain, browserId, trackingKey)
83
- ).then(mapNebulaToUserData);