import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { type GenerationResult, logLevel } from './createReporter.ts' import { host } from './host.ts' import { fileReporter } from './reporters/fileReporter.ts' import { jsonReporter } from './reporters/jsonReporter.ts' import type { Config } from './types.ts' const context = { logLevel: logLevel.info } function result(overrides: Partial = {}): GenerationResult { return { config: { name: 'petstore', root: '/tmp', output: { path: 'src/gen' }, plugins: [] } as unknown as Config, diagnostics: [], filesCreated: 1, status: 'success', hrStart: process.hrtime(), ...overrides, } } describe('jsonReporter', () => { it('writes every config as one JSON array, without the diff patches', async () => { using stdout = vi.spyOn(process.stdout, 'write').mockImplementation(() => true) const check = { changed: true, files: [{ path: 'src/gen/pet.ts', status: 'modified' as const, linesAdded: 1, linesRemoved: 1, patch: '@@ -1 +1 @@' }] } await jsonReporter.report(result({ check }), context) await jsonReporter.report(result(), context) await jsonReporter.drain?.(context) expect(stdout).toHaveBeenCalledOnce() const reports = JSON.parse(String(stdout.mock.calls[0]?.[0])) as Array<{ check: { files: Array } }> expect(reports).toHaveLength(2) expect(reports[0]?.check.files[0]).toStrictEqual({ path: 'src/gen/pet.ts', status: 'modified', linesAdded: 1, linesRemoved: 1 }) }) }) describe('fileReporter', () => { let cwd: string beforeEach(() => { cwd = mkdtempSync(join(tmpdir(), 'kubb-file-reporter-')) vi.spyOn(host, 'cwd').mockReturnValue(cwd) }) afterEach(() => { vi.restoreAllMocks() rmSync(cwd, { recursive: true, force: true }) }) const failed = () => result({ status: 'failed', diagnostics: [{ code: 'KUBB_PLUGIN_FAILED', severity: 'error', message: '\u001b[31mboom\u001b[39m' }] }) it('writes nothing without diagnostics', async () => { await fileReporter.report(result(), context) expect(readdirSync(cwd)).toStrictEqual([]) }) it('writes the log as plain text and names its path', async () => { using error = vi.spyOn(console, 'error').mockImplementation(() => {}) await fileReporter.report(failed(), context) const [log] = readdirSync(join(cwd, '.kubb')) const content = readFileSync(join(cwd, '.kubb', log!), 'utf8') expect(content).toContain('boom') expect(content).not.toContain('\u001b[') expect(error).toHaveBeenCalledWith(expect.stringContaining('Debug log written to')) }) it('prints nothing at the silent log level', async () => { using error = vi.spyOn(console, 'error').mockImplementation(() => {}) await fileReporter.report(failed(), { logLevel: logLevel.silent }) expect(readdirSync(join(cwd, '.kubb'))).toHaveLength(1) expect(error).not.toHaveBeenCalled() }) })