-
Notifications
You must be signed in to change notification settings - Fork 50
/
index.js
654 lines (577 loc) · 19.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
import { parse, format } from 'url';
import { randomUUID } from 'crypto';
import { createRequire } from 'node:module';
import debug from 'debug';
import ignoredEvents from './lib/ignoredEvents.js';
import { parseRequestCookies, formatCookie } from './lib/cookies.js';
import { getHeaderValue, parseHeaders } from './lib/headers.js';
import {
formatMillis,
parsePostData,
isSupportedProtocol,
toNameValuePairs,
} from './lib/util.js';
import populateEntryFromResponse from './lib/entryFromResponse.js';
import finalizeEntry from './lib/finalizeEntry.js';
const require = createRequire(import.meta.url);
const version = require('./package.json').version;
const log = debug('chrome-har');
const defaultOptions = {
includeResourcesFromDiskCache: false,
includeTextFromResponseBody: false,
};
const isEmpty = (o) => !o;
function addFromFirstRequest(page, params) {
if (!page.__timestamp) {
page.__wallTime = params.wallTime;
page.__timestamp = params.timestamp;
page.startedDateTime = new Date(params.wallTime * 1000).toISOString();
// URL is better than blank, and it's what devtools uses.
page.title = page.title === '' ? params.request.url : page.title;
}
}
function populateRedirectResponse(page, params, entries, options) {
const previousEntry = entries.find(
(entry) => entry._requestId === params.requestId,
);
if (previousEntry) {
previousEntry._requestId += 'r';
populateEntryFromResponse(
previousEntry,
params.redirectResponse,
page,
options,
);
} else {
log(
`Couldn't find original request for redirect response: ${
params.requestId
}`,
);
}
}
export function harFromMessages(messages, options) {
options = Object.assign({}, defaultOptions, options);
const ignoredRequests = new Set(),
rootFrameMappings = new Map();
let pages = [],
entries = [],
entriesWithoutPage = [],
responsesWithoutPage = [],
paramsWithoutPage = [],
responseReceivedExtraInfos = [],
currentPageId;
for (const message of messages) {
const params = message.params;
const method = message.method;
if (!/^(Page|Network)\..+/.test(method)) {
continue;
}
switch (method) {
case 'Page.frameStartedLoading':
case 'Page.frameRequestedNavigation':
case 'Page.navigatedWithinDocument':
{
const frameId = params.frameId;
const rootFrame = rootFrameMappings.get(frameId) || frameId;
if (pages.some((page) => page.__frameId === rootFrame)) {
continue;
}
currentPageId = randomUUID();
const title =
method === 'Page.navigatedWithinDocument' ? params.url : '';
const page = {
id: currentPageId,
startedDateTime: '',
title: title,
pageTimings: {},
__frameId: rootFrame,
};
pages.push(page);
// do we have any unmmapped requests, add them
if (entriesWithoutPage.length > 0) {
// update page
for (let entry of entriesWithoutPage) {
entry.pageref = page.id;
}
entries = entries.concat(entriesWithoutPage);
addFromFirstRequest(page, paramsWithoutPage[0]);
// Add unmapped redirects
for (let params of paramsWithoutPage) {
if (params.redirectResponse) {
populateRedirectResponse(page, params, entries, options);
}
}
}
if (responsesWithoutPage.length > 0) {
for (let params of responsesWithoutPage) {
let entry = entries.find(
(entry) => entry._requestId === params.requestId,
);
if (entry) {
populateEntryFromResponse(
entry,
params.response,
page,
options,
);
} else {
log(`Couln't find matching request for response`);
}
}
}
}
break;
case 'Network.requestWillBeSent':
{
const request = params.request;
if (!isSupportedProtocol(request.url)) {
ignoredRequests.add(params.requestId);
continue;
}
const page = pages[pages.length - 1];
const cookieHeader = getHeaderValue(request.headers, 'Cookie');
//Before we used to remove the hash framgment because of Chrome do that but:
// 1. Firefox do not
// 2. If we remove it, the HAR will not have the same URL as we tested
// and that makes PageXray generate the wromng URL and we end up with two pages
// in sitespeed.io if we run in SPA mode
const url = parse(
request.url + (request.urlFragment ? request.urlFragment : ''),
true,
);
const postData = parsePostData(
getHeaderValue(request.headers, 'Content-Type'),
request.postData,
);
const req = {
method: request.method,
url: format(url),
queryString: toNameValuePairs(url.query),
postData,
headersSize: -1,
bodySize: isEmpty(request.postData) ? 0 : request.postData.length,
cookies: parseRequestCookies(cookieHeader),
headers: parseHeaders(request.headers),
};
if (request.isLinkPreload) {
req._isLinkPreload = true;
}
const entry = {
cache: {},
startedDateTime: '',
__requestWillBeSentTime: params.timestamp,
__wallTime: params.wallTime,
_requestId: params.requestId,
__frameId: params.frameId,
_initialPriority: request.initialPriority,
_priority: request.initialPriority,
pageref: currentPageId,
request: req,
time: 0,
_initiator_detail: JSON.stringify(params.initiator),
_initiator_type: params.initiator.type,
// Chrome's DevTools Frontend returns this field in lower case
_resourceType: params.type ? params.type.toLowerCase() : null,
};
// The object initiator change according to its type
switch (params.initiator.type) {
case 'parser':
{
entry._initiator = params.initiator.url;
entry._initiator_line = params.initiator.lineNumber + 1; // Because lineNumber is 0 based
}
break;
case 'script':
{
if (
params.initiator.stack &&
params.initiator.stack.callFrames.length > 0
) {
const topCallFrame = params.initiator.stack.callFrames[0];
entry._initiator = topCallFrame.url;
entry._initiator_line = topCallFrame.lineNumber + 1; // Because lineNumber is 0 based
entry._initiator_column = topCallFrame.columnNumber + 1; // Because columnNumber is 0 based
entry._initiator_function_name = topCallFrame.functionName;
entry._initiator_script_id = topCallFrame.scriptId;
}
}
break;
}
if (params.redirectResponse) {
populateRedirectResponse(page, params, entries, options);
}
if (!page) {
log(
`Request will be sent with requestId ${params.requestId} that can't be mapped to any page at the moment.`,
);
// ignoredRequests.add(params.requestId);
entriesWithoutPage.push(entry);
paramsWithoutPage.push(params);
continue;
}
entries.push(entry);
// this is the first request for this page, so set timestamp of page.
addFromFirstRequest(page, params);
// wallTime is not necessarily monotonic, timestamp is. So calculate startedDateTime from timestamp diffs.
// (see https://cs.chromium.org/chromium/src/third_party/WebKit/Source/platform/network/ResourceLoadTiming.h?q=requestTime+package:%5Echromium$&dr=CSs&l=84)
const entrySecs =
page.__wallTime + (params.timestamp - page.__timestamp);
entry.startedDateTime = new Date(entrySecs * 1000).toISOString();
}
break;
case 'Network.requestServedFromCache':
{
if (pages.length < 1) {
//we haven't loaded any pages yet.
continue;
}
if (ignoredRequests.has(params.requestId)) {
continue;
}
const entry = entries.find(
(entry) => entry._requestId === params.requestId,
);
if (!entry) {
log(
`Received requestServedFromCache for requestId ${params.requestId} with no matching request.`,
);
continue;
}
entry.__servedFromCache = true;
entry.cache.beforeRequest = {
lastAccess: '',
eTag: '',
hitCount: 0,
};
}
break;
case 'Network.requestWillBeSentExtraInfo':
{
if (ignoredRequests.has(params.requestId)) {
continue;
}
const entry = entries.find(
(entry) => entry._requestId === params.requestId,
);
if (!entry) {
log(
`Extra info sent for requestId ${params.requestId} with no matching request.`,
);
continue;
}
if (params.headers) {
entry.request.headers = entry.request.headers.concat(
parseHeaders(params.headers),
);
}
if (params.associatedCookies) {
entry.request.cookies = (entry.request.cookies || []).concat(
params.associatedCookies
.filter(({ blockedReasons }) => !blockedReasons.length)
.map(({ cookie }) => formatCookie(cookie)),
);
}
}
break;
case 'Network.responseReceivedExtraInfo':
{
if (pages.length < 1) {
//we haven't loaded any pages yet.
continue;
}
if (ignoredRequests.has(params.requestId)) {
continue;
}
let entry = entries.find(
(entry) => entry._requestId === params.requestId,
);
if (!entry) {
entry = entriesWithoutPage.find(
(entry) => entry._requestId === params.requestId,
);
}
if (!entry) {
responseReceivedExtraInfos.push(params);
continue;
}
if (!entry.response) {
// Extra info received before response
entry.extraResponseInfo = {
headers: parseHeaders(params.headers),
blockedCookies: params.blockedCookies,
};
responseReceivedExtraInfos.push(params);
continue;
}
if (params.headers) {
entry.response.headers = parseHeaders(params.headers);
}
}
break;
case 'Network.responseReceived':
{
if (pages.length < 1) {
//we haven't loaded any pages yet.
responsesWithoutPage.push(params);
continue;
}
if (ignoredRequests.has(params.requestId)) {
continue;
}
let entry = entries.find(
(entry) => entry._requestId === params.requestId,
);
if (!entry) {
entry = entriesWithoutPage.find(
(entry) => entry._requestId === params.requestId,
);
}
if (!entry) {
log(
`Received network response for requestId ${params.requestId} with no matching request.`,
);
continue;
}
const frameId =
rootFrameMappings.get(params.frameId) || params.frameId;
const page =
pages.find((page) => page.__frameId === frameId) ||
pages[pages.length - 1];
if (!page) {
log(
`Received network response for requestId ${params.requestId} that can't be mapped to any page.`,
);
continue;
}
try {
populateEntryFromResponse(entry, params.response, page, options);
} catch (e) {
log(
`Error parsing response: ${JSON.stringify(params, undefined, 2)}`,
);
throw e;
}
const responseReceivedExtraInfo = responseReceivedExtraInfos.find(
(responseReceivedExtraInfo) =>
responseReceivedExtraInfo.requestId == params.requestId,
);
if (responseReceivedExtraInfo && responseReceivedExtraInfo.headers) {
entry.response.headers = parseHeaders(
responseReceivedExtraInfo.headers,
);
}
}
break;
case 'Network.dataReceived':
{
if (pages.length < 1) {
//we haven't loaded any pages yet.
continue;
}
if (ignoredRequests.has(params.requestId)) {
continue;
}
const entry = entries.find(
(entry) => entry._requestId === params.requestId,
);
if (!entry) {
log(
`Received network data for requestId ${params.requestId} with no matching request.`,
);
continue;
}
// It seems that people sometimes have an entry without a response,
// I wonder how that works
// https://github.com/sitespeedio/sitespeed.io/issues/2645
if (entry.response) {
entry.response.content.size += params.dataLength;
}
const page = pages.find((page) => page.id === entry.pageref);
if (entry._chunks && page) {
entry._chunks.push({
ts: formatMillis((params.timestamp - page.__timestamp) * 1000),
bytes: params.dataLength,
});
} else if (page) {
entry._chunks = [
{
ts: formatMillis((params.timestamp - page.__timestamp) * 1000),
bytes: params.dataLength,
},
];
}
}
break;
case 'Network.loadingFinished':
{
if (pages.length < 1) {
//we haven't loaded any pages yet.
continue;
}
if (ignoredRequests.has(params.requestId)) {
ignoredRequests.delete(params.requestId);
continue;
}
const entry = entries.find(
(entry) => entry._requestId === params.requestId,
);
if (!entry) {
log(
`Network loading finished for requestId ${params.requestId} with no matching request.`,
);
continue;
}
finalizeEntry(entry, params);
}
break;
case 'Page.loadEventFired':
{
if (pages.length < 1) {
//we haven't loaded any pages yet.
continue;
}
const page = pages[pages.length - 1];
if (params.timestamp && page.__timestamp) {
page.pageTimings.onLoad = formatMillis(
(params.timestamp - page.__timestamp) * 1000,
);
}
}
break;
case 'Page.domContentEventFired':
{
if (pages.length < 1) {
//we haven't loaded any pages yet.
continue;
}
const page = pages[pages.length - 1];
if (params.timestamp && page.__timestamp) {
page.pageTimings.onContentLoad = formatMillis(
(params.timestamp - page.__timestamp) * 1000,
);
}
}
break;
case 'Page.frameAttached':
{
const frameId = params.frameId,
parentId = params.parentFrameId;
rootFrameMappings.set(frameId, parentId);
let grandParentId = rootFrameMappings.get(parentId);
while (grandParentId) {
rootFrameMappings.set(frameId, grandParentId);
grandParentId = rootFrameMappings.get(grandParentId);
}
}
break;
case 'Network.loadingFailed':
{
if (ignoredRequests.has(params.requestId)) {
ignoredRequests.delete(params.requestId);
continue;
}
const entry = entries.find(
(entry) => entry._requestId === params.requestId,
);
if (!entry) {
log(
`Network loading failed for requestId ${params.requestId} with no matching request.`,
);
continue;
}
if (params.errorText === 'net::ERR_ABORTED') {
finalizeEntry(entry, params);
log(
`Loading was canceled due to Chrome or a user action for requestId ${params.requestId}.`,
);
continue;
}
// This could be due to incorrect domain name etc. Sad, but unfortunately not something that a HAR file can
// represent.
log(
`Failed to load url '${entry.request.url}' (canceled: ${params.canceled})`,
);
entries = entries.filter(
(entry) => entry._requestId !== params.requestId,
);
}
break;
case 'Network.resourceChangedPriority':
{
const entry = entries.find(
(entry) => entry._requestId === params.requestId,
);
if (!entry) {
log(
`Received resourceChangedPriority for requestId ${params.requestId} with no matching request.`,
);
continue;
}
entry._priority = message.params.newPriority;
}
break;
default:
// Keep the old functionallity and log unknown events
ignoredEvents(method);
break;
}
}
if (!options.includeResourcesFromDiskCache) {
entries = entries.filter(
(entry) => entry.cache.beforeRequest === undefined,
);
}
const deleteInternalProperties = (o) => {
// __ properties are only for internal use, _ properties are custom properties for the HAR
for (const prop in o) {
if (prop.startsWith('__')) {
delete o[prop];
}
}
return o;
};
entries = entries
.filter((entry) => {
if (!entry.response) {
log(`Dropping incomplete request: ${entry.request.url}`);
}
return entry.response;
})
.map(deleteInternalProperties);
pages = pages.map(deleteInternalProperties);
pages = pages.reduce((result, page, index) => {
const hasEntry = entries.some((entry) => entry.pageref === page.id);
if (hasEntry) {
result.push(page);
} else {
log(`Skipping empty page: ${index + 1}`);
}
return result;
}, []);
const pagerefMapping = pages.reduce((result, page, index) => {
result[page.id] = `page_${index + 1}`;
return result;
}, {});
pages = pages.map((page) => {
page.id = pagerefMapping[page.id];
return page;
});
entries = entries.map((entry) => {
entry.pageref = pagerefMapping[entry.pageref];
return entry;
});
// FIXME sanity check if there are any pages/entries created
return {
log: {
version: '1.2',
creator: {
name: 'chrome-har',
version,
comment: 'https://github.com/sitespeedio/chrome-har',
},
pages,
entries,
},
};
}