@whotracksme/reporting 5.1.17

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 (179) hide show
  1. package/.editorconfig +12 -0
  2. package/.eslintignore +3 -0
  3. package/.eslintrc +16 -0
  4. package/.github/workflows/release.yml +34 -0
  5. package/.github/workflows/tests.yml +20 -0
  6. package/.prettierrc +9 -0
  7. package/.tool-versions +1 -0
  8. package/CHANGELOG.md +795 -0
  9. package/LICENSE +373 -0
  10. package/README.md +1 -0
  11. package/communication/README.md +11 -0
  12. package/communication/example/index.js +43 -0
  13. package/communication/example/manifest.json +16 -0
  14. package/communication/karma.conf.cjs +19 -0
  15. package/communication/package.json +52 -0
  16. package/communication/rollup.common-config.cjs +17 -0
  17. package/communication/rollup.config.cjs +10 -0
  18. package/communication/src/encoding.js +54 -0
  19. package/communication/src/errors.js +84 -0
  20. package/communication/src/index.js +76 -0
  21. package/communication/src/logger.js +41 -0
  22. package/communication/src/padding.js +60 -0
  23. package/communication/src/proxied-http.js +231 -0
  24. package/communication/src/server-public-key-accessor.js +123 -0
  25. package/communication/src/timestamps.js +37 -0
  26. package/communication/src/trusted-clock.js +58 -0
  27. package/communication/src/utils.js +28 -0
  28. package/communication/src/zlib.js +17 -0
  29. package/communication/test/helpers/in-memory-database.js +43 -0
  30. package/communication/test/server-public-key-accessor.spec.js +135 -0
  31. package/communication/test/utils.spec.js +43 -0
  32. package/package.json +50 -0
  33. package/reporting/TODO.md +2 -0
  34. package/reporting/assets/request/bloom_filter.dat +0 -0
  35. package/reporting/assets/request/update.json +1 -0
  36. package/reporting/example/content.js +11 -0
  37. package/reporting/example/index.js +132 -0
  38. package/reporting/example/inspector/index.html +17 -0
  39. package/reporting/example/inspector/index.js +27 -0
  40. package/reporting/example/manifests/chromium.json +37 -0
  41. package/reporting/example/manifests/firefox.json +35 -0
  42. package/reporting/example/rules.json +62 -0
  43. package/reporting/example/setup.js +1 -0
  44. package/reporting/example/tests/test1.html +10 -0
  45. package/reporting/karma.conf.cjs +22 -0
  46. package/reporting/package.json +63 -0
  47. package/reporting/rollup.common-config.cjs +19 -0
  48. package/reporting/rollup.config.cjs +20 -0
  49. package/reporting/src/LRU.js +149 -0
  50. package/reporting/src/activity-estimator.js +298 -0
  51. package/reporting/src/alive-check.js +139 -0
  52. package/reporting/src/alive-message-generator.js +142 -0
  53. package/reporting/src/bloom-filters.js +345 -0
  54. package/reporting/src/country-provider.js +295 -0
  55. package/reporting/src/cyrb53.js +32 -0
  56. package/reporting/src/digest.js +33 -0
  57. package/reporting/src/doublefetch-page-handler.js +548 -0
  58. package/reporting/src/duplicate-detector.js +233 -0
  59. package/reporting/src/errors.js +84 -0
  60. package/reporting/src/event-listener-queue.js +121 -0
  61. package/reporting/src/fixed-size-cache.js +63 -0
  62. package/reporting/src/hash-detector.js +1526 -0
  63. package/reporting/src/html-parser.js +17 -0
  64. package/reporting/src/http.js +265 -0
  65. package/reporting/src/index.js +14 -0
  66. package/reporting/src/job-scheduler.js +912 -0
  67. package/reporting/src/logger.js +121 -0
  68. package/reporting/src/md5.js +334 -0
  69. package/reporting/src/message-sender.js +51 -0
  70. package/reporting/src/network.js +140 -0
  71. package/reporting/src/new-page-approver.js +119 -0
  72. package/reporting/src/page-aggregator.js +185 -0
  73. package/reporting/src/page-quorum-check-handler.js +200 -0
  74. package/reporting/src/page-structure.js +136 -0
  75. package/reporting/src/pagedb.js +671 -0
  76. package/reporting/src/pages.js +1798 -0
  77. package/reporting/src/patterns-updater.js +310 -0
  78. package/reporting/src/patterns.js +416 -0
  79. package/reporting/src/persisted-bitarray.js +265 -0
  80. package/reporting/src/persisted-hashes.js +189 -0
  81. package/reporting/src/quorum-checker.js +327 -0
  82. package/reporting/src/random.js +39 -0
  83. package/reporting/src/reporting.js +290 -0
  84. package/reporting/src/request/config.js +116 -0
  85. package/reporting/src/request/content-script.js +77 -0
  86. package/reporting/src/request/database.js +147 -0
  87. package/reporting/src/request/dnt.js +24 -0
  88. package/reporting/src/request/hash.js +101 -0
  89. package/reporting/src/request/index.js +874 -0
  90. package/reporting/src/request/page-telemetry.js +42 -0
  91. package/reporting/src/request/qs-whitelist2.js +247 -0
  92. package/reporting/src/request/resources/prob.js +601 -0
  93. package/reporting/src/request/steps/block-rules.js +40 -0
  94. package/reporting/src/request/steps/check-context.js +37 -0
  95. package/reporting/src/request/steps/cookie-context.js +209 -0
  96. package/reporting/src/request/steps/oauth-detector.js +101 -0
  97. package/reporting/src/request/steps/page-logger.js +177 -0
  98. package/reporting/src/request/steps/redirect-tagger.js +75 -0
  99. package/reporting/src/request/steps/subdomain-check.js +34 -0
  100. package/reporting/src/request/steps/token-checker/index.js +189 -0
  101. package/reporting/src/request/steps/token-checker/token-domain.js +129 -0
  102. package/reporting/src/request/steps/token-examiner.js +182 -0
  103. package/reporting/src/request/steps/token-telemetry/cached-entry-pipeline.js +210 -0
  104. package/reporting/src/request/steps/token-telemetry/index.js +234 -0
  105. package/reporting/src/request/steps/token-telemetry/key-pipeline.js +109 -0
  106. package/reporting/src/request/steps/token-telemetry/token-pipeline.js +105 -0
  107. package/reporting/src/request/time.js +73 -0
  108. package/reporting/src/request/utils/bloom-filter-packed.js +107 -0
  109. package/reporting/src/request/utils/chrome-storage-map.js +282 -0
  110. package/reporting/src/request/utils/subject.js +37 -0
  111. package/reporting/src/request/utils/temp-set.js +56 -0
  112. package/reporting/src/request/utils/tlds.js +55 -0
  113. package/reporting/src/request/utils.js +41 -0
  114. package/reporting/src/request-reporter.js +111 -0
  115. package/reporting/src/sanitizer.js +519 -0
  116. package/reporting/src/search-extractor.js +338 -0
  117. package/reporting/src/self-check.js +105 -0
  118. package/reporting/src/seq-executor.js +43 -0
  119. package/reporting/src/session-storage.js +399 -0
  120. package/reporting/src/url-analyzer.js +161 -0
  121. package/reporting/src/url-cleaner.js +60 -0
  122. package/reporting/src/utils/pacemaker.js +279 -0
  123. package/reporting/src/utils/url.js +114 -0
  124. package/reporting/src/utils.js +345 -0
  125. package/reporting/src/webrequest-pipeline/cname-uncloak.js +110 -0
  126. package/reporting/src/webrequest-pipeline/index.js +287 -0
  127. package/reporting/src/webrequest-pipeline/logger.js +14 -0
  128. package/reporting/src/webrequest-pipeline/page-store.js +282 -0
  129. package/reporting/src/webrequest-pipeline/page.js +140 -0
  130. package/reporting/src/webrequest-pipeline/pipeline.js +249 -0
  131. package/reporting/src/webrequest-pipeline/utils/webrequest.js +113 -0
  132. package/reporting/src/webrequest-pipeline/webrequest-context.js +153 -0
  133. package/reporting/test/README.md +2 -0
  134. package/reporting/test/activity-estimator.spec.js +356 -0
  135. package/reporting/test/alive-check.spec.js +156 -0
  136. package/reporting/test/alive-message-generator.spec.js +186 -0
  137. package/reporting/test/country-provider.spec.js +263 -0
  138. package/reporting/test/doublefetch-page-handler.spec.js +818 -0
  139. package/reporting/test/duplicate-detector.spec.js +689 -0
  140. package/reporting/test/helpers/dom-parsers.js +41 -0
  141. package/reporting/test/helpers/fake-session-storage.js +69 -0
  142. package/reporting/test/helpers/fast-check-utils.js +28 -0
  143. package/reporting/test/helpers/fetch-mock.js +57 -0
  144. package/reporting/test/helpers/in-memory-database.js +14 -0
  145. package/reporting/test/helpers/memory-map.js +72 -0
  146. package/reporting/test/helpers/pagedb-mocks.js +41 -0
  147. package/reporting/test/index.js +47 -0
  148. package/reporting/test/job-scheduler.spec.js +691 -0
  149. package/reporting/test/network.spec.js +72 -0
  150. package/reporting/test/page-aggregator.spec.js +104 -0
  151. package/reporting/test/page-quorum-check-handler.spec.js +86 -0
  152. package/reporting/test/pagedb.spec.js +250 -0
  153. package/reporting/test/pages.spec.js +693 -0
  154. package/reporting/test/patterns-updater.spec.js +446 -0
  155. package/reporting/test/patterns.spec.js +751 -0
  156. package/reporting/test/persisted-hashes.spec.js +169 -0
  157. package/reporting/test/reporting.spec.js +205 -0
  158. package/reporting/test/request/database.spec.js +59 -0
  159. package/reporting/test/request/hash.spec.js +108 -0
  160. package/reporting/test/request/index.spec.js +378 -0
  161. package/reporting/test/request/qs-whitelist2.spec.js +189 -0
  162. package/reporting/test/request/steps/check-context.spec.js +51 -0
  163. package/reporting/test/request/steps/oauth-detector.spec.js +339 -0
  164. package/reporting/test/request/test-pages.js +1246 -0
  165. package/reporting/test/request/utils/bloom-filter-packed.spec.js +37 -0
  166. package/reporting/test/request/utils/chrome-storage-map.spec.js +28 -0
  167. package/reporting/test/request/utils/tldts.spec.js +62 -0
  168. package/reporting/test/request/utils.spec.js +168 -0
  169. package/reporting/test/sanitizer.spec.js +1087 -0
  170. package/reporting/test/search-extractor.spec.js +590 -0
  171. package/reporting/test/seq-executor.spec.js +158 -0
  172. package/reporting/test/session-storage.spec.js +400 -0
  173. package/reporting/test/setup.js +24 -0
  174. package/reporting/test/url-analyzer.spec.js +451 -0
  175. package/reporting/test/url-cleaner.spec.js +102 -0
  176. package/reporting/test/utils/pacemaker.spec.js +222 -0
  177. package/reporting/test/utils/url.spec.js +660 -0
  178. package/reporting/test/utils.spec.js +299 -0
  179. package/reporting/test/webrequest-pipeline/pipeline.spec.js +251 -0
