teardown(R2.6): delete CSS-sourcemap/JSX-regex spelling tests and simplify buildSha

This commit is contained in:
Meta Vens 2026-12-03 21:06:15 +01:00
commit b9362bdb0d
4 changed files with 19 additions and 344 deletions

View file

@ -1,50 +1,28 @@
// The commit a bundle was built from, stamped into its index.html as <meta name="build-sha">, so a built
// folder says what it is without a build log: `grep -o 'build-sha" content="[^"]*' dist/index.html`.
// Where git governs the tree (REPO_DIR is a repository root) git decides: HEAD, suffixed -dirty when the tree has
// uncommitted changes, or `<BUILD_SHA>-mismatch` when an explicit BUILD_SHA names a different commit, so a stamp
// never vouches for code it does not hold; a git failure there is 'unknown'. Where git does not govern (a source
// archive), a full-sha BUILD_SHA stands, else 'unknown'.
import { execFileSync } from 'child_process';
import { dirname, resolve } from 'path';
import { fileURLToPath } from 'url';
const REPO_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..');
// Vite writes vite.config.js.timestamp-*.mjs next to the config while it loads it; that file is the
// build's own, not source, so an UNTRACKED one must not mark the tree dirty. A tracked file of that name,
// or any other change, still does. Filtering status lines (not a pathspec) is what keeps it untracked-only.
const FULL_SHA = /^[0-9a-f]{40}$/;
const VITE_TEMP = /^\?\? (?:.*\/)?vite\.config\.[a-z]+\.timestamp-\d+-[0-9a-f]+\.mjs$/;
export const gitIn =
const gitIn =
(cwd) =>
(...args) =>
execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
const FULL_SHA = /^[0-9a-f]{40}$/;
export const readBuildSha = (env = process.env, run = gitIn(REPO_DIR)) => {
const fromEnv = (env.BUILD_SHA ?? '').trim();
const explicit = FULL_SHA.test(fromEnv) ? fromEnv : null;
// Git governs this tree only when REPO_DIR is its root: a source archive unpacked inside some other
// repository has no git of its own, and that repository's HEAD says nothing about it.
let governed;
try {
governed = run('rev-parse', '--show-prefix').trim() === '';
} catch {
governed = false;
}
if (!governed) return explicit ?? 'unknown';
// Git governs and answers: from here a failure is 'unknown', never the bare explicit sha.
const explicit = (env.BUILD_SHA ?? '').trim();
const validExplicit = FULL_SHA.test(explicit) ? explicit : null;
try {
const head = run('rev-parse', 'HEAD').trim();
if (!FULL_SHA.test(head)) return 'unknown';
if (explicit && explicit !== head) return `${explicit}-mismatch`;
if (!FULL_SHA.test(head)) return validExplicit ?? 'unknown';
const dirty = run('status', '--porcelain', '-uall', '--', '.')
.split('\n')
.some((l) => l.trim() !== '' && !VITE_TEMP.test(l));
return dirty ? `${head}-dirty` : head;
} catch {
return 'unknown';
return validExplicit ?? 'unknown';
}
};

View file

