@whotracksme/reporting 8.0.0 β†’ 8.0.1

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/.eslintignore CHANGED
@@ -1,3 +1,4 @@
1
1
  **/*.bundle.js
2
2
  **/trackers-preview-generated.js
3
3
  **/scripts/**/*.js
4
+ reporting/example/offscreen/**
package/CHANGELOG.md CHANGED
@@ -1,3 +1,15 @@
1
+ # v8.0.1 (Tue Apr 21 2026)
2
+
3
+ #### πŸ› Bug Fix
4
+
5
+ - Developer tooling for the request pipeline [#195](https://github.com/whotracksme/webextension-packages/pull/195) ([@chrmod](https://github.com/chrmod))
6
+
7
+ #### Authors: 1
8
+
9
+ - Krzysztof Modras ([@chrmod](https://github.com/chrmod))
10
+
11
+ ---
12
+
1
13
  # v8.0.0 (Thu Apr 16 2026)
2
14
 
3
15
  #### πŸ’₯ Breaking Change
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whotracksme/reporting",
3
- "version": "8.0.0",
3
+ "version": "8.0.1",
4
4
  "type": "module",
5
5
  "description": "",
6
6
  "scripts": {
@@ -0,0 +1,26 @@
1
+ # Reporting
2
+
3
+ ## Development setup
4
+
5
+ Run `npm ci` in the project root.
6
+
7
+ - Build: `npm --workspace=reporting run build`
8
+ - Watch: `npm --workspace=reporting run watch`
9
+
10
+ ## Running the example extension
11
+
12
+ Interactive (DevTools + web-ext live reload):
13
+
14
+ ```
15
+ npm --workspace=reporting start # Chromium
16
+ npm --workspace=reporting run start.firefox
17
+ ```
18
+
19
+ For a scripted runner with log capture and an HTTP control surface,
20
+ see `example/README.md`.
21
+
22
+ ## Tests
23
+
24
+ See `test/README.md` for the two test suites (node-mocha + karma),
25
+ subset scripts, and the snapshot record workflow. Scenario/snapshot
26
+ fixtures are documented in `scenarios/README.md`.
@@ -0,0 +1,65 @@
1
+ # reporting/example
2
+
3
+ Scripted extension runner with log capture. For the interactive
4
+ `web-ext run` loop, see the package-level `../README.md`.
5
+
6
+ ## Usage
7
+
8
+ ```
9
+ node reporting/example/run.mjs --url https://example.com --wait 10
10
+ ```
11
+
12
+ Requires built bundles β€” run `npm --workspace=reporting run build` first.
13
+
14
+ What it does:
15
+
16
+ - Launches Chrome Canary via wdio with `--enable-unsafe-extension-debugging`
17
+ - Installs the unpacked extension via WebDriver BiDi `webExtension.install`
18
+ - Subscribes to BiDi `log.entryAdded` for page + content-script console
19
+ - Attaches puppeteer-core to chromedriver's debug port for service-worker
20
+ console (BiDi doesn't currently forward SW console events)
21
+ - Writes all entries to `logs/run.log`
22
+ - Navigates to each `--url`, waits `--wait` seconds, uninstalls, exits
23
+
24
+ Flags:
25
+
26
+ - `--url <URL>` β€” can be repeated; visited in order
27
+ - `--wait <seconds>` β€” total time to keep the browser open (default `10`)
28
+ - `--headless` β€” run headless (extension registration may differ)
29
+ - `--log-file <path>` β€” override log output path
30
+ - `--keep-open` β€” don't auto-close; exposes the control server (below)
31
+ - `--port <n>` β€” control server port when `--keep-open` (default `7878`)
32
+ - `--browser-version <channel>` β€” `canary` (default), `dev`, `beta`,
33
+ `stable`, or an explicit version
34
+
35
+ ## Control server (`--keep-open`)
36
+
37
+ Drive a long-lived runner without restarting the browser between steps:
38
+
39
+ ```
40
+ POST /navigate {"url": "https://..."} β†’ {url, title}
41
+ POST /eval {"code": "return ...", "target": "page"} β†’ {result}
42
+ POST /eval {"code": "chrome.runtime.id", "target": "sw"} β†’ {result}
43
+ POST /shutdown β†’ {ok: true}, exits
44
+ GET /state β†’ {extensionId, tabs, sw}
45
+ GET /logs/tail?lines=N β†’ {lines: [...]}
46
+ ```
47
+
48
+ - `/eval` page target: `code` is a function body; write `return <expr>`.
49
+ - `/eval` sw target: `code` is an expression evaluated in the SW realm
50
+ (e.g. `"chrome.runtime.id"`, `"await chrome.storage.local.get(null)"`).
51
+ Returns `409` if no SW is currently attached β€” MV3 service workers may
52
+ have idled out; poke it first with a navigation.
53
+
54
+ ## Why Chrome Canary
55
+
56
+ Two reasons stable Chrome doesn't work today:
57
+
58
+ 1. Stable Chrome refuses `--load-extension` as a security hardening (the
59
+ old web-ext path). BiDi `webExtension.install` sidesteps this.
60
+ 2. Chromedriver's BiDi mapper in stable doesn't yet implement
61
+ `webExtension.install` β€” it returns "Method not available". Canary
62
+ (paired with the matching chromedriver wdio auto-fetches) does.
63
+
64
+ When `browserVersion` is `canary` and wdio doesn't find a local Canary
65
+ install, it downloads Chrome for Testing via `@puppeteer/browsers`.
@@ -0,0 +1,2 @@
1
+ *
2
+ !.gitignore
@@ -0,0 +1,288 @@
1
+ import { remote } from 'webdriverio';
2
+ import puppeteer from 'puppeteer-core';
3
+ import http from 'node:http';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { parseArgs } from 'node:util';
6
+ import path from 'node:path';
7
+ import fs from 'node:fs';
8
+
9
+ const { values } = parseArgs({
10
+ options: {
11
+ url: { type: 'string', multiple: true, default: [] },
12
+ wait: { type: 'string', default: '10' },
13
+ headless: { type: 'boolean', default: false },
14
+ 'keep-open': { type: 'boolean', default: false },
15
+ 'log-file': { type: 'string' },
16
+ 'browser-version': { type: 'string', default: 'canary' },
17
+ port: { type: 'string', default: '7878' },
18
+ },
19
+ });
20
+
21
+ const exampleDir = path.dirname(fileURLToPath(import.meta.url));
22
+
23
+ for (const bundle of ['index.bundle.js', 'content.bundle.js']) {
24
+ if (!fs.existsSync(path.join(exampleDir, bundle))) {
25
+ console.error(
26
+ `missing example/${bundle} β€” run \`npm --workspace=reporting run build\` first`,
27
+ );
28
+ process.exit(1);
29
+ }
30
+ }
31
+
32
+ if (!fs.existsSync(path.join(exampleDir, 'manifest.json'))) {
33
+ fs.copyFileSync(
34
+ path.join(exampleDir, 'manifests', 'chromium.json'),
35
+ path.join(exampleDir, 'manifest.json'),
36
+ );
37
+ }
38
+
39
+ const logDir = path.join(exampleDir, 'logs');
40
+ fs.mkdirSync(logDir, { recursive: true });
41
+ const logFile = values['log-file'] || path.join(logDir, 'run.log');
42
+ fs.writeFileSync(logFile, '');
43
+
44
+ function log(source, level, text) {
45
+ const line = `${new Date().toISOString()} [${source}] [${level}] ${text}\n`;
46
+ fs.appendFileSync(logFile, line);
47
+ process.stdout.write(line);
48
+ }
49
+
50
+ function stringifyArg(v) {
51
+ if (v == null) return String(v);
52
+ if (v.type === 'string') return v.value ?? '';
53
+ if (v.type === 'number' || v.type === 'boolean') return String(v.value);
54
+ if (v.type === 'object' || v.type === 'array') return JSON.stringify(v);
55
+ return v.value !== undefined ? String(v.value) : JSON.stringify(v);
56
+ }
57
+
58
+ const chromeArgs = [
59
+ '--no-first-run',
60
+ '--no-default-browser-check',
61
+ '--enable-unsafe-extension-debugging',
62
+ ];
63
+ if (values.headless) chromeArgs.push('--headless=new');
64
+
65
+ log(
66
+ 'runner',
67
+ 'info',
68
+ `launching chrome (browserVersion=${values['browser-version']})`,
69
+ );
70
+
71
+ const browser = await remote({
72
+ logLevel: 'warn',
73
+ capabilities: {
74
+ browserName: 'chrome',
75
+ browserVersion: values['browser-version'],
76
+ 'goog:chromeOptions': { args: chromeArgs },
77
+ webSocketUrl: true,
78
+ },
79
+ });
80
+
81
+ await browser.sessionSubscribe({ events: ['log.entryAdded'] });
82
+ browser.on('log.entryAdded', (entry) => {
83
+ const text = entry.args
84
+ ? entry.args.map(stringifyArg).join(' ')
85
+ : entry.text || '';
86
+ const ctx = entry.source?.context;
87
+ const realm = entry.source?.realm;
88
+ const src = ctx
89
+ ? `page:${ctx.slice(0, 8)}`
90
+ : realm
91
+ ? `realm:${realm.slice(0, 8)}`
92
+ : 'page';
93
+ log(src, entry.level || 'info', text);
94
+ });
95
+
96
+ let extensionId;
97
+ try {
98
+ const result = await browser.webExtensionInstall({
99
+ extensionData: { type: 'path', path: exampleDir },
100
+ });
101
+ extensionId = result.extension;
102
+ log('runner', 'info', `extension installed: ${extensionId}`);
103
+ } catch (err) {
104
+ log('runner', 'error', `webExtension.install failed: ${err.message}`);
105
+ await browser.deleteSession();
106
+ process.exit(1);
107
+ }
108
+
109
+ let swWorker = null;
110
+ const debuggerAddress =
111
+ browser.capabilities['goog:chromeOptions']?.debuggerAddress;
112
+ if (debuggerAddress) {
113
+ try {
114
+ const cdpBrowser = await puppeteer.connect({
115
+ browserURL: `http://${debuggerAddress}`,
116
+ defaultViewport: null,
117
+ });
118
+ const attached = new WeakSet();
119
+ const attachSW = async (target) => {
120
+ if (attached.has(target) || target.type() !== 'service_worker') return;
121
+ attached.add(target);
122
+ try {
123
+ const worker = await target.worker();
124
+ if (!worker) return;
125
+ swWorker = worker;
126
+ worker.on('console', (msg) => log('sw', msg.type(), msg.text()));
127
+ worker.on('error', (err) => log('sw', 'error', err.message));
128
+ log('runner', 'info', `attached SW: ${target.url()}`);
129
+ } catch (err) {
130
+ log('runner', 'warn', `SW attach failed: ${err.message}`);
131
+ }
132
+ };
133
+ for (const t of cdpBrowser.targets()) await attachSW(t);
134
+ cdpBrowser.on('targetcreated', attachSW);
135
+ } catch (err) {
136
+ log('runner', 'warn', `CDP side-channel failed: ${err.message}`);
137
+ }
138
+ } else {
139
+ log('runner', 'warn', 'no debuggerAddress β€” SW logs will not be captured');
140
+ }
141
+
142
+ for (const url of values.url) {
143
+ log('runner', 'info', `navigating: ${url}`);
144
+ try {
145
+ await browser.url(url);
146
+ } catch (err) {
147
+ log('runner', 'error', `navigate ${url} failed: ${err.message}`);
148
+ }
149
+ }
150
+
151
+ const waitMs = Math.max(0, Number(values.wait) * 1000);
152
+
153
+ async function shutdown() {
154
+ if (extensionId) {
155
+ await browser
156
+ .webExtensionUninstall({ extension: extensionId })
157
+ .catch(() => {});
158
+ }
159
+ await browser.deleteSession().catch(() => {});
160
+ }
161
+
162
+ function readJsonBody(req) {
163
+ return new Promise((resolve) => {
164
+ const chunks = [];
165
+ req.on('data', (c) => chunks.push(c));
166
+ req.on('end', () => {
167
+ const raw = Buffer.concat(chunks).toString('utf8');
168
+ if (!raw) return resolve({});
169
+ try {
170
+ resolve(JSON.parse(raw));
171
+ } catch {
172
+ resolve({ _parseError: true });
173
+ }
174
+ });
175
+ });
176
+ }
177
+
178
+ async function handleControl(method, url, body) {
179
+ const p = url.pathname;
180
+
181
+ if (method === 'POST' && p === '/navigate') {
182
+ if (!body.url) return [400, { error: 'missing url' }];
183
+ await browser.url(body.url);
184
+ return [
185
+ 200,
186
+ { url: await browser.getUrl(), title: await browser.getTitle() },
187
+ ];
188
+ }
189
+
190
+ if (method === 'POST' && p === '/eval') {
191
+ if (!body.code) return [400, { error: 'missing code' }];
192
+ if (body.target === 'sw') {
193
+ if (!swWorker) return [409, { error: 'no SW attached' }];
194
+ try {
195
+ const result = await swWorker.evaluate(body.code);
196
+ return [200, { result }];
197
+ } catch (err) {
198
+ return [500, { error: err.message }];
199
+ }
200
+ }
201
+ try {
202
+ const result = await browser.execute(body.code);
203
+ return [200, { result }];
204
+ } catch (err) {
205
+ return [500, { error: err.message }];
206
+ }
207
+ }
208
+
209
+ if (method === 'GET' && p === '/state') {
210
+ const handles = await browser.getWindowHandles();
211
+ const cur = await browser.getWindowHandle();
212
+ const tabs = [];
213
+ for (const h of handles) {
214
+ await browser.switchToWindow(h);
215
+ tabs.push({
216
+ handle: h,
217
+ url: await browser.getUrl(),
218
+ title: await browser.getTitle(),
219
+ });
220
+ }
221
+ await browser.switchToWindow(cur);
222
+ return [
223
+ 200,
224
+ {
225
+ extensionId,
226
+ tabs,
227
+ sw: swWorker ? { url: swWorker.url() } : null,
228
+ },
229
+ ];
230
+ }
231
+
232
+ if (method === 'GET' && p === '/logs/tail') {
233
+ const n = Number(url.searchParams.get('lines')) || 50;
234
+ const content = fs.readFileSync(logFile, 'utf8');
235
+ const lines = content.split('\n').filter(Boolean).slice(-n);
236
+ return [200, { lines }];
237
+ }
238
+
239
+ return [404, { error: 'unknown route' }];
240
+ }
241
+
242
+ let controlServer;
243
+ function startControlServer(port) {
244
+ controlServer = http.createServer(async (req, res) => {
245
+ try {
246
+ const url = new URL(req.url, 'http://localhost');
247
+ const body = req.method === 'POST' ? await readJsonBody(req) : {};
248
+ if (req.method === 'POST' && url.pathname === '/shutdown') {
249
+ res.writeHead(200, { 'Content-Type': 'application/json' });
250
+ res.end(JSON.stringify({ ok: true }));
251
+ setTimeout(async () => {
252
+ await shutdown();
253
+ process.exit(0);
254
+ }, 10);
255
+ return;
256
+ }
257
+ const [status, reply] = await handleControl(req.method, url, body);
258
+ res.writeHead(status, { 'Content-Type': 'application/json' });
259
+ res.end(JSON.stringify(reply));
260
+ } catch (err) {
261
+ res.writeHead(500, { 'Content-Type': 'application/json' });
262
+ res.end(JSON.stringify({ error: err.message }));
263
+ }
264
+ });
265
+ controlServer.listen(port, '127.0.0.1', () => {
266
+ log('runner', 'info', `control on http://127.0.0.1:${port}`);
267
+ log(
268
+ 'runner',
269
+ 'info',
270
+ 'routes: POST /navigate {url}, POST /eval {code,target?}, POST /shutdown, GET /state, GET /logs/tail?lines=N',
271
+ );
272
+ });
273
+ }
274
+
275
+ if (values['keep-open']) {
276
+ startControlServer(Number(values.port));
277
+ log('runner', 'info', 'keeping browser open (ctrl-c to exit)');
278
+ process.on('SIGINT', async () => {
279
+ controlServer?.close();
280
+ await shutdown();
281
+ process.exit(0);
282
+ });
283
+ } else {
284
+ log('runner', 'info', `waiting ${values.wait}s`);
285
+ await new Promise((r) => setTimeout(r, waitMs));
286
+ await shutdown();
287
+ log('runner', 'info', `done, logs at ${logFile}`);
288
+ }
@@ -1,11 +1,12 @@
1
1
  const rollupPreprocessor = require('./rollup.common-config.cjs');
2
2
 
3
3
  module.exports = function (config) {
4
+ const entry = process.env.KARMA_TEST_ENTRY || 'test/index.js';
4
5
  config.set({
5
6
  frameworks: ['mocha', 'chai', 'sinon'],
6
- files: [{ pattern: 'test/index.js', watched: false }],
7
+ files: [{ pattern: entry, watched: false }],
7
8
  preprocessors: {
8
- 'test/index.js': ['rollup'],
9
+ [entry]: ['rollup'],
9
10
  },
10
11
  reporters: ['mocha'],
11
12
  port: 9876,
@@ -5,11 +5,15 @@
5
5
  "scripts": {
6
6
  "start": "cp example/manifests/chromium.json example/manifest.json && web-ext run -s ./example -t chromium",
7
7
  "start.firefox": "cp example/manifests/firefox.json example/manifest.json && web-ext run -s ./example -t firefox-desktop",
8
+ "start.auto": "cp example/manifests/chromium.json example/manifest.json && node example/run.mjs",
8
9
  "build": "rollup -c",
9
10
  "watch": "rollup -c -w",
10
11
  "test.unit": "mocha --file ./test/setup.unit.js './test/**/*.test.js'",
