chore(quality): ratchet Oxlint, React Doctor, and Zustand performance (#11034)

* chore(quality): ratchet lint and Zustand performance

* fix(ci): stabilize React peer lock snapshot

* fix(ci): isolate PR diff and React Doctor CLI
This commit is contained in:
Neil
2026-07-27 18:58:36 -07:00
committed by GitHub
parent 9a8e21a47e
commit 12ef12c55b
18 changed files with 1324 additions and 143 deletions
@@ -0,0 +1,76 @@
import { spawnSync } from 'node:child_process'
import { mkdtempSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { describe, expect, it } from 'vitest'
const pluginPath = path.resolve('config/oxlint-plugins/app-store-performance.mjs')
const oxlintPath = path.resolve(
process.platform === 'win32' ? 'node_modules/.bin/oxlint.cmd' : 'node_modules/.bin/oxlint'
)
function lintSource(source) {
const directory = mkdtempSync(path.join(tmpdir(), 'orca-app-store-lint-'))
const sourcePath = path.join(directory, 'sample.tsx')
const configPath = path.join(directory, 'oxlint.json')
writeFileSync(sourcePath, source)
writeFileSync(
configPath,
JSON.stringify({
categories: {
correctness: 'off'
},
jsPlugins: [{ name: 'app-store-performance', specifier: pluginPath }],
rules: {
'app-store-performance/require-selector': 'warn',
'app-store-performance/no-identity-selector': 'warn',
'app-store-performance/no-fresh-selector-result': 'warn'
}
})
)
const result = spawnSync(oxlintPath, ['--config', configPath, '--format', 'json', sourcePath], {
encoding: 'utf8'
})
if (result.error) {
throw result.error
}
expect(result.status).toBe(0)
return JSON.parse(result.stdout).diagnostics
}
describe('app store performance Oxlint plugin', () => {
it('reports whole-store and fresh-reference subscriptions', () => {
const diagnostics = lintSource(`
import { useAppStore as useStore } from '@/store'
const WholeStore = () => useStore()
const Identity = () => useStore((state) => state)
const Fresh = () => useStore((state) => ({ active: state.active }))
const Conditional = () => useStore((state) => state.active ? state.items : [])
const Nested = () => useStore((state) => {
if (state.active) return state.items.filter(Boolean)
return state.items
})
`)
expect(diagnostics.map((diagnostic) => diagnostic.code)).toEqual([
'app-store-performance(require-selector)',
'app-store-performance(no-identity-selector)',
'app-store-performance(no-fresh-selector-result)',
'app-store-performance(no-fresh-selector-result)',
'app-store-performance(no-fresh-selector-result)'
])
})
it('allows focused, cached, and useShallow selectors', () => {
const diagnostics = lintSource(`
import { useAppStore } from '@/store'
import { useShallow as shallow } from 'zustand/react/shallow'
const selectActive = (state) => state.active
const Focused = () => useAppStore(selectActive)
const Cached = () => useAppStore((state) => state.cachedProjection)
const Shallow = () => useAppStore(shallow((state) => ({ active: state.active })))
`)
expect(diagnostics).toEqual([])
})
})
@@ -0,0 +1,225 @@
import { execFileSync, spawnSync } from 'node:child_process'
import { existsSync, readFileSync } from 'node:fs'
import path from 'node:path'
import process from 'node:process'
import { pathToFileURL } from 'node:url'
import { resolvePullRequestDiffBase } from './git-pull-request-diff-base.mjs'
const SOURCE_FILE_PATTERN = /\.(?:[cm]?[jt]sx?)$/
const OXLINT_SCANS = [
{
label: 'code quality',
args: [
'--config',
'config/oxlint-code-quality.json',
'--report-unused-disable-directives-severity',
'warn'
]
},
{
label: 'type-aware code quality',
args: ['--type-aware', '--config', 'config/oxlint-code-quality-type-aware.json']
},
{
label: 'React Doctor',
args: ['--config', 'config/oxlint-react-doctor.json']
}
]
export function parseAddedLineRanges(diff) {
const ranges = []
const hunkPattern = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/
for (const line of diff.split(/\r?\n/)) {
const match = hunkPattern.exec(line)
if (!match) {
continue
}
const start = Number.parseInt(match[1], 10)
const count = match[2] === undefined ? 1 : Number.parseInt(match[2], 10)
if (count > 0) {
ranges.push({ start, end: start + count - 1 })
}
}
return ranges
}
export function overlapsAddedLines(startLine, endLine, ranges) {
return ranges.some((range) => startLine <= range.end && endLine >= range.start)
}
function runGit(root, args, options = {}) {
return execFileSync('git', args, {
cwd: root,
encoding: options.encoding ?? 'utf8',
maxBuffer: 64 * 1024 * 1024
})
}
function splitNullDelimited(output) {
return output.split('\0').filter(Boolean)
}
function resolveBase(root, requestedBase) {
for (const candidate of [
requestedBase,
process.env.ORCA_CODE_QUALITY_BASE,
'origin/main',
'main'
]) {
if (!candidate) {
continue
}
const result = spawnSync('git', ['rev-parse', '--verify', `${candidate}^{commit}`], {
cwd: root,
stdio: 'ignore'
})
if (result.status === 0) {
return candidate
}
}
throw new Error('Pass the pull request base SHA or make origin/main available locally.')
}
export function collectAddedLineRanges(root, requestedBase) {
const base = resolveBase(root, requestedBase)
const mergeBase = runGit(root, ['merge-base', base, 'HEAD']).trim()
const comparisonBase = resolvePullRequestDiffBase(root, mergeBase)
const changedFiles = splitNullDelimited(
runGit(root, ['diff', '--name-only', '-z', '--diff-filter=ACMRTUB', comparisonBase, '--'])
)
const untrackedFiles = splitNullDelimited(
runGit(root, ['ls-files', '--others', '--exclude-standard', '-z'])
)
const rangesByFile = new Map()
for (const file of changedFiles) {
if (!SOURCE_FILE_PATTERN.test(file) || !existsSync(path.join(root, file))) {
continue
}
const diff = runGit(root, ['diff', '--unified=0', '--no-color', comparisonBase, '--', file])
const ranges = parseAddedLineRanges(diff)
if (ranges.length > 0) {
rangesByFile.set(file, ranges)
}
}
for (const file of untrackedFiles) {
const absolutePath = path.join(root, file)
if (!SOURCE_FILE_PATTERN.test(file) || !existsSync(absolutePath)) {
continue
}
const lineCount = readFileSync(absolutePath, 'utf8').split(/\r?\n/).length
rangesByFile.set(file, [{ start: 1, end: lineCount }])
}
return { base, comparisonBase, rangesByFile }
}
function parseOxlintOutput(stdout, label) {
const start = stdout.indexOf('{')
const end = stdout.lastIndexOf('}')
if (start === -1 || end === -1) {
throw new Error(`${label} did not return Oxlint JSON output.`)
}
return JSON.parse(stdout.slice(start, end + 1))
}
function normalizedDiagnosticPath(root, filename) {
const absolutePath = path.isAbsolute(filename) ? filename : path.join(root, filename)
return path.relative(root, absolutePath).split(path.sep).join('/')
}
function diagnosticLineRange(root, filename, span) {
const startLine = span.line
if (!Number.isInteger(startLine)) {
return null
}
if (!Number.isInteger(span.offset) || !Number.isInteger(span.length) || span.length === 0) {
return { start: startLine, end: startLine }
}
const absolutePath = path.isAbsolute(filename) ? filename : path.join(root, filename)
const source = readFileSync(absolutePath)
const highlighted = source.subarray(span.offset, span.offset + span.length).toString('utf8')
return { start: startLine, end: startLine + (highlighted.match(/\n/g)?.length ?? 0) }
}
export function diagnosticTouchesAddedLines(diagnostic, rangesByFile, root = process.cwd()) {
const file = normalizedDiagnosticPath(root, diagnostic.filename)
const ranges = rangesByFile.get(file)
if (!ranges) {
return false
}
return (diagnostic.labels ?? []).some((label) => {
const lineRange = diagnosticLineRange(root, diagnostic.filename, label.span)
return lineRange !== null && overlapsAddedLines(lineRange.start, lineRange.end, ranges)
})
}
function annotationValue(value) {
return String(value).replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A')
}
function printDiagnostic(diagnostic, root) {
const file = normalizedDiagnosticPath(root, diagnostic.filename)
const line = diagnostic.labels?.[0]?.span?.line ?? 1
const code = diagnostic.code ?? 'oxlint'
console.error(
`::error file=${annotationValue(file)},line=${line},title=${annotationValue(code)}::${annotationValue(diagnostic.message)}`
)
console.error(`${file}:${line} ${code}: ${diagnostic.message}`)
}
function runOxlintScan(root, scan, files) {
const pnpm = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm'
const result = spawnSync(pnpm, ['exec', 'oxlint', ...scan.args, '--format', 'json', ...files], {
cwd: root,
encoding: 'utf8',
maxBuffer: 128 * 1024 * 1024
})
if (result.error) {
throw result.error
}
if (!result.stdout.trim()) {
process.stderr.write(result.stderr)
throw new Error(`${scan.label} failed before producing diagnostics.`)
}
return parseOxlintOutput(result.stdout, scan.label).diagnostics ?? []
}
export function main(
root = process.cwd(),
requestedBase = process.argv.slice(2).find((argument) => argument !== '--')
) {
const { base, comparisonBase, rangesByFile } = collectAddedLineRanges(root, requestedBase)
const files = [...rangesByFile.keys()]
if (files.length === 0) {
console.log(`Changed-code quality gate: no changed JavaScript or TypeScript since ${base}.`)
return 0
}
let failures = 0
for (const scan of OXLINT_SCANS) {
const diagnostics = runOxlintScan(root, scan, files).filter((diagnostic) =>
diagnosticTouchesAddedLines(diagnostic, rangesByFile, root)
)
for (const diagnostic of diagnostics) {
printDiagnostic(diagnostic, root)
}
failures += diagnostics.length
console.log(
`${scan.label}: ${diagnostics.length} new finding(s) across ${files.length} changed file(s).`
)
}
if (failures > 0) {
console.error(
`Changed-code quality gate failed with ${failures} finding(s) since ${comparisonBase.slice(0, 12)}.`
)
return 1
}
console.log(`Changed-code quality gate passed since ${comparisonBase.slice(0, 12)}.`)
return 0
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
process.exit(main())
}
@@ -0,0 +1,44 @@
import { describe, expect, it } from 'vitest'
import {
diagnosticTouchesAddedLines,
overlapsAddedLines,
parseAddedLineRanges
} from './check-changed-code-quality.mjs'
describe('changed-code quality line matching', () => {
it('parses added and replaced hunk ranges while ignoring deletions', () => {
const ranges = parseAddedLineRanges(
['@@ -10,2 +10,3 @@', '@@ -20 +21 @@', '@@ -40,4 +42,0 @@', '@@ -50 +48,2 @@'].join('\n')
)
expect(ranges).toEqual([
{ start: 10, end: 12 },
{ start: 21, end: 21 },
{ start: 48, end: 49 }
])
})
it('matches diagnostics that overlap any added line', () => {
const ranges = [
{ start: 5, end: 7 },
{ start: 12, end: 12 }
]
expect(overlapsAddedLines(3, 5, ranges)).toBe(true)
expect(overlapsAddedLines(8, 11, ranges)).toBe(false)
expect(overlapsAddedLines(12, 14, ranges)).toBe(true)
})
it('normalizes absolute diagnostic paths before matching', () => {
const root = process.cwd()
const file = 'config/scripts/check-changed-code-quality.test.mjs'
const diagnostic = {
filename: `${root}/${file}`,
labels: [{ span: { line: 24 } }]
}
expect(
diagnosticTouchesAddedLines(diagnostic, new Map([[file, [{ start: 24, end: 24 }]]]), root)
).toBe(true)
})
})
@@ -0,0 +1,35 @@
import { spawnSync } from 'node:child_process'
import process from 'node:process'
import { resolvePullRequestDiffBase } from './git-pull-request-diff-base.mjs'
const requestedBase =
process.argv.slice(2).find((argument) => argument !== '--') ??
process.env.ORCA_CODE_QUALITY_BASE ??
'origin/main'
const base = resolvePullRequestDiffBase(process.cwd(), requestedBase)
const pnpm = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm'
const result = spawnSync(
pnpm,
[
'dlx',
'react-doctor@0.9.1',
'.',
'--yes',
'--scope',
'lines',
'--base',
base,
'--include-untracked',
'--no-dead-code',
'--no-supply-chain',
'--no-telemetry',
'--blocking',
'error'
],
{ stdio: 'inherit' }
)
if (result.error) {
throw result.error
}
process.exit(result.status ?? 1)
@@ -0,0 +1,23 @@
import { execFileSync } from 'node:child_process'
import process from 'node:process'
export function selectPullRequestDiffBase(requestedBase, headParents, eventName) {
if (eventName === 'pull_request' && headParents.length >= 2) {
return headParents[0]
}
return requestedBase
}
export function resolvePullRequestDiffBase(
root,
requestedBase,
eventName = process.env.GITHUB_EVENT_NAME
) {
const [, ...headParents] = execFileSync('git', ['rev-list', '--parents', '-n', '1', 'HEAD'], {
cwd: root,
encoding: 'utf8'
})
.trim()
.split(/\s+/)
return selectPullRequestDiffBase(requestedBase, headParents, eventName)
}
@@ -0,0 +1,19 @@
import { describe, expect, it } from 'vitest'
import { selectPullRequestDiffBase } from './git-pull-request-diff-base.mjs'
describe('pull request diff base selection', () => {
it('uses the merge commit first parent for pull request checkouts', () => {
expect(
selectPullRequestDiffBase('event-base', ['current-base', 'pull-request-head'], 'pull_request')
).toBe('current-base')
})
it('keeps the requested base outside synthetic pull request merges', () => {
expect(selectPullRequestDiffBase('requested-base', ['parent'], 'pull_request')).toBe(
'requested-base'
)
expect(selectPullRequestDiffBase('requested-base', ['parent', 'other'], 'push')).toBe(
'requested-base'
)
})
})
@@ -0,0 +1,47 @@
import { spawnSync } from 'node:child_process'
import { mkdtempSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { describe, expect, it } from 'vitest'
const pluginPath = path.resolve('config/oxlint-plugins/mobile-pairing-qrcode-import.mjs')
const oxlintPath = path.resolve(
process.platform === 'win32' ? 'node_modules/.bin/oxlint.cmd' : 'node_modules/.bin/oxlint'
)
function lintSource(source) {
const directory = mkdtempSync(path.join(tmpdir(), 'orca-qrcode-import-lint-'))
const sourcePath = path.join(directory, 'sample.ts')
const configPath = path.join(directory, 'oxlint.json')
writeFileSync(sourcePath, source)
writeFileSync(
configPath,
JSON.stringify({
categories: { correctness: 'off' },
jsPlugins: [{ name: 'mobile-pairing', specifier: pluginPath }],
rules: { 'mobile-pairing/no-eager-qrcode-import': 'error' }
})
)
const result = spawnSync(oxlintPath, ['--config', configPath, '--format', 'json', sourcePath], {
encoding: 'utf8'
})
if (result.error) {
throw result.error
}
return JSON.parse(result.stdout).diagnostics
}
describe('mobile pairing qrcode import rule', () => {
it('rejects eager runtime imports', () => {
const diagnostics = lintSource("import QRCode from 'qrcode'\nvoid QRCode")
expect(diagnostics.map((diagnostic) => diagnostic.code)).toEqual([
'mobile-pairing(no-eager-qrcode-import)'
])
})
it('allows type-only and lazy imports', () => {
expect(lintSource("import type QRCode from 'qrcode'\nlet qr: typeof QRCode")).toEqual([])
expect(lintSource("const QRCode = await import('qrcode')\nvoid QRCode")).toEqual([])
})
})
@@ -0,0 +1,81 @@
#!/usr/bin/env node
import { performance } from 'node:perf_hooks'
import process from 'node:process'
import { createStore } from 'zustand/vanilla'
const SUBSCRIBERS = Number.parseInt(process.env.ORCA_ZUSTAND_BENCH_SUBSCRIBERS ?? '2500', 10)
const WRITES = Number.parseInt(process.env.ORCA_ZUSTAND_BENCH_WRITES ?? '2000', 10)
const MAX_MILLISECONDS_PER_WRITE = Number.parseFloat(
process.env.ORCA_ZUSTAND_BENCH_MAX_MS_PER_WRITE ?? '5'
)
for (const [name, value] of [
['ORCA_ZUSTAND_BENCH_SUBSCRIBERS', SUBSCRIBERS],
['ORCA_ZUSTAND_BENCH_WRITES', WRITES],
['ORCA_ZUSTAND_BENCH_MAX_MS_PER_WRITE', MAX_MILLISECONDS_PER_WRITE]
]) {
if (!Number.isFinite(value) || value <= 0) {
throw new Error(`${name} must be positive, received ${value}`)
}
}
function measureRound() {
const stableProjection = Object.freeze({ activeRepoId: 'repo-1' })
const store = createStore(() => ({ unrelatedWrite: 0, stableProjection }))
let selectorRuns = 0
let renderInvalidations = 0
const unsubscribe = Array.from({ length: SUBSCRIBERS }, () => {
let previous = store.getState().stableProjection
return store.subscribe((state) => {
selectorRuns += 1
const next = state.stableProjection
if (!Object.is(previous, next)) {
renderInvalidations += 1
}
previous = next
})
})
const start = performance.now()
for (let index = 1; index <= WRITES; index += 1) {
store.setState({ unrelatedWrite: index })
}
const elapsed = performance.now() - start
for (const release of unsubscribe) {
release()
}
return { elapsed, selectorRuns, renderInvalidations }
}
measureRound()
const rounds = Array.from({ length: 5 }, measureRound).sort(
(left, right) => left.elapsed - right.elapsed
)
const median = rounds[2]
const expectedSelectorRuns = SUBSCRIBERS * WRITES
const millisecondsPerWrite = median.elapsed / WRITES
if (median.selectorRuns !== expectedSelectorRuns) {
throw new Error(
`Expected ${expectedSelectorRuns} selector runs, observed ${median.selectorRuns}; update the fan-out model.`
)
}
if (median.renderInvalidations !== 0) {
throw new Error(
`${median.renderInvalidations} unrelated writes changed a stable selector result.`
)
}
console.log(
`Zustand fan-out: ${SUBSCRIBERS} subscribers × ${WRITES} unrelated writes = ${expectedSelectorRuns.toLocaleString()} selector runs`
)
console.log(
`Median ${median.elapsed.toFixed(2)} ms total, ${millisecondsPerWrite.toFixed(4)} ms/write, 0 render invalidations`
)
if (process.argv.includes('--check') && millisecondsPerWrite > MAX_MILLISECONDS_PER_WRITE) {
console.error(
`Zustand fan-out exceeded ${MAX_MILLISECONDS_PER_WRITE.toFixed(2)} ms/write. Inspect selector work and store subscription growth.`
)
process.exit(1)
}