@@ -0,0 +1,693 @@
1
+ /**
2
+ * WhoTracks.Me
3
+ * https://whotracks.me/
4
+ *
5
+ * Copyright 2017-present Ghostery GmbH. All rights reserved.
6
+ *
7
+ * This Source Code Form is subject to the terms of the Mozilla Public
8
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
9
+ * file, You can obtain one at http://mozilla.org/MPL/2.0
10
+ */
11
+
12
+ import { expect } from 'chai';
13
+
14
+ import Pages, { stripLazyVars, CANCEL_LAZY_VAR } from '../src/pages.js';
15
+ import UrlAnalyzer from '../src/url-analyzer.js';
16
+ import SessionStorageWrapper from '../src/session-storage.js';
17
+ import Patterns from '../src/patterns.js';
18
+
19
+ class ListenerMock {
20
+ constructor() {
21
+ this._listeners = new Set();
22
+ }
23
+
24
+ addListener(handler) {
25
+ this._listeners.add(handler);
26
+ }
27
+
28
+ removeListener(handler) {
29
+ this._listeners.delete(handler);
30
+ }
31
+
32
+ hasListener(handler) {
33
+ return this._listeners.has(handler);
34
+ }
35
+
36
+ hasListeners() {
37
+ return this._listeners.size > 0;
38
+ }
39
+
40
+ dispatch(...args) {
41
+ this._listeners.forEach((handler) => handler(...args));
42
+ }
43
+ }
44
+
45
+ function completeListenersApi() {
46
+ return {
47
+ tabs: [
48
+ 'onZoomChange',
49
+ 'onReplaced',
50
+ 'onRemoved',
51
+ 'onAttached',
52
+ 'onDetached',
53
+ 'onHighlighted',
54
+ 'onActivated',
55
+ 'onMoved',
56
+ 'onUpdated',
57
+ 'onCreated',
58
+ ],
59
+ webNavigation: [
60
+ 'onHistoryStateUpdated',
61
+ 'onTabReplaced',
62
+ 'onReferenceFragmentUpdated',
63
+ 'onCreatedNavigationTarget',
64
+ 'onErrorOccurred',
65
+ 'onCompleted',
66
+ 'onDOMContentLoaded',
67
+ 'onCommitted',
68
+ 'onBeforeNavigate',
69
+ ],
70
+ webRequest: [
71
+ 'onErrorOccurred',
72
+ 'onCompleted',
73
+ 'onBeforeRedirect',
74
+ 'onResponseStarted',
75
+ 'onAuthRequired',
76
+ 'onHeadersReceived',
77
+ 'onSendHeaders',
78
+ 'onBeforeSendHeaders',
79
+ 'onBeforeRequest',
80
+ ],
81
+ windows: ['onBoundsChanged', 'onCreated', 'onFocusChanged', 'onRemoved'],
82
+ };
83
+ }
84
+
85
+ class ChromeApiMock {
86
+ constructor({ listeners = completeListenersApi() } = {}) {
87
+ this._listeners = listeners;
88
+ for (const [api, events] of Object.entries(listeners)) {
89
+ this[api] = this[api] || {};
90
+ for (const event of events) {
91
+ this[api][event] = new ListenerMock();
92
+ }
93
+ }
94
+
95
+ const tabQueryStub = async () => [];
96
+ this.tabs = this.tabs || {};
97
+ this.tabs.query = this.tabs.query || tabQueryStub;
98
+ }
99
+
100
+ _ensureAllListenersRemoved() {
101
+ for (const [api, events] of Object.entries(this._listeners)) {
102
+ const listeners = events.filter((x) => this[api][x].hasListeners());
103
+ if (listeners.length > 0) {
104
+ throw new Error(
105
+ `Forgot to clean up listener: chrome.${api} still has the following listeners: ${listeners}`,
106
+ );
107
+ }
108
+ }
109
+ }
110
+
111
+ async replay(uut, initialState, recordedEvents) {
112
+ if (initialState.openTabs) {
113
+ uut.openTabs = new Map(initialState.openTabs);
114
+ }
115
+ for (const { api, event, args } of recordedEvents) {
116
+ this[api][event].dispatch(...args);
117
+ }
118
+ }
119
+ }
120
+
121
+ function newUrlAnalyzer() {
122
+ return new UrlAnalyzer(new Patterns());
123
+ }
124
+
125
+ function stubNewPageApprover() {
126
+ return {
127
+ async markAsPrivate() {},
128
+ };
129
+ }
130
+
131
+ function newInMemorySessionStore() {
132
+ // forces an in-memory fallback session storage
133
+ return new SessionStorageWrapper({ sessionApi: null });
134
+ }
135
+
136
+ async function fetchJson(url) {
137
+ const response = await fetch(url);
138
+ if (!response.ok) {
139
+ throw new Error(`Unable to reach endpoint: ${url}: ${response.statusText}`);
140
+ }
141
+ return response.json();
142
+ }
143
+
144
+ async function loadTestFixtures(url) {
145
+ const { links } = await fetchJson(url);
146
+ expect(links).to.be.an('object');
147
+ const expectedOrigin = new URL(url).origin;
148
+ for (const fixtureUrl of Object.values(links)) {
149
+ expect(new URL(fixtureUrl).origin).to.eql(expectedOrigin);
150
+ }
151
+ return Object.entries(links).map(([name, link]) => ({
152
+ name,
153
+ scenarioLink: link,
154
+ }));
155
+ }
156
+
157
+ describe('#Pages', function () {
158
+ describe('without providing a full implementation of the chrome API', function () {
159
+ it('should load and unload', async function () {
160
+ const pages = new Pages({
161
+ config: {},
162
+ urlAnalyzer: newUrlAnalyzer(),
163
+ newPageApprover: stubNewPageApprover(),
164
+ pageSessionStore: newInMemorySessionStore(),
165
+ });
166
+ await pages.init();
167
+ pages.unload();
168
+ });
169
+ });
170
+
171
+ describe('with a complete chrome API stub', function () {
172
+ let uut;
173
+ let chromeApiMock;
174
+ let urlAnalyzer;
175
+
176
+ function runScenario(name, { notes, expectations, events }) {
177
+ const { initialState, recorded } = events || {};
178
+ try {
179
+ expect(notes, '<notes>').to.be.a('string');
180
+ expect(expectations, '<expectations>').to.be.an('object');
181
+ expect(expectations).to.contain.any.key('expectedTabs', 'activeTab');
182
+ expect(initialState, '<events.initialState>').to.be.an('object');
183
+ expect(recorded, '<events.recorded>').to.be.an('array');
184
+ } catch (e) {
185
+ e.message = `Broken scenario '${name}' detected (${e.message})`;
186
+ throw e;
187
+ }
188
+
189
+ chromeApiMock.replay(uut, initialState, recorded);
190
+ const state = uut.describe();
191
+ try {
192
+ const { expectedTabs, activeTab } = expectations;
193
+ if (expectedTabs) {
194
+ expect(state?.openTabs).to.have.keys(Object.keys(expectedTabs));
195
+ for (const [tabId, data] of Object.entries(expectedTabs)) {
196
+ expect(state.openTabs[tabId]).to.deep.include(data);
197
+ }
198
+ }
199
+
200
+ const pp = (x) => JSON.stringify(x, null, 2);
201
+ if (activeTab === 'none') {
202
+ if (state.activeTab !== undefined) {
203
+ expect.fail(
204
+ `Expected no active tab, but got:\n${pp(state.activeTab)}`,
205
+ );
206
+ }
207
+ } else if (activeTab) {
208
+ if (state.activeTab === undefined) {
209
+ expect.fail(
210
+ `No open tab, but expected the to be open: ${pp(activeTab)}`,
211
+ );
212
+ }
213
+ for (const [key, value] of Object.entries(activeTab)) {
214
+ expect(state.activeTab[key]).to.eql(
215
+ value,
216
+ 'Active tabs do not match:\nExpected the following values...\n' +
217
+ pp(activeTab) +
218
+ '\n\n... to be present in\n' +
219
+ pp(state.activeTab),
220
+ );
221
+ }
222
+ }
223
+ } catch (e) {
224
+ e.results = state;
225
+ throw e;
226
+ }
227
+ }
228
+
229
+ function initMocks() {
230
+ tryDestroyOldMocks();
231
+
232
+ chromeApiMock = new ChromeApiMock();
233
+ const config = {
234
+ pages: {
235
+ chrome: chromeApiMock,
236
+ },
237
+ };
238
+ urlAnalyzer = newUrlAnalyzer();
239
+ uut = new Pages({
240
+ config,
241
+ urlAnalyzer,
242
+ newPageApprover: stubNewPageApprover(),
243
+ pageSessionStore: newInMemorySessionStore(),
244
+ });
245
+ }
246
+
247
+ function destroyMocks() {
248
+ try {
249
+ uut.unload();
250
+ chromeApiMock._ensureAllListenersRemoved();
251
+ } finally {
252
+ uut = null;
253
+ chromeApiMock = null;
254
+ urlAnalyzer = null;
255
+ }
256
+ }
257
+
258
+ function tryDestroyOldMocks() {
259
+ if (uut) {
260
+ try {
261
+ destroyMocks();
262
+ } catch (e) {
263
+ console.warn('Ignore error while cleaning up old mocks', e);
264
+ }
265
+ }
266
+ }
267
+
268
+ beforeEach(initMocks);
269
+ afterEach(destroyMocks);
270
+
271
+ describe('should load and unload', function () {
272
+ it('without waiting for fully initialization', async function () {
273
+ await uut.init();
274
+ uut.unload();
275
+ chromeApiMock._ensureAllListenersRemoved();
276
+ });
277
+
278
+ it('when waiting for fully initialization', async function () {
279
+ await uut.init();
280
+ await uut._ready;
281
+ uut.unload();
282
+ chromeApiMock._ensureAllListenersRemoved();
283
+ });
284
+ });
285
+
286
+ describe('when fully initialized', function () {
287
+ beforeEach(async () => {
288
+ await uut.init();
289
+ await uut._ready;
290
+ });
291
+
292
+ it('should detect an opened page: new tab, followed by a page visit', async function () {
293
+ chromeApiMock.tabs.onCreated.dispatch({
294
+ active: true,
295
+ audible: false,
296
+ autoDiscardable: true,
297
+ discarded: false,
298
+ groupId: -1,
299
+ height: 1069,
300
+ highlighted: true,
301
+ id: 1182717827,
302
+ incognito: false,
303
+ index: 1,
304
+ mutedInfo: {
305
+ muted: false,
306
+ },
307
+ openerTabId: 1182717595,
308
+ pendingUrl: 'chrome://newtab/',
309
+ pinned: false,
310
+ selected: true,
311
+ status: 'loading',
312
+ title: 'New Tab',
313
+ url: '',
314
+ width: 729,
315
+ windowId: 1182717594,
316
+ });
317
+ chromeApiMock.tabs.onActivated.dispatch({
318
+ tabId: 1182717827,
319
+ windowId: 1182717594,
320
+ });
321
+ chromeApiMock.tabs.onUpdated.dispatch(
322
+ 1182717827,
323
+ {
324
+ status: 'loading',
325
+ url: 'chrome://newtab/',
326
+ },
327
+ {
328
+ active: true,
329
+ audible: false,
330
+ autoDiscardable: true,
331
+ discarded: false,
332
+ groupId: -1,
333
+ height: 1069,
334
+ highlighted: true,
335
+ id: 1182717827,
336
+ incognito: false,
337
+ index: 1,
338
+ mutedInfo: {
339
+ muted: false,
340
+ },
341
+ openerTabId: 1182717595,
342
+ pinned: false,
343
+ selected: true,
344
+ status: 'loading',
345
+ title: 'New Tab',
346
+ url: 'chrome://newtab/',
347
+ width: 729,
348
+ windowId: 1182717594,
349
+ },
350
+ );
351
+ chromeApiMock.tabs.onUpdated.dispatch(
352
+ 1182717827,
353
+ {
354
+ status: 'complete',
355
+ },
356
+ {
357
+ active: true,
358
+ audible: false,
359
+ autoDiscardable: true,
360
+ discarded: false,
361
+ favIconUrl: '',
362
+ groupId: -1,
363
+ height: 1069,
364
+ highlighted: true,
365
+ id: 1182717827,
366
+ incognito: false,
367
+ index: 1,
368
+ mutedInfo: {
369
+ muted: false,
370
+ },
371
+ openerTabId: 1182717595,
372
+ pinned: false,
373
+ selected: true,
374
+ status: 'complete',
375
+ title: 'New Tab',
376
+ url: 'chrome://newtab/',
377
+ width: 729,
378
+ windowId: 1182717594,
379
+ },
380
+ );
381
+
382
+ // verify: the new tab should be open now
383
+ expect(uut.activeTab.tabId).to.eql(1182717827);
384
+ expect(uut.openTabs._map).to.have.keys(1182717827);
385
+ expect(uut.openTabs.get(1182717827)).to.include({
386
+ status: 'complete',
387
+ title: 'New Tab',
388
+ url: 'chrome://newtab/',
389
+ });
390
+
391
+ chromeApiMock.tabs.onUpdated.dispatch(
392
+ 1182717827,
393
+ {
394
+ status: 'loading',
395
+ url: 'http://example.test/',
396
+ },
397
+ {
398
+ active: true,
399
+ audible: false,
400
+ autoDiscardable: true,
401
+ discarded: false,
402
+ groupId: -1,
403
+ height: 1069,
404
+ highlighted: true,
405
+ id: 1182717827,
406
+ incognito: false,
407
+ index: 1,
408
+ mutedInfo: {
409
+ muted: false,
410
+ },
411
+ openerTabId: 1182717595,
412
+ pinned: false,
413
+ selected: true,
414
+ status: 'loading',
415
+ title: 'example.test',
416
+ url: 'http://example.test/',
417
+ width: 729,
418
+ windowId: 1182717594,
419
+ },
420
+ );
421
+ chromeApiMock.tabs.onUpdated.dispatch(
422
+ 1182717827,
423
+ {
424
+ status: 'complete',
425
+ },
426
+ {
427
+ active: true,
428
+ audible: false,
429
+ autoDiscardable: true,
430
+ discarded: false,
431
+ groupId: -1,
432
+ height: 1069,
433
+ highlighted: true,
434
+ id: 1182717827,
435
+ incognito: false,
436
+ index: 1,
437
+ mutedInfo: {
438
+ muted: false,
439
+ },
440
+ openerTabId: 1182717595,
441
+ pinned: false,
442
+ selected: true,
443
+ status: 'complete',
444
+ title: 'example.test',
445
+ url: 'http://example.test/',
446
+ width: 729,
447
+ windowId: 1182717594,
448
+ },
449
+ );
450
+
451
+ // verify: the new page should be detected now
452
+ expect(uut.activeTab.tabId).to.eql(1182717827);
453
+ expect(uut.openTabs._map).to.have.keys(1182717827);
454
+ expect(uut.openTabs.get(1182717827)).to.include({
455
+ status: 'complete',
456
+ title: 'example.test',
457
+ url: 'http://example.test/',
458
+ });
459
+ });
460
+
461
+ // This are optional tests that can be enabled if the REPLAY_FIXTURES_URL
462
+ // environment variable is defined. Karma lacks access to the filesystem,
463
+ // but we can fetch fixtures over the network.
464
+ //
465
+ // eslint-disable-next-line no-undef
466
+ const testFixturesUrl = __karma__.config.REPLAY_FIXTURES_URL;
467
+ if (testFixturesUrl) {
468
+ it('passes remote tests', async function () {
469
+ this.timeout(10000000);
470
+ const maxRequests = 3;
471
+ const fixtures = await loadTestFixtures(testFixturesUrl);
472
+ const fixtures2 = [...fixtures];
473
+ const prefetchScenario = () => {
474
+ const next = fixtures2.shift();
475
+ if (next) {
476
+ next.pendingFixture = fetchJson(next.scenarioLink);
477
+ }
478
+ };
479
+ for (let i = 0; i < maxRequests - 1; i += 1) {
480
+ prefetchScenario();
481
+ }
482
+ let testsPassed = [];
483
+ let testsFailed = [];
484
+ try {
485
+ console.log(
486
+ `Running test fixtures: ${fixtures.length} tests found`,
487
+ );
488
+ while (fixtures.length > 0) {
489
+ prefetchScenario();
490
+ initMocks();
491
+ await uut.init();
492
+ await uut.blockUntilFullInit();
493
+
494
+ const { name, pendingFixture } = fixtures.shift();
495
+ const fixture = await pendingFixture;
496
+ try {
497
+ if (!fixture?.scenario) {
498
+ throw new Error(
499
+ 'Broken test setup: expected a "scenario" field',
500
+ );
501
+ }
502
+ runScenario(name, fixture.scenario);
503
+ testsPassed.push(name);
504
+ console.log(`test ${name}: PASSED`);
505
+ } catch (e) {
506
+ testsFailed.push({ name, error: e });
507
+ e.message = `Test fixture <${name}> failed: ${e}`;
508
+ console.error(e);
509
+ if (e.results) {
510
+ console.log(`This was the scenario (${name}):\n
511
+ ----------------------------------------------------------------------
512
+ ${JSON.stringify(fixture.scenario.expectations, null, 2)}
513
+ ----------------------------------------------------------------------
514
+
515
+ But this was the actual state:\n
516
+ ----------------------------------------------------------------------
517
+ ${JSON.stringify(e.results, null, 2)}
518
+ ----------------------------------------------------------------------
519
+ `);
520
+ }
521
+ }
522
+ }
523
+ if (testsFailed.length > 0) {
524
+ throw testsFailed[0].error;
525
+ }
526
+ } finally {
527
+ const passed = testsPassed.length;
528
+ const failed = testsFailed.length;
529
+ const total = testsPassed.length + testsFailed.length;
530
+ if (total > 0) {
531
+ const ratio = ((100 * passed) / total).toFixed(2);
532
+ console.log(
533
+ `
534
+ ****************** remote test results *************
535
+ ${total} tests run: ${passed} passed, ${failed} failed (${ratio}% passed)
536
+ ****************************************************
537
+ `,
538
+ );
539
+ if (failed > 0) {
540
+ console.warn(
541
+ `The following tests failed:\n${testsFailed
542
+ .map((x) => `* ${x.error}`)
543
+ .join('\n')}\n\n`,
544
+ );
545
+ }
546
+ }
547
+ }
548
+ });
549
+ }
550
+ });
551
+ });
552
+ });
553
+
554
+ describe('#stripLazyVars', function () {
555
+ describe('should not modify object without lazy vars', async function () {
556
+ for (const [pos, value] of Object.entries([
557
+ null,
558
+ undefined,
559
+ 0,
560
+ 1,
561
+ 1.23,
562
+ NaN,
563
+ Infinity,
564
+ 'foo',
565
+ [],
566
+ [1, 2, 3],
567
+ [[]],
568
+ new Date(0),
569
+ { foo: 1 },
570
+ { foo: 1, bar: { baz: 2 } },
571
+ { foo: NaN },
572
+ ])) {
573
+ it(`- example ${pos}: ${JSON.stringify(value)}`, async function () {
574
+ expect(stripLazyVars(value)).to.eql(value);
575
+ });
576
+ }
577
+ });
578
+
579
+ describe('should should remove pending lazy vars', async function () {
580
+ for (const [pos, { before, after }] of Object.entries([
581
+ {
582
+ before: {
583
+ pendingLazyVar: {
584
+ _pending: {},
585
+ },
586
+ },
587
+ after: {},
588
+ },
589
+ {
590
+ before: {
591
+ pendingLazyVar: {
592
+ _pending: {},
593
+ },
594
+ },
595
+ after: {},
596
+ },
597
+ ])) {
598
+ it(`- example ${pos}: ${JSON.stringify(before)}`, async function () {
599
+ expect(stripLazyVars(before)).to.eql(after);
600
+ });
601
+ }
602
+ });
603
+
604
+ describe('should should remove cancelled lazy vars', async function () {
605
+ for (const [pos, { before, after }] of Object.entries([
606
+ {
607
+ before: {
608
+ cancelledLazyVar: {
609
+ _pending: {
610
+ result: CANCEL_LAZY_VAR,
611
+ },
612
+ },
613
+ },
614
+ after: {},
615
+ },
616
+ {
617
+ before: {
618
+ foo: {
619
+ cancelledLazyVar: {
620
+ _pending: {
621
+ result: CANCEL_LAZY_VAR,
622
+ },
623
+ },
624
+ },
625
+ },
626
+ after: {
627
+ foo: {},
628
+ },
629
+ },
630
+ ])) {
631
+ it(`- example ${pos}: ${JSON.stringify(before)}`, async function () {
632
+ expect(stripLazyVars(before)).to.eql(after);
633
+ });
634
+ }
635
+ });
636
+
637
+ describe('should should inline resolved lazy vars', async function () {
638
+ for (const [pos, { before, after }] of Object.entries([
639
+ {
640
+ before: {
641
+ resolvedLazyVar: {
642
+ _pending: {},
643
+ result: 'foo',
644
+ },
645
+ },
646
+ after: {
647
+ resolvedLazyVar: 'foo',
648
+ },
649
+ },
650
+ {
651
+ before: {
652
+ foo: {
653
+ bar: {
654
+ _pending: {},
655
+ result: {
656
+ baz: 42,
657
+ },
658
+ },
659
+ },
660
+ },
661
+ after: {
662
+ foo: {
663
+ bar: {
664
+ baz: 42,
665
+ },
666
+ },
667
+ },
668
+ },
669
+ {
670
+ before: {
671
+ resolvedLazyVar: {
672
+ _pending: {},
673
+ result: {
674
+ nestedLazyVar: {
675
+ _pending: {},
676
+ result: 'foo',
677
+ },
678
+ },
679
+ },
680
+ },
681
+ after: {
682
+ resolvedLazyVar: {
683
+ nestedLazyVar: 'foo',
684
+ },
685
+ },
686
+ },
687
+ ])) {
688
+ it(`- example ${pos}: ${JSON.stringify(before)}`, async function () {
689
+ expect(stripLazyVars(before)).to.eql(after);
690
+ });
691
+ }
692
+ });
693
+ });