This repository was archived by the owner on Feb 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.js
More file actions
104 lines (96 loc) · 2.64 KB
/
index.js
File metadata and controls
104 lines (96 loc) · 2.64 KB
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
/* eslint-disable no-console */
import zlib from 'zlib'
import { promisify } from 'util'
import path from 'path'
import fs from 'fs'
import axios from 'axios'
import gzipSize from 'gzip-size'
import brotliSize from 'brotli-size'
import omitDeep from 'omit-deep'
import { detectProvider } from './provider'
import { resolveConfig, getToken, getApiUrl } from './config'
const gzip = promisify(zlib.gzip)
async function sizeAssets(webpackStats, { fileSystem = fs } = {}) {
const readFile = promisify(
fileSystem.readFile ? fileSystem.readFile.bind(fileSystem) : fs.readFile,
)
return Promise.all(
webpackStats.assets.map(async asset => {
const fullPath = path.join(webpackStats.outputPath, asset.name)
const buffer = await readFile(fullPath)
return {
...asset,
gzipSize: await gzipSize(buffer),
brotliSize: brotliSize.sync(buffer),
}
}),
)
}
function getErrorMessage(error) {
if (
error.response &&
error.response.data &&
error.response.data.error &&
error.response.data.error.message
) {
return error.response.data.error.message
}
return error.message
}
export async function uploadStats({
context = process.cwd(),
configFile,
webpackStats,
token: optionToken,
fileSystem,
}) {
try {
const token = getToken(optionToken)
const apiUrl = getApiUrl()
const metadata = detectProvider()
const stats = omitDeep(webpackStats, 'source')
const config = await resolveConfig(context, configFile)
const assets = await sizeAssets(stats, { fileSystem })
const { data: bundle } = await axios.post(`${apiUrl}/bundles`, {
token,
bundler: 'webpack',
stats: {
assets,
chunksNumber: stats.chunks.length,
modulesNumber: stats.modules.length,
assetsNumber: stats.assets.length,
},
})
const data = await gzip(Buffer.from(JSON.stringify(stats)))
await axios.request({
method: 'put',
url: bundle.webpackStatsPutUrl,
data,
headers: {
'content-encoding': 'gzip',
},
maxContentLength: 30 * 1024 * 1024,
})
await axios.post(`${apiUrl}/builds`, {
token,
bundleId: bundle.id,
branch: metadata.branch,
commit: metadata.commit,
providerMetadata: metadata,
config,
})
} catch (error) {
if (
error.response &&
error.response.data &&
error.response.data.error &&
error.response.data.error.errors
) {
console.error('Invalid Bundle Analyzer config:')
error.response.data.error.errors.forEach(message =>
console.error(message),
)
}
throw new Error(getErrorMessage(error))
}
}