# Source Code Structure - TypeScript Implementation

TypeScript-specific implementation of the principles defined in [SOURCE_STRUCTURE.md](../core/SOURCE_STRUCTURE.md).

## Vertical Flow

- **File Declaration Order:** Within a TypeScript file, follow a consistent order: (1) imports, (2) type definitions and interfaces, (3) constants, (4) the primary exported class or function, (5) helper functions (private, in order of first use). The primary export should be the focal point -- readers find it early and drill into helpers as needed.
- **Proximity of Related Code:** Declare variables close to where they are used. Define helper functions near the code that calls them. Keep related type definitions in the same file as the functions that use them unless they are shared across modules.
- **Top-Down Readability:** Arrange exported functions so the high-level orchestration reads first and the details follow. A reader scanning from top to bottom should understand the module's purpose from the first exported function, then dive into helpers for details.
- **Dependency Order in Imports:** Order imports by distance: (1) Node.js built-ins (`node:path`, `node:crypto`), (2) framework imports, (3) third-party packages, (4) internal absolute imports, (5) relative imports. Separate each group with a blank line.

## Formatting

- **Consistent Formatter:** Use Prettier or Biome with a checked-in configuration. Run formatting in CI. Never manually format code where the formatter would produce different output. Let the tool own all whitespace decisions.
- **Line Length:** Configure the formatter for a consistent line length (80 or 100 characters). Avoid horizontal scrolling. The formatter handles line wrapping -- do not fight it.
- **Trailing Commas:** Always use trailing commas in multi-line parameter lists, object literals, arrays, and type definitions. This produces cleaner diffs and makes reordering lines trivial. Configure `"trailingComma": "all"` in Prettier.
- **Explicit Semicolons:** Use consistent semicolon style (either always or never) as configured by the formatter. Do not mix styles within a project.
- **Blank Lines for Grouping:** Use a single blank line to separate logical groups: imports from types, types from functions, one function from the next. Do not use multiple blank lines -- they waste vertical space without adding clarity.
- **Consistent Brace Style:** Use the same brace style throughout the project (typically K&R / 1TBS for TypeScript). Let the formatter enforce this.

## Project Structure

- **Feature-Based Organization:**
  ```
  src/
    features/
      auth/
        auth.controller.ts
        auth.service.ts
        auth.repository.ts
        auth.types.ts
        auth.schema.ts       (Zod schemas)
        auth.test.ts
        index.ts              (barrel export)
      orders/
        ...
    core/
      config/                 (typed configuration, env validation)
      errors/                 (error classes, error handler)
      middleware/             (auth, validation, logging, rate-limiting)
      types/                 (shared types, utility types)
      utils/                 (shared pure utility functions)
    infrastructure/
      database/              (connection, migrations, client)
      cache/                 (Redis client, caching utilities)
      http/                  (external API clients)
    main.ts                  (entry point, composition root)
  ```
- **One Concept Per File:** Each file should export one primary concept: one class, one group of related functions, one type family, or one configuration object. Name the file to match its primary export in `kebab-case`: `order-service.ts` exports `OrderService`, `auth-middleware.ts` exports `authMiddleware`.
- **Barrel Files (index.ts):** Use barrel files at feature boundaries to define the module's public API. Export only what consumers need. Keep barrel files thin -- just re-exports, no logic:
  ```typescript
  // features/auth/index.ts
  export { AuthService } from './auth.service';
  export type { AuthenticatedUser, AuthToken } from './auth.types';
  ```
  Do not create barrel files for every subdirectory -- they create circular dependency traps and slow down the TypeScript compiler.
- **Test Co-Location:** Place test files next to the source files they test: `auth.service.ts` and `auth.service.test.ts` in the same directory. For integration tests that span features, use a top-level `tests/` directory. Name test files with `.test.ts` or `.spec.ts` suffix consistently.
- **Configuration Files at Root:** Keep `tsconfig.json`, `package.json`, `.eslintrc`, `.prettierrc`, and `vitest.config.ts` at the project root. Use `tsconfig.json` path aliases (`@/features/*`, `@/core/*`) to enable clean imports without deep relative paths.
- **Type Definition Organization:** Shared types used across features live in `core/types/`. Feature-specific types live in the feature directory (`features/auth/auth.types.ts`). Generated types (API schemas, database types) live in a dedicated `generated/` directory and are gitignored or committed depending on the generation strategy.
- **File Length Guideline:** Keep files under 300 lines. If a file grows beyond this, it likely contains multiple responsibilities. Split by extracting helper functions, types, or sub-components into separate files. Long files defeat code review and IDE navigation.
