forked from treosh/crux-api
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
79 lines (71 loc) · 2.79 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
import { retryAfterTimeout } from './retry'
/**
* @typedef {{ key: string, fetch?: function }} CreateOptions
* @typedef {{ url?: string, origin?: string, formFactor?: FormFactor, effectiveConnectionType?: Connection }} QueryRecordOptions
* @typedef {QueryRecordOptions[]} BatchOptions
* @typedef {(SuccessResponse | null)[]} BatchResponse
*
* @typedef {'ALL_FORM_FACTORS' | 'PHONE' | 'DESKTOP' | 'TABLET'} FormFactor
* @typedef {'4G' | '3G' | '2G' | 'slow-2G' | 'offline'} Connection
* @typedef {{ histogram: { start: number | string, end: number | string, density: number }[], percentiles: { p75: number | string } }} MetricValue
* @typedef {'first_contentful_paint' | 'largest_contentful_paint' | 'first_input_delay' | 'cumulative_layout_shift'} MetricName
* @typedef {{ error: { code: number, message: string, status: string } }} ErrorResponse
* @typedef {{
* record: {
* key: {
* url?: string,
* origin?: string,
* effectiveConnectionType?: Connection,
* formFactor?: FormFactor
* },
* metrics: {
* first_contentful_paint?: MetricValue,
* largest_contentful_paint?: MetricValue,
* first_input_delay?: MetricValue,
* cumulative_layout_shift?: MetricValue,
* }
* },
* urlNormalizationDetails?: {
* originalUrl: string,
* normalizedUrl: string
* }
* }} SuccessResponse
*/
/**
* Fetch CrUX API and handles 4xx errors.
* Inspired by: https://github.com/GoogleChrome/CrUX/blob/master/js/crux-api-util.js
*
* @param {CreateOptions} createOptions
*/
export function createQueryRecord(createOptions) {
const key = createOptions.key
const fetch = createOptions.fetch || window.fetch
return queryRecord
/**
* @param {QueryRecordOptions} queryOptions
* @return {Promise<SuccessResponse | null>}
*/
async function queryRecord(queryOptions, retryCounter = 1) {
const apiEndpoint = `https://chromeuxreport.googleapis.com/v1/records:queryRecord?key=${key}`
const res = await fetch(apiEndpoint, { method: 'POST', body: JSON.stringify(queryOptions) })
if (res.status >= 500) throw new Error(`Invalid CrUX API status: ${res.status}`)
const json = await res.json()
if (json && json.error) {
const { error } = /** @type {ErrorResponse} */ (json)
if (error.code === 404) return null
if (error.code === 429) return retryAfterTimeout(retryCounter, () => queryRecord(queryOptions, retryCounter + 1))
throw new Error(JSON.stringify(error))
}
if (!json || (json && !json.record.key)) throw new Error(`Invalid response: ${JSON.stringify(json)}`)
return /** @type {SuccessResponse} */ (json)
}
}
/**
* Normalize URL to match CrUX API key.
*
* @param {string} url
*/
export function normalizeUrl(url) {
const u = new URL(url)
return u.origin + u.pathname
}