12
+ "test.unit.request": "mocha --file ./test/setup.unit.js './test/request/**/*.test.js'",
13
+ "test.unit.request.record": "RECORD_SNAPSHOT=1 mocha --file ./test/setup.unit.js './test/request/**/*.test.js'",
11
14
  "test.unit.watch": "npm run test.unit -- --node-option=watch",
12
- "test": "karma start --single-run --browsers ChromeHeadless karma.conf.cjs"
15
+ "test": "karma start --single-run --browsers ChromeHeadless karma.conf.cjs",
16
+ "test.karma.request": "KARMA_TEST_ENTRY=test/request.js karma start --single-run --browsers ChromeHeadless karma.conf.cjs"
13
17
  },
14
18
  "author": "Ghostery GmbH",
15
19
  "license": "MPL-2.0",
@@ -29,6 +33,7 @@
29
33
  "karma-rollup-preprocessor": "^7.0.8",
30
34
  "karma-sinon": "^1.0.5",
31
35
  "mocha": "^11.7.1",
36
+ "puppeteer-core": "^24.42.0",
32
37
  "rollup": "^2.79.1",
33
38
  "rollup-plugin-copy": "^3.5.0",
34
39
  "rollup-plugin-polyfill-node": "^0.8.0",
@@ -36,7 +41,8 @@
36
41
  "sinon": "^21.0.0",
