Repository navigation
Expand file tree
/
Copy pathwasm-size.js
More file actions
226 lines (216 loc) · 7.93 KB
/
Copy pathwasm-size.js
File metadata and controls
226 lines (216 loc) · 7.93 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
216
217
218
219
220
221
222
223
224
225
226
import { createHash } from 'node:crypto'
import {
appendFileSync,
readFileSync,
realpathSync,
writeFileSync,
} from 'node:fs'
import { join, resolve } from 'node:path'
import { parseArgs } from 'node:util'
import { gzipSync } from 'node:zlib'
import { wasmBindgenVersionPattern } from './wasm-bindgen-version.js'
const artifacts = { wasm: 'index_bg.wasm', glue: 'index.js' }
const tools = ['rustc', 'wasmPack', 'wasmBindgen', 'wasmOpt', 'bun', 'node']
const readJson = (file) => JSON.parse(readFileSync(file, 'utf8'))
const object = (value) =>
value !== null && typeof value === 'object' && !Array.isArray(value)
const text = (value) => typeof value === 'string' && value.trim().length > 0
const bytes = (value) => Number.isSafeInteger(value) && value > 0
function requireInput(condition, message) {
if (!condition) throw new Error(`verify-wasm-size: ${message}`)
}
function keys(value, expected, label) {
const matches = object(value) && Object.keys(value).sort().join()
requireInput(matches === [...expected].sort().join(), `invalid ${label} keys`)
}
export function validateConfig(config) {
keys(config, ['wasm', 'glue'], 'config')
for (const name of Object.keys(artifacts)) {
keys(config[name], ['raw', 'gzip'], `config.${name}`)
for (const kind of ['raw', 'gzip']) {
const policy = config[name][kind]
const label = `${name}.${kind}`
keys(policy, ['growth', 'roundBytes'], `config.${label}`)
const growth = Number.isFinite(policy.growth) && policy.growth >= 0
requireInput(growth, `invalid ${label} growth`)
requireInput(bytes(policy.roundBytes), `invalid ${label} roundBytes`)
}
}
return config
}
export function validateMetadata(metadata, directories) {
keys(metadata, ['jobId', 'buildCommand', 'base', 'candidate'], 'metadata')
const provenance = text(metadata.jobId) && text(metadata.buildCommand)
requireInput(provenance, 'missing job/build provenance')
for (const side of ['base', 'candidate']) {
const source = metadata[side]
keys(
source,
['commit', 'tree', 'packageDir', 'wasmBindgenVersion', 'tools'],
`metadata.${side}`,
)
for (const id of ['commit', 'tree']) {
const valid =
typeof source[id] === 'string' && /^[a-f0-9]{40}$/.test(source[id])
requireInput(valid, `invalid ${side}.${id}`)
}
const path = source.packageDir
const matches =
text(path) && realpathSync(path) === realpathSync(directories[side])
requireInput(matches, `${side} packageDir does not match CLI`)
keys(source.tools, tools, `${side}.tools`)
for (const tool of tools) {
requireInput(text(source.tools[tool]), `missing ${side} tool ${tool}`)
if (
tool === 'wasmBindgen' &&
source.wasmBindgenVersion !== metadata.base.wasmBindgenVersion
)
continue
const matches = source.tools[tool] === metadata.base.tools[tool]
requireInput(matches, `tool mismatch: ${tool}`)
}
const version = source.wasmBindgenVersion
requireInput(
typeof version === 'string' && wasmBindgenVersionPattern.test(version),
`invalid ${side}.wasmBindgenVersion`,
)
requireInput(
source.tools.wasmBindgen.split(/\r?\n/, 1)[0] ===
`wasm-bindgen ${version}`,
`tool mismatch: ${side} wasmBindgen does not match committed lock version`,
)
}
const distinct =
realpathSync(directories.base) !== realpathSync(directories.candidate)
requireInput(distinct, 'base and candidate package directories must differ')
return metadata
}
export function measure(directory) {
return Object.fromEntries(
Object.entries(artifacts).map(([name, file]) => {
const path = join(realpathSync(directory), file)
const content = readFileSync(path)
requireInput(bytes(content.length), `empty artifact: ${path}`)
const sizes = {
file: path,
sha256: createHash('sha256').update(content).digest('hex'),
raw: content.length,
gzip: gzipSync(content, { level: 9 }).length,
}
return [name, sizes]
}),
)
}
export function compare(base, candidate, config) {
validateConfig(config)
const metrics = []
for (const name of Object.keys(artifacts)) {
for (const kind of ['raw', 'gzip']) {
const before = base?.[name]?.[kind]
const after = candidate?.[name]?.[kind]
requireInput(
bytes(before) && bytes(after),
`invalid measurement: ${name}.${kind}`,
)
const { growth, roundBytes } = config[name][kind]
const limit = Math.ceil((before * (1 + growth)) / roundBytes) * roundBytes
requireInput(bytes(limit), `unsafe limit: ${name}.${kind}`)
metrics.push({
artifact: name,
kind,
baseBytes: before,
candidateBytes: after,
limitBytes: limit,
deltaBytes: after - before,
deltaPercent: ((after - before) / before) * 100,
growth,
roundBytes,
passed: after <= limit,
})
}
}
return { passed: metrics.every((metric) => metric.passed), metrics }
}
export function summary(report) {
const { metadata, measurements, config, measurement } = report
const evidence = { metadata, measurements, config, measurement }
const lines = [
`## WASM size: ${report.passed ? 'PASS' : 'FAIL'}`,
'',
'| Metric | Base bytes | Candidate bytes | Limit bytes | Delta bytes | Delta % | Result |',
'| --- | ---: | ---: | ---: | ---: | ---: | --- |',
...report.metrics.map(
(row) =>
`| ${row.artifact}/${row.kind} | ${row.baseBytes} | ${row.candidateBytes} | ${row.limitBytes} | ${row.deltaBytes} | ${row.deltaPercent.toFixed(3)} | ${row.passed ? 'PASS' : 'FAIL'} |`,
),
'',
'Limits: ceil(baseBytes * (1 + growth) / roundBytes) * roundBytes; policies recorded below.',
'',
'```json',
JSON.stringify(evidence, null, 2),
'```',
'',
]
return lines.join('\n')
}
export function cli(args, environment = process.env) {
const names = [
'base-pkg',
'candidate-pkg',
'metadata',
'config',
'report',
'summary',
]
const options = Object.fromEntries(
names.map((name) => [name, { type: 'string' }]),
)
const { values } = parseArgs({ args, options })
for (const flag of ['base-pkg', 'candidate-pkg', 'metadata', 'report'])
requireInput(text(values[flag]), `required --${flag}`)
const summaryFile = values.summary ?? environment.GITHUB_STEP_SUMMARY
requireInput(text(summaryFile), 'required --summary or GITHUB_STEP_SUMMARY')
const defaultConfig = new URL(
'./bindings/devup-ui-wasm/size-budget.json',
import.meta.url,
)
const configFile = values.config ?? defaultConfig
const paths = [values.report, summaryFile].map((path) => resolve(path))
const directories = {
base: values['base-pkg'],
candidate: values['candidate-pkg'],
}
// Reject outputs that could overwrite evidence or policy before writing anything.
const files = Object.values(directories).flatMap((dir) =>
Object.values(artifacts).map((file) => join(dir, file)),
)
const inputs = [values.metadata, configFile, ...files]
const safe = inputs.every((file) => !paths.includes(realpathSync(file)))
requireInput(
paths[0] !== paths[1] && safe,
'outputs must not overwrite inputs or each other',
)
const config = validateConfig(readJson(configFile))
const metadata = validateMetadata(readJson(values.metadata), directories)
const base = measure(directories.base)
const candidate = measure(directories.candidate)
const report = {
schemaVersion: 1,
...compare(base, candidate, config),
metadata,
measurements: { base, candidate },
config,
measurement: {
implementation: 'node:zlib.gzipSync',
level: 9,
node: process.version,
zlib: process.versions.zlib,
},
}
const markdown = summary(report)
writeFileSync(values.report, JSON.stringify(report, null, 2) + '\n')
if (values.summary) writeFileSync(summaryFile, markdown)
else appendFileSync(summaryFile, markdown)
console.info(markdown)
return report.passed ? 0 : 1
}