|
| 1 | +import fs from 'node:fs' |
| 2 | +import { fileURLToPath } from 'node:url' |
1 | 3 | import { defineConfig, mergeConfig } from 'vitest/config' |
2 | 4 | import sharedConfig from '../../vitest.shared' |
3 | 5 |
|
| 6 | +const SOURCE_FILE_PATTERN = /\.(jsx?|tsx?)$/; |
| 7 | +const CLIENT_VERSION_SENTINEL = "STACK_COMPILE_TIME_CLIENT_PACKAGE_VERSION_SENTINEL"; |
| 8 | +const ENFORCE_PRE: "pre" = "pre"; |
| 9 | + |
| 10 | +function getPackageVersionLabel() { |
| 11 | + const packageJson: unknown = JSON.parse(fs.readFileSync(fileURLToPath(new URL("./package.json", import.meta.url)), "utf-8")); |
| 12 | + if ( |
| 13 | + typeof packageJson !== "object" |
| 14 | + || packageJson === null |
| 15 | + || !("name" in packageJson) |
| 16 | + || typeof packageJson.name !== "string" |
| 17 | + || !("version" in packageJson) |
| 18 | + || typeof packageJson.version !== "string" |
| 19 | + ) { |
| 20 | + throw new Error("Expected package.json to include string name and version fields."); |
| 21 | + } |
| 22 | + |
| 23 | + return `js ${packageJson.name}@${packageJson.version}`; |
| 24 | +} |
| 25 | + |
| 26 | +const replaceCompileTimeClientVersion = () => { |
| 27 | + const packageVersionLabel = getPackageVersionLabel(); |
| 28 | + return { |
| 29 | + name: 'stackframe vitest client version replacement', |
| 30 | + enforce: ENFORCE_PRE, |
| 31 | + transform(code: string, id: string) { |
| 32 | + const filePath = id.split(/[?#]/, 1)[0]; |
| 33 | + if (!SOURCE_FILE_PATTERN.test(filePath) || !code.includes(CLIENT_VERSION_SENTINEL)) { |
| 34 | + return null; |
| 35 | + } |
| 36 | + |
| 37 | + return { |
| 38 | + code: code.replaceAll(CLIENT_VERSION_SENTINEL, packageVersionLabel), |
| 39 | + map: null, |
| 40 | + }; |
| 41 | + }, |
| 42 | + }; |
| 43 | +}; |
| 44 | + |
4 | 45 | export default mergeConfig( |
5 | 46 | sharedConfig, |
6 | | - defineConfig({}), |
| 47 | + defineConfig({ |
| 48 | + plugins: [replaceCompileTimeClientVersion()], |
| 49 | + }), |
7 | 50 | ) |
0 commit comments