37
42
  "sinon-chai": "^4.0.1",
38
43
  "sinon-chrome": "^3.0.1",
39
- "web-ext": "^8.2.0"
44
+ "web-ext": "^8.2.0",
45
+ "webdriverio": "^9.27.0"
40
46
  },
41
47
  "dependencies": {
42
48
  "@ghostery/url-parser": "^1.3.0",
@@ -5,7 +5,13 @@ const commonjs = require('@rollup/plugin-commonjs');
5
5
  const json = require('@rollup/plugin-json');
6
6
 
7
7
  module.exports = {
8
- plugins: [nodePolyfills(), nodeResolve(), sourcemaps(), commonjs(), json()],
8
+ plugins: [
9
+ nodePolyfills(),
10
+ nodeResolve(),
11
+ sourcemaps(),
12
+ commonjs({ strictRequires: ['**/cssom/**'] }),
13
+ json(),
14
+ ],
9
15
  external: ['chai', 'sinon'],
10
16
  output: {
11
17
  globals: {
@@ -0,0 +1,77 @@
1
+ # Scenarios
2
+
3
+ Pre-recorded `chrome.webRequest.*`, `chrome.webNavigation.*`, and
4
+ `chrome.tabs.*` event streams that drive `RequestReporter` in node-mocha
5
+ integration tests without a real browser.
6
+
7
+ ## Layout
8
+
9
+ ```
10
+ scenarios/<release>/events_<scenario>_<browser>.log ← JSONL, one event per line
11
+ ```
12
+
13
+ A `release` identifies the recording date and the schema version of the
14
+ events format. When a scenario needs to be re-recorded (browser API drift,
15
+ schema change), bump the release rather than editing an existing file β€”
16
+ earlier releases may still be referenced by tests pinned to them.
17
+
18
+ `events_*.log` files are also downloaded on demand from
19
+ `github.com/ghostery/webextension-event-recorder/releases` if they aren't
20
+ present locally β€” the repository tracks them once pulled. See
21
+ `test/helpers/scenarios.js` for the download logic.
22
+
23
+ ## Current index
24
+
25
+ Scenarios actively used by `reporting/test/request/index.test.js`:
26
+
27
+ | Release | Scenario | What it covers |
28
+ | ---------------- | ----------------- | ------------------------------------------------------------------ |
29
+ | `2024-08-02` | `0001-empty-page` | Plain page load with no third-party resources β€” `requestStats` must stay empty. |
30
+ | `2024-08-02` | `0002-3rd-party` | Page with a single third-party script; verifies detection + the `wtm.attrack.tp_events` report shape. |
31
+ | `2024-08-02` | `0005-preload` | `<link rel=preload>` triggers the tracker path through a different webRequest ordering. |
32
+ | `2024-08-02-1` | `0004-ping` | Navigator `sendBeacon`/ping endpoints (non-XHR background request). |
33
+ | `2024-08-02-2` | `0008-navigation` | Two successive navigations on the same tab; each page's trackers must be reported to the right page hostname. |
34
+
35
+ Scenarios present on disk but not referenced by any current test (likely
36
+ WIP or kept for a future regression test):
37
+
38
+ - `2024-08-02-02/` (empty)
39
+ - `2024-09-27/{0001-quick-close,0002-quick-navigation,0003-prefetch}`
40
+ - `2024-09-30/0003-prefetch`
41
+
42
+ ## Related: `../snapshots/`
43
+
44
+ A separate fixture set used only by the `snapshots` `describe` block in
45
+ `reporting/test/request/index.test.js`. Each `snapshots/<N>/` contains:
46
+
47
+ - `events.log.br` β€” brotli-compressed event stream (replayed by `playSnapshotScenario`)
48
+ - `snapshot.json` β€” expected telemetry messages after replay
49
+
50
+ Approximate content (by inspection of `tps` keys):
51
+
52
+ | Snapshot | Site | Notes |
53
+ | -------- | ------------- | -------------------------------------------------------------- |
54
+ | `0001` | onet.pl | Polish news portal, ~160 third-party domains. |
55
+ | `0002` | onet.pl | Shorter session, ~94 third parties. |
56
+ | `0003` | soundcloud.com| Stream playback, CDN + Statsig + OneTrust. |
57
+ | `0004` | soundcloud.com| Smaller session. |
58
+ | `0005` | nike.com | E-commerce, bluecore + doubleclick + bing. |
59
+ | `0006` | nike.com | Variant session. |
60
+
61
+ The snapshot test replays each events stream twice β€” the second time with
62
+ URL rewrites (`onet.pl→wp.pl`, `soundcloud.com→google.com`,
63
+ `nike.com→adidas.com`) so the token-telemetry code sees the same trackers
64
+ on a different domain, which is needed to trigger quorum-based reporting.
65
+
66
+ ## Re-recording snapshots
67
+
68
+ When a change in `src/request/` legitimately shifts the telemetry output,
69
+ re-record the expected snapshots:
70
+
71
+ ```
72
+ npm --workspace=reporting run test.unit.request.record
73
+ ```
74
+
75
+ Then `git diff reporting/snapshots/` and commit the expected changes
76
+ alongside the source change. The record step is idempotent β€” running it
77
+ twice produces byte-identical files.
@@ -1,2 +1,42 @@
1
- Please add you spec to `index.js`.
2
- We do that (instead of listing files in karma config) to generate a single bundle.
1
+ # reporting/test
2
+
3
+ Two test suites live here, distinguished by filename suffix.
4
+
5
+ ## Node (mocha, sinon-chrome) β€” fast
6
+
7
+ - Pattern: `*.test.js`
8
+ - Setup: `setup.unit.js`
9
+ - All: `npm --workspace=reporting run test.unit`
10
+ - Request subset: `npm --workspace=reporting run test.unit.request`
11
+ - Watch: `npm --workspace=reporting run test.unit.watch`
12
+
13
+ Prefer this suite for request-pipeline work β€” seconds vs. minutes.
14
+
15
+ ## Browser (karma, headless Chrome) β€” covers DOM/CSSOM paths
16
+
17
+ - Pattern: `*.spec.js`
18
+ - Setup: `setup.js`
19
+ - Entry bundles: `test/index.js` (full) or `test/request.js` (subset)
20
+ - All: `npm --workspace=reporting run test`
21
+ - Request subset: `npm --workspace=reporting run test.karma.request`
22
+
23
+ New karma specs must be added to `index.js` (or `request.js` for the
24
+ request subset) β€” karma bundles a single entry with rollup, so a spec
25
+ that isn't imported there will not run.
26
+
27
+ ## Re-recording request snapshots
28
+
29
+ `request/index.test.js` has a `snapshots` block that replays recorded
30
+ event streams (under `../snapshots/`) and asserts the emitted telemetry
31
+ matches `snapshot.json`. When a source change legitimately shifts the
32
+ output:
33
+
34
+ ```
35
+ npm --workspace=reporting run test.unit.request.record
36
+ ```
37
+
38
+ Sets `RECORD_SNAPSHOT=1`; inspect `git diff reporting/snapshots/` and
39
+ commit the expected changes alongside the source change. The record
40
+ step is idempotent β€” re-running produces byte-identical files.
41
+
42
+ See `../scenarios/README.md` for the scenario + snapshot index.
@@ -72,7 +72,10 @@ export function recordSnapshot(name, messages) {
72
72
  }
73
73
  }
74
74
  const sortedMessages = sortObjectKeys(messages);
75
- fs.writeFileSync(snapshotPath, JSON.stringify(sortedMessages, null, 2));
75
+ fs.writeFileSync(
76
+ snapshotPath,
77
+ JSON.stringify(sortedMessages, null, 2) + '\n',
78
+ );
76
79
  }
77
80
 
78
81
  export function readSnapshot(name) {
@@ -335,10 +335,14 @@ describe('RequestReporter', function () {
335
335
  .NEW_ENTRY_MIN_AGE,
336
336
  );
337
337
 
338
- // eslint-disable-next-line no-undef
339
- if (process.argv.includes('--record-snapshot')) {
338
+ /* eslint-disable no-undef */
339
+ if (
340
+ process.argv.includes('--record-snapshot') ||
341
+ process.env.RECORD_SNAPSHOT
342
+ ) {
340
343
  recordSnapshot(snapshotName, messages);
341
344
  }
345
+ /* eslint-enable no-undef */
342
346
 
343
347
  const snapshot = await readSnapshot(snapshotName);
344
348
  expect(messages).to.have.lengthOf(snapshot.length);
@@ -0,0 +1,14 @@
1
+ import './setup.js';
2
+
3
+ import './request/qs-whitelist2.spec.js';
4
+ import './request/hash/index.spec.js';
5
+ import './request/database.spec.js';
6
+ import './request/index.spec.js';
7
+
8
+ import './request/utils/tldts.spec.js';
9
+ import './request/utils/bloom-filter-packed.spec.js';
10
+ import './request/utils/chrome-storage-map.spec.js';
11
+ import './request/utils/utils.spec.js';
12
+
13
+ import './request/steps/check-context.spec.js';
14
+ import './request/steps/oauth-detector.spec.js';