| 19 | const browserOutput = Boolean(process.env.BROWSER_OUTPUT) |
| 20 | |
| 21 | async function withRequestMetrics( |
| 22 | metricName: string, |
| 23 | page: Page, |
| 24 | fn: () => Promise<void> |
| 25 | ): Promise<void> { |
| 26 | const activePromises: Array<Promise<void>> = [] |
| 27 | const sizeByExtension = new Map<string, number>() |
| 28 | const requestsByExtension = new Map<string, number>() |
| 29 | const responseHandler = (response: Response) => { |
| 30 | activePromises.push( |
| 31 | (async () => { |
| 32 | const url = response.request().url() |
| 33 | const status = response.status() |
| 34 | const extension = |
| 35 | /^[^?#]+\.([a-z0-9]+)(?:[?#]|$)/i.exec(url)?.[1] ?? 'none' |
| 36 | const currentRequests = requestsByExtension.get(extension) ?? 0 |
| 37 | requestsByExtension.set(extension, currentRequests + 1) |
| 38 | if (status >= 200 && status < 300) { |
| 39 | let body |
| 40 | try { |
| 41 | body = await response.body() |
| 42 | } catch { |
| 43 | // empty |
| 44 | } |
| 45 | if (body) { |
| 46 | const size = body.length |
| 47 | const current = sizeByExtension.get(extension) ?? 0 |
| 48 | sizeByExtension.set(extension, current + size) |
| 49 | } |
| 50 | } |
| 51 | })() |
| 52 | ) |
| 53 | } |
| 54 | let errorCount = 0 |
| 55 | let warningCount = 0 |
| 56 | let logCount = 0 |
| 57 | const consoleHandler = (message: ConsoleMessage) => { |
| 58 | const type = message.type() |
| 59 | if (type === 'error') { |
| 60 | errorCount++ |
| 61 | } else if (type === 'warning') { |
| 62 | warningCount++ |
| 63 | } else { |
| 64 | logCount++ |
| 65 | } |
| 66 | if (browserOutput) { |
| 67 | activePromises.push( |
| 68 | (async () => { |
| 69 | const args = [] |
| 70 | try { |
| 71 | const text = message.text() |
| 72 | for (const arg of message.args()) { |
| 73 | args.push(await arg.jsonValue()) |
| 74 | } |
| 75 | console.log(`[${type}] ${text}`, ...args) |
| 76 | } catch { |
| 77 | // Ignore |
| 78 | } |