diff --git a/.github/workflows/backend-review.yml b/.github/workflows/backend-review.yml index 2845f4c4b2..3eed993d48 100644 --- a/.github/workflows/backend-review.yml +++ b/.github/workflows/backend-review.yml @@ -301,14 +301,19 @@ jobs: name: build-api path: packages/api/dist + - name: Use Bun 1.4.3 + uses: oven-sh/setup-bun@v2 + with: + bun-version: '1.4.3' + - name: Type check data-provider - run: npx tsc --noEmit -p packages/data-provider/tsconfig.json + run: bun check -p packages/data-provider/tsconfig.json - name: Type check data-schemas - run: npx tsc --noEmit -p packages/data-schemas/tsconfig.json + run: bun check -p packages/data-schemas/tsconfig.json - name: Type check @librechat/api - run: npx tsc --noEmit -p packages/api/tsconfig.json + run: bun check -p packages/api/tsconfig.json - name: OpenAPI spec drift check run: npm run -w @librechat/api openapi:check @@ -317,7 +322,7 @@ jobs: run: npm run -w @librechat/api openapi:test - name: Type check @librechat/client - run: npx tsc --noEmit -p packages/client/tsconfig.json + run: bun check -p packages/client/tsconfig.json circular-deps: name: Circular dependency checks diff --git a/.github/workflows/frontend-review.yml b/.github/workflows/frontend-review.yml index 682b410dec..bcb1616407 100644 --- a/.github/workflows/frontend-review.yml +++ b/.github/workflows/frontend-review.yml @@ -8,6 +8,7 @@ on: - 'packages/client/**' - 'packages/chat/**' - 'packages/data-provider/**' + - 'scripts/typecheck.mts' - 'package.json' - 'package-lock.json' - '.github/workflows/frontend-review.yml' @@ -23,6 +24,7 @@ on: - 'packages/client/**' - 'packages/chat/**' - 'packages/data-provider/**' + - 'scripts/typecheck.mts' - 'package.json' - 'package-lock.json' - '.github/workflows/frontend-review.yml' @@ -284,6 +286,11 @@ jobs: name: build-chat-package path: packages/chat/dist + - name: Use Bun 1.4.3 + uses: oven-sh/setup-bun@v2 + with: + bun-version: '1.4.3' + - name: Type check client run: npm run typecheck working-directory: client @@ -324,6 +331,11 @@ jobs: name: build-data-provider path: packages/data-provider/dist + - name: Use Bun 1.4.3 + uses: oven-sh/setup-bun@v2 + with: + bun-version: '1.4.3' + - name: Type check run: npm run typecheck working-directory: packages/chat diff --git a/client/package.json b/client/package.json index 2691a5020e..d036828c14 100644 --- a/client/package.json +++ b/client/package.json @@ -4,7 +4,7 @@ "description": "", "type": "module", "scripts": { - "typecheck": "tsc --noEmit", + "typecheck": "node ../scripts/typecheck.mts", "data-provider": "cd .. && npm run build:data-provider", "build:file": "cross-env NODE_ENV=production vite build --debug > vite-output.log 2>&1", "build": "cross-env NODE_ENV=production NODE_OPTIONS=--max-old-space-size=8192 vite build", diff --git a/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx index 13a4dc021d..65ba73a79f 100644 --- a/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx +++ b/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx @@ -1392,9 +1392,11 @@ describe('live disclosure ownership', () => { global.IntersectionObserver = originalObserver; }); beforeEach(() => { - const observer: IntersectionObserver = { + // Unannotated so the extra `scrollMargin` is accepted by DOM libs that predate it. + const observer = { root: null, rootMargin: '', + scrollMargin: '', thresholds: [], observe: jest.fn(), unobserve: jest.fn(), diff --git a/client/src/lib/rum/useRum.ts b/client/src/lib/rum/useRum.ts index 9e77697904..0482dbf82a 100644 --- a/client/src/lib/rum/useRum.ts +++ b/client/src/lib/rum/useRum.ts @@ -131,7 +131,7 @@ function ensureRumProxyAuth(proxyUrl: string): void { return originalFetch(input, init); }; - window.fetch = Object.assign(patchedFetch, { preconnect: window.fetch.preconnect }); + window.fetch = patchedFetch; rumProxyFetchPatched = true; } diff --git a/client/src/utils/__tests__/clock.spec.ts b/client/src/utils/__tests__/clock.spec.ts index e189bfe475..e9cf78ba71 100644 --- a/client/src/utils/__tests__/clock.spec.ts +++ b/client/src/utils/__tests__/clock.spec.ts @@ -67,7 +67,7 @@ describe('localeWeekStartsOn', () => { /** Deletes the engine's week data for the duration, so the region heuristic * is what answers, on every engine rather than only pre-Baseline-2024 ones. */ const withoutEngineWeekData = (run: () => void) => { - const proto = Intl.Locale.prototype as Intl.Locale & { + const proto = Intl.Locale.prototype as Omit & { getWeekInfo?: () => { firstDay: number }; weekInfo?: { firstDay: number }; }; diff --git a/client/src/utils/clock.ts b/client/src/utils/clock.ts index 10175d4411..2d9dccf179 100644 --- a/client/src/utils/clock.ts +++ b/client/src/utils/clock.ts @@ -176,12 +176,12 @@ const FALLBACK_REGION_WEEK_START = new Map([ ['MV', 5], ]); -/** `Intl.Locale.prototype.getWeekInfo`/`.weekInfo` (Baseline 2024) predate this - * project's TS lib target, so neither member is declared on `Intl.Locale` yet. */ -interface LocaleWithWeekInfo extends Intl.Locale { +/** `Intl.Locale.prototype.getWeekInfo`/`.weekInfo` (Baseline 2024) are missing from + * older TS libs and declared as always present by newer ones; both are optional here. */ +type LocaleWithWeekInfo = Omit & { getWeekInfo?: () => { firstDay: number }; weekInfo?: { firstDay: number }; -} +}; /** `globalThis.navigator` rather than the bare global: this module is imported * through `~/utils`, which server-side rendering and plain-node test runners diff --git a/client/tsconfig.json b/client/tsconfig.json index 582ce560c1..62fcbb38e5 100644 --- a/client/tsconfig.json +++ b/client/tsconfig.json @@ -15,6 +15,8 @@ "isolatedModules": true, "noImplicitAny": false, "noEmit": true, + "types": ["node", "jest", "@testing-library/jest-dom", "vite/client"], + "noUncheckedSideEffectImports": false, "jsx": "preserve", "paths": { "~/*": ["./src/*"], @@ -23,7 +25,6 @@ "librechat-data-provider/*": ["../packages/data-provider/*"] } }, - "types": ["node", "jest", "@testing-library/jest-dom"], "exclude": ["node_modules", "vite.config.ts"], "include": [ "src/**/*", diff --git a/e2e/specs/mock/scenarios/suppression-baseline.spec.ts b/e2e/specs/mock/scenarios/suppression-baseline.spec.ts index 49ac1510a8..903e5bdcd3 100644 --- a/e2e/specs/mock/scenarios/suppression-baseline.spec.ts +++ b/e2e/specs/mock/scenarios/suppression-baseline.spec.ts @@ -628,6 +628,10 @@ test.describe('the recorded design-rule backlog', () => { join(emptyRoot, 'scripts/static-checks.mts'), ); copyFileSync(resolve(repoRoot, 'scripts/i18n.mts'), join(emptyRoot, 'scripts/i18n.mts')); + copyFileSync( + resolve(repoRoot, 'scripts/typecheck.mts'), + join(emptyRoot, 'scripts/typecheck.mts'), + ); mkdirSync(join(emptyRoot, 'scripts/eslint'), { recursive: true }); copyFileSync( resolve(repoRoot, 'scripts/eslint/design.mjs'), @@ -1105,6 +1109,7 @@ function syntheticRoot(): string { for (const file of [ 'scripts/static-checks.mts', 'scripts/i18n.mts', + 'scripts/typecheck.mts', /** The local design rules the config registers and the runner validates against. */ 'scripts/eslint/design.mjs', 'scripts/eslint/chat.mjs', diff --git a/e2e/specs/mock/scenarios/typecheck.spec.ts b/e2e/specs/mock/scenarios/typecheck.spec.ts new file mode 100644 index 0000000000..02412d3083 --- /dev/null +++ b/e2e/specs/mock/scenarios/typecheck.spec.ts @@ -0,0 +1,137 @@ +import { spawnSync } from 'node:child_process'; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { tmpdir } from 'node:os'; +import { expect, test } from '@playwright/test'; +import { inOneProject, repoRoot, staticChecks } from './lint.helpers'; + +/** + * `scripts/typecheck.mts` is the type checker contributors and the frontend + * review jobs run: `bun check` when the installed Bun provides it, the + * repository's `tsc` otherwise. Each scenario runs the real script against a + * scratch project with a PATH it controls, so the choice of checker is what + * the scenario observes, whether or not the machine running it has Bun. + */ + +const SCRIPT = resolve(repoRoot, 'scripts/typecheck.mts'); + +interface Scratch { + dir: string; + project: string; + bin: string; +} + +/** A one-file strict project, with or without a type error, plus an empty bin dir. */ +function scratch(source: string): Scratch { + const dir = mkdtempSync(join(tmpdir(), 'lc-typecheck-')); + writeFileSync(join(dir, 'index.ts'), source); + writeFileSync( + join(dir, 'tsconfig.json'), + JSON.stringify({ + compilerOptions: { strict: true, noEmit: true, types: [], skipLibCheck: true }, + files: ['index.ts'], + }), + ); + const bin = join(dir, 'bin'); + mkdirSync(bin); + return { dir, project: join(dir, 'tsconfig.json'), bin }; +} + +/** A stand-in `bun` that logs its arguments; `check --help` answers `helpStatus`. */ +function fakeBun(bin: string, log: string, helpStatus: number, checkStatus: number): void { + const path = join(bin, 'bun'); + writeFileSync( + path, + [ + '#!/bin/sh', + `echo "$@" >> '${log}'`, + `if [ "$2" = "--help" ]; then exit ${helpStatus}; fi`, + `exit ${checkStatus}`, + '', + ].join('\n'), + ); + chmodSync(path, 0o755); +} + +/** Runs the script from the repository root with only `bin` and node on PATH. */ +function typecheck(bin: string, project: string) { + const result = spawnSync(process.execPath, [SCRIPT, '-p', project], { + cwd: repoRoot, + encoding: 'utf8', + env: { ...process.env, PATH: `${bin}:${dirname(process.execPath)}:/usr/bin:/bin` }, + }); + return { status: result.status, output: `${result.stdout ?? ''}${result.stderr ?? ''}` }; +} + +function logged(log: string): string { + return existsSync(log) ? readFileSync(log, 'utf8') : ''; +} + +test.describe('the shared type checker', () => { + test.beforeEach(inOneProject); + + test('a contributor with Bun gets bun check, and its verdict is the run verdict @scenario:typecheck-runs-bun-check-when-bun-provides-it', () => { + const { dir, project, bin } = scratch('export const value: number = 1;\n'); + const log = join(dir, 'bun.log'); + try { + fakeBun(bin, log, 0, 1); + const failing = typecheck(bin, project); + expect(failing.status, 'a failing bun check passed the run').toBe(1); + expect(logged(log)).toContain(`check -p ${project}`); + expect(failing.output).not.toContain('falling back to tsc'); + + fakeBun(bin, log, 0, 0); + expect(typecheck(bin, project).status, 'a passing bun check failed the run').toBe(0); + } finally { + rmSync(dir, { force: true, recursive: true }); + } + }); + + test('a contributor without Bun falls back to tsc, which still fails on a type error @scenario:typecheck-falls-back-to-tsc-without-bun', () => { + const broken = scratch("export const value: number = 'text';\n"); + const clean = scratch('export const value: number = 1;\n'); + try { + const failing = typecheck(broken.bin, broken.project); + expect(failing.output).toContain('falling back to tsc'); + expect(failing.output).toContain('TS2322'); + expect(failing.status, 'the fallback hid a type error').not.toBe(0); + + const passing = typecheck(clean.bin, clean.project); + expect(passing.output).toContain('falling back to tsc'); + expect(passing.status).toBe(0); + } finally { + rmSync(broken.dir, { force: true, recursive: true }); + rmSync(clean.dir, { force: true, recursive: true }); + } + }); + + test('a Bun release without the check command falls back to tsc @scenario:typecheck-falls-back-on-bun-without-check', () => { + const { dir, project, bin } = scratch("export const value: number = 'text';\n"); + const log = join(dir, 'bun.log'); + try { + fakeBun(bin, log, 1, 0); + const result = typecheck(bin, project); + expect(result.output).toContain('falling back to tsc'); + expect(result.output).toContain('TS2322'); + expect(result.status).not.toBe(0); + expect(logged(log), 'bun check ran although Bun reported no check command').not.toContain( + `check -p`, + ); + } finally { + rmSync(dir, { force: true, recursive: true }); + } + }); + + test('a change to the shared checker alone selects the TypeScript gate @scenario:a-checker-only-change-selects-the-typecheck-gate', () => { + const listed = staticChecks(['scripts/typecheck.mts', '--list', '--full']); + expect(listed.output).toMatch(/TypeScript \(typecheck\)\s+would run/); + }); +}); diff --git a/packages/api/tsconfig.json b/packages/api/tsconfig.json index 10246b7aa5..7ed6308871 100644 --- a/packages/api/tsconfig.json +++ b/packages/api/tsconfig.json @@ -8,7 +8,7 @@ "target": "es2015", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true, - "lib": ["es2017", "dom", "ES2021.String", "ES2021.WeakRef"], + "lib": ["es2017", "dom", "ES2021.String", "ES2021.WeakRef", "ES2022.Error"], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, @@ -18,6 +18,9 @@ "isolatedModules": true, "noEmit": true, "sourceMap": true, + // A few specs import client modules to assert both sides agree on a shared contract. + "rootDir": "../..", + "types": ["node", "jest", "multer", "passport", "bun"], "paths": { "~/*": ["./src/*"], // @librechat/agents ships declaration files that import its internal "@/" alias, which diff --git a/packages/chat/package.json b/packages/chat/package.json index 2605ea4b3c..37ddbcbf0f 100644 --- a/packages/chat/package.json +++ b/packages/chat/package.json @@ -53,7 +53,7 @@ "build": "npm run clean && tsdown", "b:build": "bun run b:clean && bun run tsdown", "build:watch": "tsdown --watch", - "typecheck": "tsc --noEmit", + "typecheck": "node ../../scripts/typecheck.mts", "test": "jest", "test:ci": "jest --ci" }, diff --git a/packages/client/tsconfig.json b/packages/client/tsconfig.json index 65b1eb1f72..fc04eaa76b 100644 --- a/packages/client/tsconfig.json +++ b/packages/client/tsconfig.json @@ -21,7 +21,9 @@ "~/*": ["./src/*"] }, "lib": ["ES2020", "DOM", "DOM.Iterable"], - "resolveJsonModule": true + "resolveJsonModule": true, + "types": ["node", "vite/client"], + "noUncheckedSideEffectImports": false }, "include": ["src/**/*"], "exclude": [ diff --git a/packages/data-provider/tsconfig.json b/packages/data-provider/tsconfig.json index b8ed29eb2a..66b6124161 100644 --- a/packages/data-provider/tsconfig.json +++ b/packages/data-provider/tsconfig.json @@ -5,7 +5,7 @@ "module": "esnext", "noImplicitAny": true, "outDir": "./types", - "target": "es5", + "target": "es2017", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true, "lib": ["es2017", "dom", "ES2021.String"], @@ -18,6 +18,7 @@ "isolatedModules": true, "noEmit": true, "sourceMap": true, + "types": ["node", "jest"], "paths": { "librechat-data-provider/react-query": ["./src/react-query/index.ts"], "src/*": ["./src/*"] diff --git a/packages/data-schemas/tsconfig.json b/packages/data-schemas/tsconfig.json index 76597facb6..f55b4e00b9 100644 --- a/packages/data-schemas/tsconfig.json +++ b/packages/data-schemas/tsconfig.json @@ -13,6 +13,7 @@ "forceConsistentCasingInFileNames": true, "resolveJsonModule": true, "sourceMap": true, + "types": ["node", "jest"], "paths": { "~/*": ["./src/*"] } diff --git a/scripts/static-checks.mts b/scripts/static-checks.mts index dc36fce501..55944b3233 100644 --- a/scripts/static-checks.mts +++ b/scripts/static-checks.mts @@ -58,6 +58,7 @@ import { import type { Dirent } from 'node:fs'; import { isTranslationReferenced } from './i18n.mts'; +import { resolveTypecheck } from './typecheck.mts'; const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); @@ -156,6 +157,7 @@ const FILTERS = { typecheck: [ 'client/**', 'packages/**', + 'scripts/typecheck.mts', 'package.json', 'package-lock.json', '.github/workflows/backend-review.yml', @@ -1905,13 +1907,17 @@ function findCircularDependencies(): CheckOutcome { // --------------------------------------------------------------- TypeScript /** - * One entry per `tsc --noEmit` the review workflows run. `paths` includes each - * project's upstream packages, so an edit to data-provider still typechecks the - * projects that consume it; `requires` lists the builds its imports resolve - * through, mirroring those jobs' dependency on the build artifacts. + * One entry per type check the review workflows run (`bun check`, or `tsc` + * without Bun). `paths` includes each project's upstream packages, so an edit + * to data-provider still typechecks the projects that consume it; `requires` + * lists the builds its imports resolve through, mirroring those jobs' + * dependency on the build artifacts. */ const ROOT_MANIFESTS = ['package.json', 'package-lock.json']; +/** The checker every project runs through, so a change to it rechecks them all. */ +const TYPECHECK_SCRIPT = 'scripts/typecheck.mts'; + /** Each imported gate reruns in CI when its owning workflow changes. */ const BACKEND_REVIEW = '.github/workflows/backend-review.yml'; const FRONTEND_REVIEW = '.github/workflows/frontend-review.yml'; @@ -1919,7 +1925,13 @@ const FRONTEND_REVIEW = '.github/workflows/frontend-review.yml'; const TYPECHECK_PROJECTS = [ { project: 'packages/data-provider/tsconfig.json', - paths: ['packages/data-provider/**', ...ROOT_MANIFESTS, BACKEND_REVIEW, '!**.md'], + paths: [ + 'packages/data-provider/**', + ...ROOT_MANIFESTS, + TYPECHECK_SCRIPT, + BACKEND_REVIEW, + '!**.md', + ], requires: [], }, { @@ -1928,6 +1940,7 @@ const TYPECHECK_PROJECTS = [ 'packages/data-provider/**', 'packages/data-schemas/**', ...ROOT_MANIFESTS, + TYPECHECK_SCRIPT, BACKEND_REVIEW, '!**.md', ], @@ -1940,6 +1953,7 @@ const TYPECHECK_PROJECTS = [ 'packages/data-schemas/**', 'packages/api/**', ...ROOT_MANIFESTS, + TYPECHECK_SCRIPT, BACKEND_REVIEW, '!**.md', ], @@ -1951,6 +1965,7 @@ const TYPECHECK_PROJECTS = [ 'packages/data-provider/**', 'packages/client/**', ...ROOT_MANIFESTS, + TYPECHECK_SCRIPT, BACKEND_REVIEW, '!**.md', ], @@ -1962,6 +1977,7 @@ const TYPECHECK_PROJECTS = [ 'packages/data-provider/**', 'packages/chat/**', ...ROOT_MANIFESTS, + TYPECHECK_SCRIPT, FRONTEND_REVIEW, '!**.md', ], @@ -1974,6 +1990,7 @@ const TYPECHECK_PROJECTS = [ 'packages/data-provider/**', 'packages/client/**', ...ROOT_MANIFESTS, + TYPECHECK_SCRIPT, FRONTEND_REVIEW, '!**.md', ], @@ -1987,15 +2004,15 @@ function runTypecheck(context: CheckContext): CheckOutcome { return { ok: true, skipped: 'no changed TypeScript project' }; } - const tsc = resolveBin('typescript', 'tsc'); - if (!tsc) return missingBin('typescript'); + const typecheck = resolveTypecheck(ROOT); + if (!typecheck) return missingBin('typescript'); const buildFailure = buildWorkspaces([...new Set(selected.flatMap((entry) => entry.requires))]); if (buildFailure) return buildFailure; const failures: string[] = []; for (const entry of selected) { - const result = runCommand(tsc, ['--noEmit', '-p', entry.project]); + const result = runCommand(typecheck, ['-p', entry.project]); if (result.status !== 0) { failures.push(`${entry.project}:\n${result.output.trim()}`); } diff --git a/scripts/typecheck.mts b/scripts/typecheck.mts new file mode 100644 index 0000000000..09e0ef9a0c --- /dev/null +++ b/scripts/typecheck.mts @@ -0,0 +1,53 @@ +/** + * Type-checks a TypeScript project with `bun check` when the installed Bun provides it, and + * with the repository's `tsc` otherwise, so Bun stays optional locally while CI runs the same + * checker. Both pass on every workspace config; `bun check` applies TypeScript 7 semantics. + * + * Usage: node scripts/typecheck.mts [-p ] + */ +import { fileURLToPath } from 'node:url'; +import { createRequire } from 'node:module'; +import { spawnSync } from 'node:child_process'; + +export interface TypecheckCommand { + checker: 'bun' | 'tsc'; + command: string; + /** Arguments before `-p `. */ + args: string[]; +} + +let bunCheck: boolean | undefined; + +/** Probes the subcommand rather than the binary: older Bun releases have no `check`. */ +function hasBunCheck(): boolean { + bunCheck ??= spawnSync('bun', ['check', '--help'], { stdio: 'ignore' }).status === 0; + return bunCheck; +} + +/** Resolves the checker to run, or null when neither Bun nor `typescript` is available. */ +export function resolveTypecheck(root: string): TypecheckCommand | null { + if (hasBunCheck()) { + return { checker: 'bun', command: 'bun', args: ['check'] }; + } + try { + const tsc = createRequire(import.meta.url).resolve('typescript/bin/tsc', { paths: [root] }); + return { checker: 'tsc', command: process.execPath, args: [tsc, '--noEmit'] }; + } catch { + return null; + } +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const typecheck = resolveTypecheck(process.cwd()); + if (!typecheck) { + console.error('typecheck: neither `bun check` nor typescript is available; run npm ci'); + process.exit(1); + } + if (typecheck.checker === 'tsc') { + console.error('typecheck: `bun check` is unavailable, falling back to tsc'); + } + const result = spawnSync(typecheck.command, [...typecheck.args, ...process.argv.slice(2)], { + stdio: 'inherit', + }); + process.exit(result.status ?? 1); +}