LibreChat/scripts/sort-imports.mts
Marco Beretta c00c776e0e
📦 feat: Scaffold the @librechat/chat Package (#16964)
* feat: Scaffold the @librechat/chat package

Adds packages/chat with core, react and components entries, a tsdown build,
a node-environment jest config, turbo and root build wiring, import boundary
rules, design-lint scope, and core types for the chat transport, stream,
host and status. No code moves yet.

* test: Cover the @librechat/chat boundaries as scenarios

* fix: Run the chat suite in test:turbo and build it for the mock lane

test:turbo now selects @librechat/chat, the mock e2e job builds the package the
chat-package scenarios load, and the synthetic repository in the suppression
scenarios carries the packages/chat/src root lint:design:record names.

* chore: Build the chat package in frontend:ci too

* chore: Run the chat suite in test:all

* fix: Hold core TSX to the chat boundary and scan the package for cycles

* fix: Apply the chat import boundary to JavaScript sources

* fix: Keep nested core files off the components entry

* fix: Close the remaining chat package gates and fence aborts by generation

Blocks imports through the @librechat/frontend workspace name, adds the chat
sources to the i18n scan, the CSS color gate and the client Tailwind content,
and lets ChatAbortRequest carry the generation it means to stop.

* fix: Keep JSX out of the chat core and carry abort and reconnect outcomes

Rejects JSX under the core, copies the chat manifest before the Docker
install, keys the client app build caches on the chat sources, fences
reconnects by generation, and types the abort result the transport returns.

* test: Give the CSS gate's scratch tree the chat root it now scans

* fix: Close the remaining @librechat/chat gates and wiring

Rejects import() and require() across the package boundaries, holds chat
components to the literal-copy rule, compiles TSX in the package's jest
transform, builds the package in Frontend Unit Tests, requires its test job for
main promotion, adds it to the unused-dependency scan, and lists it wherever a
sibling workspace is listed: Dockerfile.multi, the docker smoke paths, the
remaining node_modules caches, the reinstall helper, the bun build chain and
AGENTS.md.

* fix: Tighten the chat boundaries and carry steering and Assistants aborts

Template-literal import() and require() and self-imports through the package
name are rejected, user-facing JSX attributes need localized text, the cycle
scan resolves self-imports, Dockerfile.multi builds the package for the client
stage, and the transport carries steer, cancelSteer, armSteer and the
Assistants abort key.

* feat: Match the chat transport and host contracts to the client's

The transport now reports settled and replaced starts, the stream's protocol
version and resumed flag, reconnect replay, generation status, paused-run
resume with approvals or answers, abort and steer protocol versions, and the
request error shape. The host config and auth carry what the client's
ChatSettings now supplies: rename-while-running, model specs, retention mode
and the user.

* fix: Keep lazy React-entry loads out of the core and type the Assistants stop

Relative import() and require() of the /react entry from core are rejected,
and an abortKey stop resolves to the terminal conversation and run messages the
Assistants route returns.

* fix: Fence start controls by protocol and close extension-bearing entry loads

Settled and replaced start results carry the protocol version, core loads of
the /react or /components entry with a file extension are rejected, and
test:packages:chat builds data-provider first.
2026-10-10 21:00:10 +02:00

258 lines
7.2 KiB
TypeScript

#!/usr/bin/env node
/**
* Sorts imports across the LibreChat monorepo per project convention
* (AGENTS.md § Code style and performance):
*
* 1. Package value imports — shortest line to longest (`react` always first)
* 2. import type from packages — longest line to shortest
* 3. import type from local — longest line to shortest
* 4. Local value imports — longest line to shortest
*
* "Local" covers relative paths (`./`, `../`) and the workspace path aliases
* (`~/`, `src/`, `test/`). Workspace packages such as `librechat-data-provider`
* and `@librechat/*` are treated as package imports, not local.
*
* Runs on Node 24+ via native type-stripping (`.mts` keeps ESM semantics under
* the CommonJS repo root):
*
* Run: npm run sort-imports
* Check only: npm run sort-imports:check
* Targeted: node scripts/sort-imports.mts path/to/file.ts [...]
*/
import { readFile, writeFile, readdir } from 'node:fs/promises';
import { join, relative, resolve, sep, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
/** Source roots scanned when no explicit files are passed. */
const SOURCE_ROOTS = [
'api',
'client/src',
'packages/api/src',
'packages/data-provider/src',
'packages/data-schemas/src',
'packages/client/src',
'packages/chat/src',
];
const SOURCE_DIRS = SOURCE_ROOTS.map((rel) => resolve(ROOT, rel));
const EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mts', '.cts', '.mjs', '.cjs'];
const SKIP_DIR_NAMES = new Set([
'node_modules',
'dist',
'types',
'coverage',
'.turbo',
'data',
'demo',
]);
const args = process.argv.slice(2);
const CHECK = args.includes('--check');
const FILE_ARGS = args.filter((arg) => !arg.startsWith('--'));
const LOCAL_PREFIXES = ['~/', 'src/', 'test/', './', '../'];
/** Per-file opt-out for modules where import order is load-bearing. */
const IGNORE_MARKER = /^\s*\/\/\s*sort-imports-ignore\b/;
function isLocal(spec: string): boolean {
return LOCAL_PREFIXES.some((prefix) => spec.startsWith(prefix));
}
function hasSourceExtension(path: string): boolean {
return EXTENSIONS.some((ext) => path.endsWith(ext));
}
function isUnderSourceDir(abs: string): boolean {
return SOURCE_DIRS.some((dir) => abs === dir || abs.startsWith(`${dir}${sep}`));
}
interface Stmt {
raw: string;
spec: string;
isType: boolean;
isLocal: boolean;
len: number;
}
function extractSpec(raw: string): string | null {
return raw.match(/from\s+['"]([^'"]+)['"]/)?.[1] ?? null;
}
/** Applies the AGENTS.md grouping/length ordering to a run of pure imports. */
function sortSegment(stmts: Stmt[]): string[] {
const g1 = stmts
.filter((s) => !s.isType && !s.isLocal)
.sort((a, b) => {
const aReact = a.spec === 'react' ? 0 : 1;
const bReact = b.spec === 'react' ? 0 : 1;
if (aReact !== bReact) return aReact - bReact;
return a.len - b.len;
});
const g2 = stmts
.filter((s) => s.isType && !s.isLocal)
.sort((a, b) => b.len - a.len);
const g3 = stmts
.filter((s) => s.isType && s.isLocal)
.sort((a, b) => b.len - a.len);
const g4 = stmts
.filter((s) => !s.isType && s.isLocal)
.sort((a, b) => b.len - a.len);
return [...g1, ...g2, ...g3, ...g4].map((s) => s.raw);
}
function sortFileImports(content: string): string | null {
const lines = content.split('\n');
if (lines.some((line) => IGNORE_MARKER.test(line))) {
return null;
}
let i = 0;
while (i < lines.length) {
const t = lines[i].trimStart();
if (
t === '' ||
t.startsWith('//') ||
t.startsWith('/*') ||
t.startsWith('*') ||
t.startsWith('*/') ||
t.startsWith('\'use ') ||
t.startsWith('"use ')
) {
i++;
} else {
break;
}
}
const importStart = i;
// Side-effect imports (no `from` clause) are treated as immovable barriers:
// sorting is confined to each contiguous run of pure imports between them, so
// module-evaluation order around anything with side effects (polyfills,
// registration, css, etc.) is never changed.
const emitted: string[] = [];
const originalRaws: string[] = [];
let segment: Stmt[] = [];
let importEnd = i;
const flushSegment = (): void => {
if (segment.length === 0) return;
emitted.push(...sortSegment(segment));
segment = [];
};
while (i < lines.length) {
const t = lines[i].trimStart();
if (!t.startsWith('import ') && !t.startsWith('import{')) break;
let raw = lines[i];
let j = i;
while (!raw.includes(';') && j + 1 < lines.length) {
j++;
raw += '\n' + lines[j];
}
i = j + 1;
importEnd = i;
originalRaws.push(raw);
const spec = extractSpec(raw);
if (spec == null || spec === '') {
flushSegment();
emitted.push(raw);
while (i < lines.length && lines[i].trim() === '') i++;
continue;
}
segment.push({
raw,
spec,
isType: /^import\s+type[\s{]/.test(raw.trimStart()),
isLocal: isLocal(spec),
len: raw
.split('\n')
.map((l) => l.trim())
.join(' ').length,
});
while (i < lines.length && lines[i].trim() === '') i++;
}
flushSegment();
if (originalRaws.length < 2) return null;
if (originalRaws.join('\n') === emitted.join('\n')) return null;
return [
...lines.slice(0, importStart),
...emitted,
...lines.slice(importEnd),
].join('\n');
}
/** Recursively yields absolute paths of every source file under `dir`. */
async function* walkSourceFiles(dir: string): AsyncGenerator<string> {
const entries = await readdir(dir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
if (SKIP_DIR_NAMES.has(entry.name)) continue;
yield* walkSourceFiles(join(dir, entry.name));
} else if (entry.isFile() && hasSourceExtension(entry.name)) {
yield join(dir, entry.name);
}
}
}
/**
* Resolves the set of files to process. When explicit paths are passed
* (e.g. by lint-staged) only those source files under a known root are sorted;
* otherwise every source file under each root is scanned.
*/
async function collectFiles(): Promise<string[]> {
if (FILE_ARGS.length > 0) {
return FILE_ARGS.map((file) => resolve(file)).filter(
(abs) => hasSourceExtension(abs) && isUnderSourceDir(abs),
);
}
const files: string[] = [];
for (const dir of SOURCE_DIRS) {
try {
for await (const abs of walkSourceFiles(dir)) {
files.push(abs);
}
} catch {
continue;
}
}
return files;
}
let changed = 0;
let total = 0;
for (const filePath of await collectFiles()) {
const rel = relative(ROOT, filePath);
const content = await readFile(filePath, 'utf8');
const result = sortFileImports(content);
total++;
if (result === null) continue;
changed++;
if (CHECK) {
console.log(` ✗ ${rel}`);
} else {
await writeFile(filePath, result);
console.log(` ✓ ${rel}`);
}
}
if (CHECK && changed) {
console.log(`\n${changed}/${total} files need sorting. Run: npm run sort-imports`);
process.exit(1);
} else if (changed) {
console.log(`\nSorted ${changed}/${total} files.`);
} else {
console.log(`All ${total} files already sorted.`);
}