Repository navigation
215 lines (204 loc) · 9.41 KB
/
Copy pathbundle-size.yml
File metadata and controls
215 lines (204 loc) · 9.41 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
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
name: Bundle Size
on:
pull_request:
branches: [main]
permissions:
contents: read
concurrency:
group: bundle-size-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
build:
name: Measure ${{ matrix.build }} bundle
runs-on: ubuntu-latest
strategy:
matrix:
include:
- build: main
ref: ${{ github.event.pull_request.base.sha }}
- build: pr
ref: ${{ github.sha }}
steps:
- name: Checkout
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ matrix.ref }}
fetch-depth: 0
persist-credentials: false
- name: Setup Tools
uses: tanstack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main
- name: Build
run: pnpm build
- name: Measure client assets
env:
REPORT_FILE: ${{ runner.temp }}/bundle-size-${{ matrix.build }}.json
run: |
node --input-type=module <<'NODE'
import { readdirSync, readFileSync, writeFileSync } from 'node:fs'
import { extname, join, relative, resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
import { gzipSync } from 'node:zlib'
const client = 'dist/client'
const totals = { js: 0, jsGzip: 0, css: 0, cssGzip: 0 }
const gzipByHref = new Map()
const entries = readdirSync(join(client, 'assets'), {
recursive: true,
withFileTypes: true,
})
for (const entry of entries) {
const extension = extname(entry.name).slice(1)
if (!entry.isFile() || (extension !== 'js' && extension !== 'css')) continue
const file = join(entry.parentPath, entry.name)
const bytes = readFileSync(file)
const gzip = gzipSync(bytes).length
totals[extension] += bytes.length
totals[`${extension}Gzip`] += gzip
gzipByHref.set(`/${relative(client, file)}`, gzip)
}
if (totals.js === 0 || totals.css === 0) {
throw new Error('Expected built JS and CSS in dist/client/assets')
}
const serverAssets = 'dist/server/assets'
const manifestFile = readdirSync(serverAssets).find((file) =>
file.startsWith('_tanstack-start-manifest_'),
)
if (!manifestFile) throw new Error('TanStack Start build manifest is missing')
const { tsrStartManifest } = await import(pathToFileURL(resolve(serverAssets, manifestFile)))
const { routes } = tsrStartManifest()
const parents = new Map()
for (const [id, route] of Object.entries(routes)) {
for (const child of route.children ?? []) parents.set(child, id)
}
const pageRoutes = {
'/': '/',
'/libraries': '/libraries',
'/start/latest': '/_library/start/$version/',
'/router/latest': '/_library/router/$version/',
'/query/latest': '/_library/query/$version/',
'/table/latest': '/_library/table/$version/',
'/charts/latest': '/_library/charts/$version/',
'/ai/latest': '/_library/ai/$version/',
'Docs article': '/_library/$libraryId/$version/docs/$',
'Framework docs article': '/_library/$libraryId/$version/docs/framework/$framework/$',
'/blog': '/blog/',
'/maintainers': '/maintainers',
'/showcase': '/showcase/',
'/chat': '/chat/',
'/chat/c/:conversationId': '/chat/c/$conversationId',
}
const pages = {}
for (const [page, id] of Object.entries(pageRoutes)) {
if (!routes[id]) continue
const matchedRoutes = new Set(['__root__'])
for (let current = id; current; current = parents.get(current)) {
matchedRoutes.add(current)
}
const hrefs = new Set()
for (const matched of matchedRoutes) {
const route = routes[matched]
for (const link of [...(route.preloads ?? []), ...(route.css ?? [])]) {
hrefs.add(typeof link === 'string' ? link : link.href)
}
for (const script of route.scripts ?? []) hrefs.add(script.attrs?.src)
}
pages[page] = [...hrefs].reduce((bytes, href) => bytes + (gzipByHref.get(href) ?? 0), 0)
}
writeFileSync(process.env.REPORT_FILE, JSON.stringify({ totals, pages }))
NODE
- name: Upload bundle sizes
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
with:
name: bundle-size-${{ matrix.build }}
path: ${{ runner.temp }}/bundle-size-${{ matrix.build }}.json
if-no-files-found: error
overwrite: true
retention-days: 7
comment:
name: Comment on bundle sizes
needs: build
if: >-
github.event.pull_request.head.repo.id == github.event.repository.id &&
github.actor != 'dependabot[bot]'
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
- name: Download bundle sizes
uses: actions/download-artifact@70fc10c6e5e1ce46ad2ea6f2b72d43f7d47b13c3 # v8.0.0
with:
pattern: bundle-size-{main,pr}
merge-multiple: true
path: ${{ runner.temp }}/bundle-size
- name: Update pull request comment
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
script: |
const { readFileSync } = require('node:fs')
const { join } = require('node:path')
const metrics = [
['JavaScript', 'js'],
['JavaScript (gzip)', 'jsGzip'],
['CSS', 'css'],
['CSS (gzip)', 'cssGzip'],
]
function readSizes(build) {
const file = join(process.env.RUNNER_TEMP, 'bundle-size', `bundle-size-${build}.json`)
const report = JSON.parse(readFileSync(file, 'utf8'))
const validSize = (bytes) => Number.isSafeInteger(bytes) && bytes > 0
if (
metrics.some(([, key]) => !validSize(report.totals?.[key])) ||
!validSize(report.pages?.['/']) ||
Object.values(report.pages).some((bytes) => !validSize(bytes))
) {
throw new Error(`Invalid bundle sizes in ${file}`)
}
return report
}
const original = context.payload.pull_request
const { data: pr } = await github.rest.pulls.get({ ...context.repo, pull_number: original.number })
if (pr.state !== 'open' || pr.base.ref !== 'main' || pr.head.sha !== original.head.sha) return
const main = readSizes('main')
const candidate = readSizes('pr')
const kib = (bytes) => bytes === undefined ? '—' : `${(bytes / 1024).toFixed(2)} KiB`
const sizeRow = (label, before, after) => {
let change = 'Added'
if (after === undefined) change = 'Removed'
else if (before !== undefined) {
const delta = after - before
const sign = delta > 0 ? '+' : ''
const indicator = delta < 0 ? '🟢 ' : delta > 0 ? '🔴 ' : ''
change = `${indicator}${sign}${kib(delta)} (${sign}${(100 * delta / before).toFixed(2)}%)`
}
return `| ${label} | ${kib(before)} | ${kib(after)} | ${change} |`
}
const pages = new Set([...Object.keys(main.pages), ...Object.keys(candidate.pages)])
const marker = /^<!-- bundle-size-report:(\d+) -->/
const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`
const body = [
`<!-- bundle-size-report:${context.runNumber} -->`,
'',
'| Asset | Main | PR merge build | Change |',
'| --- | ---: | ---: | ---: |',
...metrics.map(([label, key]) => sizeRow(label, main.totals[key], candidate.totals[key])),
'',
'| Page | Main (gzip) | PR merge build (gzip) | Change |',
'| --- | ---: | ---: | ---: |',
...Array.from(pages, (page) => sizeRow(page, main.pages[page], candidate.pages[page])),
'',
'Page sizes sum the JS and CSS in the TanStack Start manifest for each route and its layouts. Shared files count once per page.',
'',
`Compared with main at \`${original.base.sha.slice(0, 7)}\`. Gzip sizes are summed per file. [Build run](${runUrl})`,
].join('\n')
const issue = { ...context.repo, issue_number: pr.number }
for await (const { data: comments } of github.paginate.iterator(github.rest.issues.listComments, issue)) {
const previous = comments.find((comment) =>
comment.user?.login === 'github-actions[bot]' && marker.test(comment.body),
)
if (!previous) continue
const previousRun = Number(previous.body.match(marker)[1])
if (previousRun <= context.runNumber && previous.body !== body) {
await github.rest.issues.updateComment({ ...context.repo, comment_id: previous.id, body })
}
return
}
await github.rest.issues.createComment({ ...issue, body })