forked from beefyfinance/beefy-v2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
version-plugin.ts
89 lines (79 loc) · 2.57 KB
/
version-plugin.ts
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
import { transformWithEsbuild, type Plugin } from 'vite';
import { exec } from 'node:child_process';
import type { OutputBundle } from 'rollup';
import { createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
export default function (): Plugin {
type BuildVersion = {
content: string;
timestamp: number;
git: string | undefined;
};
async function getGitHashOrUndefined(): Promise<string | undefined> {
return new Promise(resolve => {
exec('git rev-parse HEAD', (error, stdout) => {
if (error) {
console.warn('Failed to get git hash, version.git will be undefined');
resolve(undefined);
} else {
const output = stdout.toString()?.replace('\n', '');
resolve(output || undefined);
}
});
});
}
function getContentHash(bundle: OutputBundle): string {
const hash = createHash('md5');
for (const key of Object.keys(bundle).sort()) {
hash.update(key);
}
return hash.digest('hex');
}
function getCloudflareHeaders(version: BuildVersion) {
return `/*
X-Git-Commit: ${version.git || 'undefined'}
X-Build-Timestamp: ${version.timestamp}
X-Content-Hash: ${version.content}
`;
}
async function getCheckerScript(version: BuildVersion) {
const filePath = path.resolve(__dirname, 'version-checker.ts');
const code = await readFile(filePath, 'utf-8');
const codeWithVersion = code.replace(
"'$$VERSION_PLACEHOLDER$$'",
JSON.stringify(JSON.stringify(version))
);
const minified = await transformWithEsbuild(codeWithVersion, filePath, {
minify: true,
loader: 'ts',
});
return `<script>${minified.code}</script>`;
}
return {
name: 'version-plugin',
enforce: 'post',
apply: 'build',
async generateBundle(options, bundle) {
const content = getContentHash(bundle);
const timestamp = Math.floor(Date.now() / 1000);
const git = await getGitHashOrUndefined();
const version = { content, timestamp, git };
this.emitFile({
fileName: 'version.json',
type: 'asset',
source: JSON.stringify(version),
});
this.emitFile({
fileName: '_headers',
type: 'asset',
source: getCloudflareHeaders(version),
});
const index = bundle['index.html'];
if (index && index.type === 'asset' && typeof index.source === 'string') {
const checkerScript = await getCheckerScript(version);
index.source = index.source.replace('</body>', `${checkerScript}</body>`);
}
},
};
}