Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
23 changes: 16 additions & 7 deletions .github/scripts/__tests__/agent-command-timeouts.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,16 @@ function toolUse(id: string, command: string, description?: string) {
};
}

function toolResult(id: string, toolUseResult: Record<string, unknown>) {
function toolResult(
id: string,
toolUseResult: {
timedOutAfterMs?: number;
stdout?: string;
stderr?: string;
interrupted?: boolean;
backgroundTaskId?: string;
},
) {
return {
type: 'user',
message: {
Expand All @@ -32,18 +41,18 @@ test('finds Bash calls that exceeded their timeout', () => {
toolResult('fast', { stdout: 'ok', stderr: '', interrupted: false }),
toolUse('slow', 'pnpm build-native --release', 'Rebuild binding'),
{ type: 'tool_progress', tool_use_id: 'slow-heartbeat-1', elapsed_time_seconds: 600 },
toolResult('slow', { backgroundTaskId: 'b1', timedOutAfterMs: 600000 }),
toolResult('slow', { backgroundTaskId: 'b1', timedOutAfterMs: 600_000 }),
{ type: 'result', is_error: true },
];

expect(findCommandTimeouts(messages)).toEqual([
{ command: 'pnpm build-native --release', description: 'Rebuild binding', timeoutMs: 600000 },
{ command: 'pnpm build-native --release', description: 'Rebuild binding', timeoutMs: 600_000 },
]);
});

test('keeps a timeout whose call is missing from the messages', () => {
expect(findCommandTimeouts([toolResult('unknown', { timedOutAfterMs: 120000 })])).toEqual([
{ command: '', description: undefined, timeoutMs: 120000 },
expect(findCommandTimeouts([toolResult('unknown', { timedOutAfterMs: 120_000 })])).toEqual([
{ command: '', description: undefined, timeoutMs: 120_000 },
]);
});

Expand All @@ -54,8 +63,8 @@ test('rejects an execution file without a message array', () => {
test('formats each command in a code block inside the list item', () => {
expect(
formatCommandTimeouts([
{ command: 'cargo check\ncargo shear', description: 'Check Rust', timeoutMs: 600000 },
{ command: 'echo ```', description: undefined, timeoutMs: 120000 },
{ command: 'cargo check\ncargo shear', description: 'Check Rust', timeoutMs: 600_000 },
{ command: 'echo ```', description: undefined, timeoutMs: 120_000 },
]),
).toBe(
[
Expand Down
6 changes: 3 additions & 3 deletions .github/scripts/__tests__/docs-fork-preview.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ await test('uses the package preview build and protected deployment pattern', as
deploy,
/workflow_run:\n\s+workflows: \['Build Docs Fork Preview'\]\n\s+types: \[completed\]/,
);
assert.doesNotMatch(deploy, /\n approve:/);
assert.doesNotMatch(deploy, /\n {2}approve:/);
const authorize = deploy.split('\n authorize:\n')[1].split('\n deploy:\n')[0];
assert.doesNotMatch(authorize, /environment:|secrets\.|: write/);
const job = deploy.split('\n deploy:\n')[1];
Expand Down Expand Up @@ -373,7 +373,7 @@ await test('pins an artifact to the triggering build attempt', async () => {
});

await test('validates build identities before making requests', async () => {
for (const value of [undefined, 0, -1, 1.5, NaN, '123', Number.MAX_SAFE_INTEGER + 1]) {
for (const value of [undefined, 0, -1, 1.5, Number.NaN, '123', Number.MAX_SAFE_INTEGER + 1]) {
for (const [runId, attempt] of [
[value, 1],
[123, value],
Expand Down Expand Up @@ -888,7 +888,7 @@ await test('rejects invalid PR numbers before using them in URLs or requests', a
0,
-1,
1.5,
NaN,
Number.NaN,
Number.MAX_SAFE_INTEGER + 1,
'2684',
'2684\nother-output=true',
Expand Down
18 changes: 7 additions & 11 deletions .github/scripts/__tests__/publish-npm-package.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,8 @@

import { describe, expect, test, vi } from 'vitest';

import {
type PublishCommandRunner,
type PublishNpmPackageOptions,
isAlreadyPublishedError,
publishNpmPackage,
} from '../publish-npm-package.ts';
import type { PublishCommandRunner, PublishNpmPackageOptions } from '../publish-npm-package.ts';
import { isAlreadyPublishedError, publishNpmPackage } from '../publish-npm-package.ts';
import type { FetchLike } from '../wait-for-npm-packages.ts';
import { response, stalledFetch } from './npm-registry.ts';

Expand All @@ -22,8 +18,8 @@ function options(fetchImpl: FetchLike, runCommand: PublishCommandRunner): Publis
registry: 'https://registry.npmjs.org',
fetchImpl,
runCommand,
log: vi.fn(),
warn: vi.fn(),
log: vi.fn<PublishNpmPackageOptions['log']>(),
warn: vi.fn<PublishNpmPackageOptions['warn']>(),
};
}

Expand Down Expand Up @@ -95,15 +91,15 @@ describe('publishNpmPackage', () => {
onTestFinished(() => {
vi.useRealTimers();
});
const fetchImpl = vi.fn(stalledFetch);
const fetchImpl = vi.fn<FetchLike>(stalledFetch);
const runCommand = vi.fn<PublishCommandRunner>().mockResolvedValue({
exitCode: 0,
output: 'published',
});
const publishOptions = options(fetchImpl, runCommand);
const result = publishNpmPackage(publishOptions);

await vi.advanceTimersByTimeAsync(9_999);
await vi.advanceTimersByTimeAsync(9999);
expect(runCommand).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1);

Expand Down Expand Up @@ -131,7 +127,7 @@ describe('publishNpmPackage', () => {
]),
)('resumes publication after $name fails (accepted=$accepted)', async ({ name, accepted }) => {
const published = new Set<string>();
const uploads: string[] = [];
const uploads: Array<string> = [];
let interrupted = false;
async function publishRelease() {
for (const packageName of releasePackages) {
Expand Down
4 changes: 2 additions & 2 deletions .github/scripts/__tests__/upgrade-deps-utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ test('selects the latest eligible stable Node.js 24 release independently of the
vi.unstubAllGlobals();
});
vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-11-12T00:00:00Z'));
const fetchMock = vi.fn().mockResolvedValue(
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(
Response.json([
{ version: 'v26.13.0', date: '2026-11-01', lts: 'Lithium' },
{ version: 'v24.9.0', date: '2026-11-01', lts: 'Krypton' },
Expand Down Expand Up @@ -60,6 +60,6 @@ test.each([
onTestFinished(() => {
vi.unstubAllGlobals();
});
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response()));
vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockResolvedValue(response()));
await expect(getLatestNodeVersion(24)).rejects.toThrow(error);
});
85 changes: 48 additions & 37 deletions .github/scripts/__tests__/upgrade-deps.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/// <reference types="node" />

import * as childProcess from 'node:child_process';
import { execFileSync } from 'node:child_process';
import {
copyFileSync,
mkdirSync,
Expand All @@ -15,18 +15,17 @@ import { dirname, join, resolve } from 'node:path';

import { expect, onTestFinished, test, vi } from 'vite-plus/test';

vi.mock('node:child_process', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:child_process')>();
return { ...actual, execFileSync: vi.fn(actual.execFileSync) };
});
import { readJsonObject as readJson, requireJsonObject } from '../../../scripts/json.ts';

vi.mock('node:child_process', { spy: true });

test.each([false, true])(
'runs the upgrade pipeline and retains metadata (install fails: %s)',
async (failInstall) => {
const root = resolve(import.meta.dirname, '../../..');
const { root: tempDir, metaDir, corePath, pluginPath, parserPath } = createSyncFixture();
onTestFinished(() => {
vi.mocked(childProcess.execFileSync).mockReset();
vi.mocked(execFileSync).mockReset();
vi.restoreAllMocks();
vi.unstubAllGlobals();
vi.unstubAllEnvs();
Expand Down Expand Up @@ -63,8 +62,8 @@ test.each([false, true])(
writeFileSync(
workspacePath,
readFileSync(workspacePath, 'utf8')
.replace(/ lint-staged: .+/, ' lint-staged: ^16.2.6')
.replace(/^ oxc-(?:minify|transform): .+\n/gm, ''),
.replace(/ {2}lint-staged: .+/, ' lint-staged: ^16.2.6')
.replaceAll(/^ {2}oxc-(?:minify|transform): .+\n/gm, ''),
);

vi.spyOn(process, 'cwd').mockReturnValue(tempDir);
Expand All @@ -76,6 +75,7 @@ test.each([false, true])(
const pinnedOxcNode = JSON.parse(
readFileSync(join(tempDir, 'packages/tools/.upstream-versions.json'), 'utf8'),
)['oxc-node'].hash;
const compareUrls: Array<string> = [];
vi.stubGlobal('fetch', async (url: string) => {
if (url === 'https://nodejs.org/dist/index.json') {
return Response.json([
Expand All @@ -87,7 +87,7 @@ test.each([false, true])(
]);
}
if (url.startsWith('https://api.github.com/repos/oxc-project/oxc-node/compare/')) {
expect(url).toContain(`/compare/${pinnedOxcNode}...`);
compareUrls.push(url);
return Response.json({ status: failInstall ? 'diverged' : 'ahead' });
}
if (url.startsWith('https://api.github.com/repos/')) {
Expand Down Expand Up @@ -137,10 +137,14 @@ test.each([false, true])(
}
throw new Error(`Unexpected request: ${url}`);
});
const commands: string[][] = [];
vi.mocked(childProcess.execFileSync).mockImplementation((command, args) => {
const commands: Array<Array<string>> = [];
let parserAtFinalInstall;
vi.mocked(execFileSync).mockImplementation((command, args) => {
expect(command).toBe('pnpm');
commands.push(args as string[]);
if (!Array.isArray(args)) {
throw new Error('Expected pnpm command arguments');
}
commands.push([...args]);
if (failInstall) {
throw new Error('Installation failed');
}
Expand All @@ -152,25 +156,35 @@ test.each([false, true])(
writeJson(parserPath, { version: '0.11.2' });
}
if (commands.length === 4) {
expect(readJson(corePath).dependencies['yuku-parser']).toBe('0.11.2');
parserAtFinalInstall = requireJsonObject(readJson(corePath).dependencies, corePath)[
'yuku-parser'
];
}
return Buffer.from('');
});

vi.resetModules();
if (failInstall) {
await expect(import('../upgrade-deps.ts')).rejects.toThrow('Installation failed');
expect(commands).toEqual([['install', '--no-frozen-lockfile']]);
expect(readJson(corePath).dependencies['yuku-parser']).toBe('^0.9.3');
} else {
await import('../upgrade-deps.ts');
expect(commands).toEqual([
['install', '--no-frozen-lockfile'],
['tool', 'sync-remote'],
['dedupe'],
['install', '--no-frozen-lockfile'],
]);
}
const failure = await import('../upgrade-deps.ts').then(
() => undefined,
(error: unknown) => error,
);
expect(failure).toEqual(failInstall ? new Error('Installation failed') : undefined);
expect(commands).toEqual(
failInstall
? [['install', '--no-frozen-lockfile']]
: [
['install', '--no-frozen-lockfile'],
['tool', 'sync-remote'],
['dedupe'],
['install', '--no-frozen-lockfile'],
],
);
expect(compareUrls).toEqual([expect.stringContaining(`/compare/${pinnedOxcNode}...`)]);
expect(parserAtFinalInstall).toBe(failInstall ? undefined : '0.11.2');
expect(readJson(corePath)).toHaveProperty(
['dependencies', 'yuku-parser'],
failInstall ? '^0.9.3' : '0.11.2',
);

expect(readFileSync(workspacePath, 'utf8')).toContain('\n lint-staged: ^17.5.1\n');
expect(readFileSync(workspacePath, 'utf8')).toContain("\n '@oxlint/plugins': =1.88.0\n");
Expand Down Expand Up @@ -211,9 +225,9 @@ test.each([false, true])(
? { old: pinnedOxcNode, new: pinnedOxcNode }
: { old: pinnedOxcNode, new: 'a'.repeat(40), tag: 'v1.2.3' },
);
if (!failInstall) {
expect(versions['yuku-parser']).toEqual({ old: '^0.9.3', new: '0.11.2' });
}
expect(versions['yuku-parser']).toEqual(
failInstall ? undefined : { old: '^0.9.3', new: '0.11.2' },
);
expect(readFileSync(join(metaDir, 'commit-message.txt'), 'utf8')).toContain(
'- lint-staged: 16.2.6 -> 17.5.1',
);
Expand All @@ -231,10 +245,6 @@ function writeJson(file: string, value: unknown) {
writeFileSync(file, JSON.stringify(value, null, 2) + '\n');
}

function readJson(file: string) {
return JSON.parse(readFileSync(file, 'utf8'));
}

function createSyncFixture() {
const root = mkdtempSync(join(tmpdir(), 'vite-plus-sync-bundled-deps-'));
onTestFinished(() => rmSync(root, { recursive: true, force: true }));
Expand Down Expand Up @@ -281,7 +291,7 @@ function createSyncFixture() {
});
writeJson(versionsPath, { oxlint: { old: '1.86.0', new: '1.87.0' } });
const run = () =>
childProcess.execFileSync(
execFileSync(
process.execPath,
[resolve(import.meta.dirname, '../upgrade-deps.ts'), '--sync-bundled-deps'],
{
Expand Down Expand Up @@ -324,7 +334,7 @@ test('pins the bundled parser, syncs Vite ranges, and preserves upgrade metadata
run();
expect(readJson(corePath).dependencies).not.toHaveProperty('yuku-ast');
expect(readJson(corePath).dependencies).not.toHaveProperty('yuku-codegen');
expect(readJson(corePath).dependencies['yuku-parser']).toBe('0.11.2');
expect(readJson(corePath)).toHaveProperty(['dependencies', 'yuku-parser'], '0.11.2');
expect(readJson(versionsPath)['yuku-parser']).toEqual({ old: '^0.9.3', new: '0.11.2' });
expect(readFileSync(join(metaDir, 'commit-message.txt'), 'utf8')).toContain(
'- yuku-parser: ^0.9.3 -> 0.11.2',
Expand Down Expand Up @@ -380,7 +390,7 @@ test('updates the parser pin when its installed version changes within the same
run();
writeJson(parserPath, { version: '0.10.4' });
run();
expect(readJson(corePath).dependencies['yuku-parser']).toBe('0.10.4');
expect(readJson(corePath)).toHaveProperty(['dependencies', 'yuku-parser'], '0.10.4');
expect(readJson(versionsPath)['yuku-parser']).toEqual({ old: '^0.9.3', new: '0.10.4' });
});

Expand All @@ -405,7 +415,8 @@ test.each([
] as const)('fails without writing core when upstream removes $name', ({ source, field, name }) => {
const fixture = createSyncFixture();
const pkg = readJson(fixture[source]);
delete pkg[field][name];
const dependencies = requireJsonObject(pkg[field], field);
delete dependencies[name];
writeJson(fixture[source], pkg);
const before = readFileSync(fixture.corePath, 'utf8');
expect(fixture.run).toThrow("review core's externals");
Expand Down
Loading
Loading