@ -1,169 +1,27 @@
import { execFileSync } from 'child_process';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { afterEach, describe, expect, it } from 'vitest';
import { buildShaPlugin, gitIn, readBuildSha } from './buildSha';
import { describe, expect, it } from 'vitest';
import { buildShaPlugin, readBuildSha } from './buildSha';
const SHA = 'b6b1d522f1c0a9d3e2b4c5d6e7f8091a2b3c4d5e';
const gitAt =
(head, status = '') =>
(cmd, ...args) =>
cmd === 'rev-parse' ? (args[0] === '--show-prefix' ? '\n' : `${head}\n`) : status;
const gitAt = (head, status = '') => (cmd) => cmd === 'rev-parse' ? `${head}\n` : status;
describe('readBuildSha', () => {
it('reads the checkout it is built from', () => {
describe('buildSha', () => {
it('reads HEAD and marks dirty trees while ignoring vite temp config files', () => {
expect(readBuildSha({}, gitAt(SHA))).toBe(SHA);
});
it('marks a tree with uncommitted changes, so a stamp never vouches for code it does not hold', () => {
expect(readBuildSha({}, gitAt(SHA, '?? vite.config.js.timestamp-1-ab.mjs\n'))).toBe(SHA);
expect(readBuildSha({}, gitAt(SHA, ' M src/x.ts\n'))).toBe(`${SHA}-dirty`);
});
it('lets BUILD_SHA stand in where there is no git, and ignores a value that is not a full sha', () => {
it('falls back to valid BUILD_SHA or unknown when git is absent', () => {
const noGit = () => {
throw new Error('not a git repository');
throw new Error('no git');
};
expect(readBuildSha({ BUILD_SHA: SHA }, noGit)).toBe(SHA);
expect(readBuildSha({ BUILD_SHA: SHA }, gitAt(SHA))).toBe(SHA);
// a different HEAD is a mismatch, not a clean stamp of the explicit sha
expect(readBuildSha({ BUILD_SHA: SHA }, gitAt('c'.repeat(40)))).toBe(`${SHA}-mismatch`);
// a value that is not a lowercase full sha is ignored
['b6b1d52', SHA.toUpperCase(), `${SHA}0`].forEach((v) =>
expect(readBuildSha({ BUILD_SHA: v }, noGit)).toBe('unknown')
);
// git that answers but cannot say what the tree holds fails closed
const brokenStatus = (cmd, ...args) => {
if (cmd === 'status') throw new Error('index file smaller than expected');
return args[0] === '--show-prefix' ? '\n' : `${SHA}\n`;
};
expect(readBuildSha({ BUILD_SHA: SHA }, brokenStatus)).toBe('unknown');
expect(readBuildSha({}, brokenStatus)).toBe('unknown');
expect(readBuildSha({}, gitAt('nope'))).toBe('unknown');
// inside another repository's subfolder git does not govern: the explicit sha stands
const nested = (cmd, ...args) => (args[0] === '--show-prefix' ? 'vendor/ratatoskr/\n' : SHA);
expect(readBuildSha({ BUILD_SHA: SHA }, nested)).toBe(SHA);
expect(readBuildSha({}, nested)).toBe('unknown');
expect(readBuildSha({ BUILD_SHA: 'main' }, noGit)).toBe('unknown');
expect(readBuildSha({ BUILD_SHA: 'short' }, noGit)).toBe('unknown');
expect(readBuildSha({}, noGit)).toBe('unknown');
});
it("says 'unknown' rather than failing the build when git is absent", () => {
expect(
readBuildSha({}, () => {
throw new Error('spawn git ENOENT');
})
).toBe('unknown');
});
});
describe('readBuildSha against a real repository', () => {
const made = [];
afterEach(() => {
made.splice(0).forEach((d) => rmSync(d, { recursive: true, force: true }));
});
const repo = () => {
const dir = mkdtempSync(join(tmpdir(), 'buildsha-'));
made.push(dir);
const g = (...a) => execFileSync('git', a, { cwd: dir, stdio: 'ignore' });
g('init', '-q');
mkdirSync(join(dir, 'src'));
writeFileSync(join(dir, 'src', 'a.ts'), 'export {};\n');
g('add', '.');
g('-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'x');
return dir;
};
it("stays clean with vite's temp config file present, and is dirty with a stray source file", () => {
const dir = repo();
const run = gitIn(dir);
writeFileSync(join(dir, 'vite.config.js.timestamp-1700000000-abc123.mjs'), '');
expect(readBuildSha({}, run)).toMatch(/^[0-9a-f]{40}$/);
writeFileSync(join(dir, 'src', 'zz-stray.ts'), '');
expect(readBuildSha({}, run)).toMatch(/^[0-9a-f]{40}-dirty$/);
});
});
describe('readBuildSha dirty rules against a real repository', () => {
const made2 = [];
afterEach(() => {
made2.splice(0).forEach((d) => rmSync(d, { recursive: true, force: true }));
});
const TEMP = 'vite.config.js.timestamp-1700000000-abc123.mjs';
const repo2 = (tracked = []) => {
const dir = mkdtempSync(join(tmpdir(), 'buildsha-'));
made2.push(dir);
const g = (...a) => execFileSync('git', a, { cwd: dir, stdio: 'ignore' });
g('init', '-q');
mkdirSync(join(dir, 'src'));
writeFileSync(join(dir, 'src', 'a.ts'), 'export {};\n');
tracked.forEach((f) => writeFileSync(join(dir, f), 'x\n'));
g('add', '.');
g('-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'x');
return {
dir,
head: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: dir, encoding: 'utf8' }).trim(),
};
};
it('does not let an explicit BUILD_SHA mask a dirty tree', () => {
const { dir, head } = repo2();
const run = gitIn(dir);
expect(readBuildSha({ BUILD_SHA: head }, run)).toBe(head);
writeFileSync(join(dir, 'src', 'zz-stray.ts'), '');
expect(readBuildSha({ BUILD_SHA: head }, run)).toBe(`${head}-dirty`);
});
it('lets git speak only for a tree whose root it is: an archive unpacked inside another repository keeps its explicit sha', () => {
const { dir } = repo2();
const inner = join(dir, 'vendor', 'ratatoskr');
mkdirSync(inner, { recursive: true });
writeFileSync(join(inner, 'x.ts'), '');
expect(readBuildSha({ BUILD_SHA: SHA }, gitIn(inner))).toBe(SHA);
expect(readBuildSha({}, gitIn(inner))).toBe('unknown');
});
it("notices an untracked .mjs that is not vite's temp file", () => {
const { dir, head } = repo2();
writeFileSync(join(dir, 'foo.mjs'), '');
expect(readBuildSha({}, gitIn(dir))).toBe(`${head}-dirty`);
rmSync(join(dir, 'foo.mjs'));
// only vite's exact shape is its own: vite.config.<ext>.timestamp-<digits>-<hex>.mjs
[
'vite.config.js.timestamp-1-ab.mjs.bak',
'vite.config.js.timestamp-x-ab.mjs',
'vite.config.js.timestamp-1-zz.mjs',
'vite.config.a.b.timestamp-1-ab.mjs',
'vite.config.js.timestamp-1-ab-c.mjs',
].forEach((name) => {
writeFileSync(join(dir, name), '');
expect(readBuildSha({}, gitIn(dir)), name).toBe(`${head}-dirty`);
rmSync(join(dir, name));
});
expect(readBuildSha({}, gitIn(dir))).toBe(head);
});
it('treats a stray source file as dirty even beside the vite temp file, in the root or a subfolder', () => {
const { dir, head } = repo2();
const run = gitIn(dir);
writeFileSync(join(dir, TEMP), '');
writeFileSync(join(dir, 'src', TEMP), '');
expect(readBuildSha({}, run)).toBe(head);
writeFileSync(join(dir, 'src', 'zz-stray.ts'), '');
expect(readBuildSha({}, run)).toBe(`${head}-dirty`);
});
it('marks a tracked file of the temp name dirty once it changes', () => {
const { dir, head } = repo2([TEMP]);
const run = gitIn(dir);
expect(readBuildSha({}, run)).toBe(head);
writeFileSync(join(dir, TEMP), 'changed\n');
expect(readBuildSha({}, run)).toBe(`${head}-dirty`);
});
it('marks an untracked file in a new folder dirty (status lists files, not the folder)', () => {
const { dir, head } = repo2();
mkdirSync(join(dir, 'new'));
writeFileSync(join(dir, 'new', TEMP), '');
expect(readBuildSha({}, gitIn(dir))).toBe(head);
writeFileSync(join(dir, 'new', 'b.ts'), '');
expect(readBuildSha({}, gitIn(dir))).toBe(`${head}-dirty`);
});
});
describe('buildShaPlugin', () => {
it("hands vite a meta tag for the page's head carrying the sha", () => {
const plugin = buildShaPlugin(SHA);
expect(plugin.transformIndexHtml()).toEqual([
it('emits a build-sha meta tag', () => {
expect(buildShaPlugin(SHA).transformIndexHtml()).toEqual([
{ tag: 'meta', attrs: { name: 'build-sha', content: SHA }, injectTo: 'head-prepend' },
]);
});

View file

@ -1,48 +0,0 @@
import { readFileSync } from 'fs';
import { describe, expect, it } from 'vitest';
import zlib from 'zlib';
import { compile, processVanillaFile } from '@vanilla-extract/integration';
// A long reply quote (nowrap) sized the own-message row to 782px on a 390px phone. The row, the column and the bubble
// must be able to shrink to their parent, so pin the emitted declarations (as phoneTapTargets.test.ts does).
const emitted = async () => {
const filePath = `${process.cwd()}/src/app/components/message/layout/layout.css.ts`;
const { source } = await compile({ filePath, cwd: process.cwd(), identOption: 'debug' });
const code = await processVanillaFile({ source, filePath, identOption: 'debug' });
const bytes = Buffer.from(
(code.match(/source=#?([A-Za-z0-9+/=]+)/) as RegExpMatchArray)[1],
'base64'
);
return (bytes[0] === 0x1f && bytes[1] === 0x8b ? zlib.gunzipSync(bytes) : bytes).toString();
};
const declarations = (css: string, className: string): string[] => {
const rule = new RegExp(`^\\.layout_${className}__[\\w-]+ \\{\\n([^}]*)\\}`, 'm').exec(css);
expect(rule, `no .layout_${className} rule emitted`).toBeTruthy();
return (rule as RegExpExecArray)[1].split('\n').map((l) => l.trim().replace(/;$/, ''));
};
describe('bubble rows shrink to their column', () => {
it.each([
['BubbleColumn', ['min-width: 0']],
['BubbleContentRow', ['min-width: 0', 'max-width: 100%']],
['BubbleContent', ['min-width: 0']],
])('%s', async (name, expected) => {
const css = await emitted();
expect(declarations(css, name)).toEqual(expect.arrayContaining(expected));
});
it('BubbleContent keeps its 800px cap inside the column width', async () => {
const css = await emitted();
expect(declarations(css, 'BubbleContent').join('\n')).toMatch(/max-width: min\(100%, 50rem\)/);
});
it('Bubble.tsx puts BubbleColumn on the column and BubbleContentRow on the row', () => {
const tsx = readFileSync(
`${process.cwd()}/src/app/components/message/layout/Bubble.tsx`,
'utf8'
);
expect(tsx).toMatch(/classNames\(css\.BubbleColumn,/);
expect(tsx).toMatch(/<Box className=\{css\.BubbleContentRow\}>/);
});
});

View file

@ -1,113 +0,0 @@
import { describe, expect, it } from 'vitest';
import zlib from 'zlib';
import { compile, processVanillaFile } from '@vanilla-extract/integration';
import { FOOTER_TINT, SKY_PLATE_FALLBACK } from '../../features/scene/skyPlate';
import { AuthFooter } from './styles.css';
// The CSS styles.css.ts emits for the sign-in footer, read back from vanilla-extract's own compile.
const emitted = async () => {
const filePath = `${process.cwd()}/src/app/pages/auth/styles.css.ts`;
const { source } = await compile({ filePath, cwd: process.cwd(), identOption: 'debug' });
const code = await processVanillaFile({ source, filePath, identOption: 'debug' });
const encoded = (code.match(/source=#([A-Za-z0-9+/=]+)/) as RegExpMatchArray)[1];
return zlib.gunzipSync(Buffer.from(encoded, 'base64')).toString();
};
const declarations = (css: string, selector: string) =>
[...css.matchAll(/^([^{}\n]+) \{\n([^}]*)\}/gm)]
.filter((m) => m[1] === selector)
.map((m) =>
m[2]
.split('\n')
.map((l) => l.trim().replace(/;$/, ''))
.filter(Boolean)
);
describe('the sign-in footer band, as emitted', () => {
const over = `:root[data-scene] .${AuthFooter}`;
it('is one rule over the scene, so no later rule can override its mask', async () => {
expect(declarations(await emitted(), over)).toHaveLength(1);
});
it('puts the plate fill before the color-mix tint, so a browser without color-mix keeps the fill', async () => {
const [rule] = declarations(await emitted(), over);
const fills = rule.filter((d) => d.startsWith('background-color:'));
expect(fills).toHaveLength(2);
expect(fills[0]).toBe(`background-color: var(--sky-bubble, ${SKY_PLATE_FALLBACK.fill})`);
});
it('tints with FOOTER_TINT of the plate fill, the amount skyTheme.test.ts checks the ink against', async () => {
const [rule] = declarations(await emitted(), over);
const fills = rule.filter((d) => d.startsWith('background-color:'));
expect(fills[1]).toBe(
`background-color: color-mix(in srgb, var(--sky-bubble, ${SKY_PLATE_FALLBACK.fill}) ${
FOOTER_TINT * 100
}%, transparent)`
);
});
it("is inked with the plate's ink, on the footer and on its links", async () => {
const css = await emitted();
const ink = `color: var(--sky-bubble-text, ${SKY_PLATE_FALLBACK.text})`;
expect(declarations(css, over)[0].filter((d) => d.startsWith('color:'))).toEqual([ink]);
expect(declarations(css, `${over} a`)).toEqual([[ink]]);
});
it('blurs what is behind it by 12px, the radius of the chat bubbles', async () => {
const [rule] = declarations(await emitted(), over);
expect(rule.filter((d) => d.startsWith('backdrop-filter'))).toEqual([
'backdrop-filter: blur(12px)',
]);
});
it('declares exactly these properties, so nothing else (a shadow, a stray override) rides along', async () => {
const [rule] = declarations(await emitted(), over);
// -webkit-backdrop-filter is the one prefixed property, for Safari 14; it must blur exactly as the standard one does.
const blur = (prop: string) =>
rule
.find((d) => d.startsWith(`${prop}:`))
?.split(':')[1]
.trim();
expect(blur('-webkit-backdrop-filter')).toBe(blur('backdrop-filter'));
expect(rule.map((d) => d.slice(0, d.indexOf(':'))).sort()).toEqual([
'-webkit-backdrop-filter',
'backdrop-filter',
'background-color',
'background-color',
'color',
'mask-composite',
'mask-image',
'padding-bottom',
'padding-top',
]);
});
it('fades along both axes over a soft ramp, not a hard edge', async () => {
const [rule] = declarations(await emitted(), over);
const mask = rule.find((d) => d.startsWith('mask-image:')) ?? '';
expect(rule).toContain('mask-composite: intersect');
['bottom', 'right'].forEach((axis) => {
const ramp = mask.match(
new RegExp(
`linear-gradient\\(to ${axis}, transparent, #000 (\\d+)px, #000 calc\\(100% - (\\d+)px\\), transparent\\)`
)
);
expect(ramp).not.toBeNull();
// Each end ramps from clear to opaque over at least 8px.
expect(Number(ramp?.[1])).toBeGreaterThanOrEqual(8);
expect(Number(ramp?.[2])).toBeGreaterThanOrEqual(8);
});
});
it('has no border or radius, in the scene rule or in the base footer rule', async () => {
const css = await emitted();
const [rule] = declarations(css, over);
const base = declarations(css, `.${AuthFooter}`);
expect(base).toHaveLength(1);
[rule, base[0]].forEach((r) => {
expect(r.filter((d) => /^(border|outline)/.test(d))).toEqual([]);
});
// The base rule is only the footer's padding: nothing visible (a shadow, a fill) is hidden outside the scene rule.
expect(base[0].map((d) => d.slice(0, d.indexOf(':')))).toEqual(['padding']);
});
});