import { existsSync, readdirSync, readFileSync } from 'node:fs' import path from 'node:path' import { describe, expect, it } from 'vitest' /** * Architecture rules, checked on every test run (template from the `dev` skill). * The folder structure is mandatory: * src/{shared, server/{modules//{domain, application/{usecases, dto}, infra/{db, drivers}}, kernel}, client} + drizzle/ * Subject first, layers inside: every server layer lives in a module (or in the kernel, which has the same layers). * Modules talk through ports: never import another module's domain or infra; another module's application only from infra. * Adjust only PATH_ALIASES and THROW_ALLOWED_FILES to the project; keep the rules. */ const ROOT = process.cwd() const SOURCE_ROOT = path.join(ROOT, 'src') const CLIENT = path.join(SOURCE_ROOT, 'client') const SHARED = path.join(SOURCE_ROOT, 'shared') const SERVER = path.join(SOURCE_ROOT, 'server') const MODULES = path.join(SERVER, 'modules') const KERNEL = path.join(SERVER, 'kernel') /** Files allowed at the root of src/server: the composition root, the app router and the entry point. */ const SERVER_ROOT_FILES = ['container.ts', 'container.test.ts', 'router.ts', 'router.test.ts', 'main.ts'] const UNIT_FOLDERS = ['domain', 'application', 'infra'] const SUB_LAYERS: Record = { application: ['usecases', 'dto'], infra: ['db', 'drivers'] } /** Layer names that must never appear below a layer (no `usecases//dto`, no `domain//ports`, no nested modules). */ const SERVER_LAYER_NAMES = new Set([ 'domain', 'application', 'infra', 'infrastructure', 'presentation', 'modules', 'features', 'kernel', 'usecases', 'use-cases', 'dto', 'dtos', 'db', 'drivers', 'ports', 'adapters', 'repositories', 'services', 'entities', ]) /** The client and shared code are not layered, but must not hide server-style layers either. */ const CLIENT_LAYER_NAMES = new Set(['domain', 'application', 'infra', 'infrastructure', 'presentation', 'modules', 'features', 'usecases', 'use-cases']) /** tsconfig path aliases: prefix -> absolute folder. */ const PATH_ALIASES: Record = { '@client/': CLIENT, '@shared/': SHARED, '@server/': SERVER, } /** * Errors are returned as Either, never thrown. The only file allowed to throw is the transport edge * that turns a Left into the framework's error (e.g. TRPCError); list it here. */ const THROW_ALLOWED_FILES = [path.join(KERNEL, 'infra', 'drivers', 'trpc', 'to-transport-error.ts')] const THROW_PATTERN = /(^|[^\w.])throw\s/ /** Database access goes through Drizzle: raw drivers only in an infra/db folder, other ORMs nowhere. */ const DATABASE_DRIVERS = ['pg', 'postgres', 'mysql2', 'better-sqlite3', '@neondatabase/serverless'] const FORBIDDEN_ORMS = ['@prisma/client', 'prisma', 'typeorm', 'knex', 'sequelize', 'mongoose', 'kysely'] const IGNORED_DIRS = new Set(['node_modules', 'dist', 'build', 'coverage', '.git']) const IMPORT_PATTERN = /^\s*(import|export)\s+(type\s+)?[^'"]*?from\s+['"]([^'"]+)['"]/gm const KEBAB_CASE = /^[a-z0-9]+(?:-[a-z0-9]+)*(?:\.[a-z0-9]+(?:-[a-z0-9]+)*)*$/ const MEMBER_LINE = /^ (?![\s/*})\].])(?:(?:public|private|protected|readonly|static|async|get|set|override|abstract|declare)\s+)*(?:constructor\b|\*?[#\w$]+\s*[(<:=?!;])/ interface ImportRef { file: string target: string packageName: string | null typeOnly: boolean } function walk(dir: string, accept: (name: string) => boolean): string[] { if (!existsSync(dir)) return [] return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { if (IGNORED_DIRS.has(entry.name)) return [] const full = path.join(dir, entry.name) if (entry.isDirectory()) return walk(full, accept) return accept(entry.name) ? [full] : [] }) } const isSource = (name: string) => /\.tsx?$/.test(name) && !/\.test\.tsx?$/.test(name) const sourceFiles = (dir: string) => walk(dir, isSource) const isInside = (file: string, dir: string) => file === dir || file.startsWith(dir + path.sep) const rel = (file: string) => path.relative(ROOT, file) function packageNameOf(specifier: string): string { const parts = specifier.split('/') return specifier.startsWith('@') ? parts.slice(0, 2).join('/') : (parts[0] ?? specifier) } function resolveTarget(file: string, specifier: string): { target: string; packageName: string | null } { const alias = Object.keys(PATH_ALIASES).find((prefix) => specifier.startsWith(prefix)) if (alias) return { target: path.join(PATH_ALIASES[alias] ?? '', specifier.slice(alias.length)), packageName: null } if (specifier.startsWith('.')) return { target: path.resolve(path.dirname(file), specifier), packageName: null } return { target: specifier, packageName: packageNameOf(specifier) } } function importsOf(file: string): ImportRef[] { const content = readFileSync(file, 'utf8') return [...content.matchAll(IMPORT_PATTERN)].map((match) => ({ file, ...resolveTarget(file, match[3] ?? ''), typeOnly: Boolean(match[2]), })) } const imports = [CLIENT, SHARED, SERVER].flatMap(sourceFiles).flatMap(importsOf) const importsFrom = (dir: string) => imports.filter((ref) => isInside(ref.file, dir)) const describeRef = (ref: ImportRef) => `${rel(ref.file)} -> ${ref.packageName ?? rel(ref.target)}` const isNodeBuiltin = (name: string | null) => name !== null && name.startsWith('node:') /** A unit is a module (src/server/modules/) or the kernel; both have the same layers. */ interface Unit { name: string dir: string } const folderNames = (dir: string) => existsSync(dir) ? readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !IGNORED_DIRS.has(entry.name)).map((entry) => entry.name) : [] const MODULE_UNITS: Unit[] = folderNames(MODULES).map((name) => ({ name, dir: path.join(MODULES, name) })) const KERNEL_UNIT: Unit = { name: 'kernel', dir: KERNEL } const UNITS = [...MODULE_UNITS, KERNEL_UNIT] const unitOf = (file: string) => UNITS.find((unit) => isInside(file, unit.dir)) ?? null const layer = (unit: Unit, ...parts: string[]) => path.join(unit.dir, ...parts) const isInLayer = (file: string, ...parts: string[]) => UNITS.some((unit) => isInside(file, layer(unit, ...parts))) /** Imports of files inside the given layer of each unit, with the unit they belong to. */ const importsFromLayer = (...parts: string[]) => UNITS.flatMap((unit) => importsFrom(layer(unit, ...parts)).map((ref) => ({ ref, unit }))) const isInsideAny = (target: string, dirs: string[]) => dirs.some((dir) => isInside(target, dir)) function staticOnlyClasses(content: string): Array<{ name: string; line: number }> { const lines = content.split('\n') const found: Array<{ name: string; line: number }> = [] for (let index = 0; index < lines.length; index++) { const header = /^(?:export )?(?:default )?(?:abstract )?class (\w+)[^{]*\{\s*$/.exec(lines[index] ?? '') if (!header) continue const members: string[] = [] let cursor = index + 1 for (; cursor < lines.length && !/^\}/.test(lines[cursor] ?? ''); cursor++) { if (MEMBER_LINE.test(lines[cursor] ?? '')) members.push(lines[cursor] ?? '') } if (members.length > 0 && members.every((member) => /\bstatic\b/.test(member))) found.push({ name: header[1] ?? '', line: index + 1 }) index = cursor } return found } describe('architecture', () => { it('keeps the domain pure (own domain, kernel domain and shared only, no packages)', () => { const violations = importsFromLayer('domain') .filter(({ ref, unit }) => ref.packageName !== null || !isInsideAny(ref.target, [layer(unit, 'domain'), layer(KERNEL_UNIT, 'domain'), SHARED])) .map(({ ref }) => describeRef(ref)) expect(violations).toEqual([]) }) it('keeps DTOs as plain shapes (dto, domain, kernel and shared only, never use cases)', () => { const violations = importsFromLayer('application', 'dto') .filter( ({ ref, unit }) => ref.packageName !== null || !isInsideAny(ref.target, [layer(unit, 'application', 'dto'), layer(unit, 'domain'), layer(KERNEL_UNIT, 'domain'), layer(KERNEL_UNIT, 'application', 'dto'), SHARED]), ) .map(({ ref }) => describeRef(ref)) expect(violations).toEqual([]) }) it('keeps application free of infrastructure and frameworks', () => { const violations = importsFromLayer('application') .filter( ({ ref, unit }) => ref.packageName !== null || !isInsideAny(ref.target, [layer(unit, 'domain'), layer(unit, 'application'), layer(KERNEL_UNIT, 'domain'), layer(KERNEL_UNIT, 'application'), SHARED]), ) .map(({ ref }) => describeRef(ref)) expect(violations).toEqual([]) }) it('lets modules talk only through ports (never another module domain or infra; its application only from infra)', () => { const violations = MODULE_UNITS.flatMap((unit) => importsFrom(unit.dir).filter((ref) => { const target = unitOf(ref.target) if (ref.packageName !== null || target === null || target === unit || target === KERNEL_UNIT) return false return !(isInside(ref.file, layer(unit, 'infra')) && isInside(ref.target, layer(target, 'application'))) }), ).map(describeRef) expect(violations).toEqual([]) }) it('keeps the kernel independent of the modules', () => { const violations = importsFrom(KERNEL).filter((ref) => isInside(ref.target, MODULES)).map(describeRef) expect(violations).toEqual([]) }) it('never imports the client from the server or shared code', () => { const violations = [...importsFrom(SERVER), ...importsFrom(SHARED)].filter((ref) => isInside(ref.target, CLIENT)).map(describeRef) expect(violations).toEqual([]) }) it('keeps shared code independent of the server', () => { const violations = importsFrom(SHARED).filter((ref) => isInside(ref.target, SERVER)).map(describeRef) expect(violations).toEqual([]) }) it('lets the client import server code only as types', () => { const violations = importsFrom(CLIENT) .filter((ref) => isInside(ref.target, SERVER) && !ref.typeOnly) .map(describeRef) expect(violations).toEqual([]) }) it('accesses the database only through Drizzle in infra/db', () => { const violations = imports .filter((ref) => !ref.typeOnly || ref.packageName?.startsWith('drizzle-orm') !== true) .filter((ref) => !isNodeBuiltin(ref.packageName)) .filter( (ref) => FORBIDDEN_ORMS.includes(ref.packageName ?? '') || (DATABASE_DRIVERS.includes(ref.packageName ?? '') && !isInLayer(ref.file, 'infra', 'db')) || (ref.packageName?.startsWith('drizzle-orm') === true && !isInLayer(ref.file, 'infra', 'db')), ) .map(describeRef) expect(violations).toEqual([]) }) it('follows the mandatory folder structure', () => { const entries = (dir: string) => (existsSync(dir) ? readdirSync(dir, { withFileTypes: true }).filter((entry) => !IGNORED_DIRS.has(entry.name) && entry.name !== '.DS_Store') : []) const files = (dir: string) => entries(dir).filter((entry) => entry.isFile()).map((entry) => entry.name) const only = (dir: string, allowed: readonly string[]) => folderNames(dir).filter((name) => !allowed.includes(name)).map((name) => `unexpected ${rel(path.join(dir, name))}`) const loose = (dir: string, allowed: readonly string[] = []) => files(dir).filter((name) => !allowed.includes(name)).map((name) => `loose file ${rel(path.join(dir, name))}`) const missing = [SHARED, SERVER, MODULES, CLIENT, path.join(ROOT, 'drizzle')].filter((dir) => !existsSync(dir)).map((dir) => `missing ${rel(dir)}`) const top = [...only(SOURCE_ROOT, ['shared', 'server', 'client']), ...only(SERVER, ['modules', 'kernel']), ...loose(SERVER, SERVER_ROOT_FILES), ...loose(MODULES)] const units = UNITS.filter((unit) => existsSync(unit.dir)).flatMap((unit) => [ ...only(unit.dir, UNIT_FOLDERS), ...loose(unit.dir), ...Object.entries(SUB_LAYERS).flatMap(([name, allowed]) => [...only(layer(unit, name), allowed), ...loose(layer(unit, name))]), ]) const layerRoots = UNITS.flatMap((unit) => [layer(unit, 'domain'), ...Object.entries(SUB_LAYERS).flatMap(([name, subs]) => subs.map((sub) => layer(unit, name, sub)))]) const nestedBelow = (roots: string[], names: Set) => roots.flatMap((root) => walk(root, () => true) .map((file) => path.relative(root, path.dirname(file))) .filter((dir) => dir !== '' && dir.split(path.sep).some((segment) => names.has(segment))) .map((dir) => path.join(root, dir)), ) const nested = [...new Set([...nestedBelow(layerRoots, SERVER_LAYER_NAMES), ...nestedBelow([CLIENT, SHARED], CLIENT_LAYER_NAMES)])] .sort() .map((dir) => `layer folder below a layer: ${rel(dir)}`) expect([...missing, ...top, ...units, ...nested]).toEqual([]) }) it('never throws on the server or in shared code (errors are returned as Either)', () => { const violations = [SERVER, SHARED] .flatMap(sourceFiles) .filter((file) => !THROW_ALLOWED_FILES.includes(file)) .flatMap((file) => readFileSync(file, 'utf8') .split('\n') .flatMap((line, index) => (THROW_PATTERN.test(line) && !/^\s*(\/\/|\*)/.test(line) ? [`${rel(file)}:${index + 1}`] : [])), ) expect(violations).toEqual([]) }) it('has no static-only classes on the server', () => { const violations = sourceFiles(SERVER).flatMap((file) => staticOnlyClasses(readFileSync(file, 'utf8')).map((found) => `${rel(file)}:${found.line} ${found.name}`), ) expect(violations).toEqual([]) }) it('names files and folders in kebab-case', () => { const paths = [CLIENT, SHARED, SERVER].flatMap((dir) => walk(dir, () => true)) const segments = new Set(paths.flatMap((file) => path.relative(SOURCE_ROOT, file).split(path.sep))) const violations = [...segments].filter((segment) => !KEBAB_CASE.test(segment)).sort() expect(violations).toEqual([]) }) })