Skip to content
Open

V2 #17

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
92 commits
Select commit Hold shift + click to select a range
c75e1a8
feat: add comprehensive rules for architecture, controllers, services…
muneebhashone Oct 5, 2025
6f3438c
chore: remove VSCode extensions configuration and clean up settings
muneebhashone Oct 6, 2025
a35cb54
chore: update configuration files and enhance middleware structure
muneebhashone Oct 9, 2025
da7dae3
chore: remove unused dependencies and session store reference from co…
muneebhashone Oct 9, 2025
c27c0b5
feat: implement server-managed session lifecycle with MongoDB and Red…
muneebhashone Oct 9, 2025
a7be4c6
fix: resolve session token hash mismatch by updating hash after final…
muneebhashone Oct 9, 2025
3b70783
feat: implement session cleanup functionality with scheduled tasks an…
muneebhashone Oct 9, 2025
507bdd0
refactor: enhance session management logging and code readability
muneebhashone Oct 9, 2025
2adef36
chore: add AGENTS.md for repository guidelines and project structure …
muneebhashone Oct 9, 2025
ead344a
refactor: standardize formatting in ResetPassword email template for …
muneebhashone Oct 9, 2025
becdbc9
chore: update OpenAPI generation script to use dotenv for environment…
muneebhashone Oct 9, 2025
f45c3c4
chore: remove session management plugin plan document as it is no lon…
muneebhashone Oct 9, 2025
91a3e8e
chore: standardize quote style in ESLint configuration for consistency
muneebhashone Oct 9, 2025
35a23e7
chore: update new module creation guide to include tbk CLI usage and …
muneebhashone Oct 9, 2025
6e29d34
feat: implement seeding system with CLI commands for database management
muneebhashone Oct 9, 2025
3a3582c
feat: add CLI commands for module and seeder generation with detailed…
muneebhashone Oct 11, 2025
e13c2bb
feat: enhance module and seeder CLI documentation with detailed steps…
muneebhashone Oct 11, 2025
6d0b02d
chore: update configuration references in documentation to reflect ch…
muneebhashone Oct 11, 2025
7079731
refactor: optimize file writing in tbk CLI and update import paths fo…
muneebhashone Oct 11, 2025
d3f5b93
refactor: standardize quote style in can-access middleware for consis…
muneebhashone Oct 11, 2025
b5adf32
refactor: clean up error handling, db call and type definitions in ca…
muneebhashone Oct 11, 2025
4fb853a
feat: implement admin dashboard with CRUD functionality and resource …
muneebhashone Oct 11, 2025
63332f9
feat: add modal functionality for record creation and editing in admi…
muneebhashone Oct 11, 2025
1fd42f8
feat: implement file upload functionality in admin dashboard with sup…
muneebhashone Oct 11, 2025
125e197
refactor: improve code readability and consistency in admin dashboard…
muneebhashone Oct 11, 2025
87c5986
feat: implement profile picture upload functionality with new upload …
muneebhashone Oct 13, 2025
752c6e2
refactor: reorganize healthcheck functionality into modules and updat…
muneebhashone Oct 13, 2025
8f70dc4
refactor: migrate logger service to observability module and update i…
muneebhashone Oct 13, 2025
c00bb10
refactor: replace socket.io setup with a new realtime plugin and upda…
muneebhashone Oct 13, 2025
3fab6f8
feat: add realtime testing interface with connection management and l…
muneebhashone Oct 13, 2025
6f7bef9
feat: add relation lookup endpoint and enhance admin dashboard with r…
muneebhashone Oct 13, 2025
a837d1a
feat: enhance admin dashboard with subdocument handling and editor fu…
muneebhashone Oct 13, 2025
cd8d566
fix: correct subdocument handling logic in schema introspection utility
muneebhashone Oct 13, 2025
5c0adec
refactor: simplify ResponseExtended interface by removing unused loca…
muneebhashone Oct 13, 2025
8c2f4dc
chore: remove outdated documentation files for email service, seeders…
muneebhashone Oct 13, 2025
ce503df
feat: implement new response validation system and update controllers…
muneebhashone Oct 13, 2025
1f2fb9e
chore: update API documentation paths and enhance frontend styles for…
muneebhashone Oct 13, 2025
bc01fef
chore: add OpenAPI generation script and update .gitignore to include…
muneebhashone Oct 13, 2025
30f4fa0
feat: add socket testing suite URL to server bootstrap logs
muneebhashone Oct 13, 2025
b0b8f84
chore: update admin queue references to remove '/admin/' prefix in do…
muneebhashone Oct 13, 2025
1544eb8
chore: refine project structure documentation for clarity and add tes…
muneebhashone Oct 13, 2025
af1efbe
feat: implement room management features in realtime app, including j…
muneebhashone Oct 13, 2025
e1c9c9f
feat: add collapsible panel for custom emit functionality in realtime…
muneebhashone Oct 13, 2025
0c1a461
refactor: improve code readability by formatting and organizing JavaS…
muneebhashone Oct 13, 2025
ecb2ef3
chore: update OpenAPI generation paths to ensure correct output locat…
muneebhashone Oct 13, 2025
34ae3fd
chore: update OpenAPI documentation file path to save in public direc…
muneebhashone Oct 13, 2025
8865449
feat: implement recent items feature in admin lookup, displaying rece…
muneebhashone Oct 13, 2025
2c3c4fe
feat: implement bulk delete and clear all functionality in admin inte…
muneebhashone Oct 13, 2025
fd6dd18
feat: add filtering options for event logs in realtime app, including…
muneebhashone Oct 13, 2025
0aab82c
feat: add admin authentication and login page
muneebhashone Oct 18, 2025
6250b9d
refactor: improve S3 upload implementation with streaming and better …
muneebhashone Oct 18, 2025
fcf773c
feat: add comprehensive HTTP status codes and improve OpenAPI respons…
muneebhashone Oct 18, 2025
35ccddc
refactor: standardize OpenAPI response schemas across auth, blog, and…
muneebhashone Oct 18, 2025
4b49ec5
refactor: reorganize utilities into focused modules and move error ha…
muneebhashone Oct 18, 2025
f405cd0
refactor: extract admin login JS to separate file and update producti…
muneebhashone Oct 18, 2025
522e392
feat: add Google OAuth redirect URI utility function
muneebhashone Oct 18, 2025
517037f
fix: google sign in support with zod schema and url builder
muneebhashone Oct 18, 2025
97de915
chore: update gitignore and PM2 ecosystem configuration
muneebhashone Oct 18, 2025
a1a7768
chore: add favicon
muneebhashone Oct 18, 2025
672f606
fix: script path in ecosystem.config.js
muneebhashone Oct 18, 2025
70db0ae
feat: add intelligent port resolver with conflict detection and fallback
muneebhashone Oct 18, 2025
abca1b3
refactor: remove unused validation function and clean up S3 upload logic
muneebhashone Oct 18, 2025
ad59cc8
refactor: enhance src/lib structure
muneebhashone Oct 18, 2025
6b212f0
refactor: update email provider integration and improve file storage …
muneebhashone Oct 18, 2025
f2a4e51
feat: implement multi-provider storage configuration with AWS S3, Clo…
muneebhashone Oct 18, 2025
e45359d
feat: enhance admin file upload handling with local storage provider …
muneebhashone Oct 18, 2025
0f5e5e2
feat: implement cache provider abstraction with Redis and in-memory s…
muneebhashone Oct 18, 2025
08dbcfc
refactor: reorganize observability plugin structure and enhance healt…
muneebhashone Oct 19, 2025
dd31a54
refactor: update routing and status code references to use new MagicR…
muneebhashone Oct 19, 2025
347c880
refactor: update ESLint configuration and enhance plugin import paths…
muneebhashone Oct 19, 2025
746fa40
refactor: reorganize import paths and add port resolver utility for e…
muneebhashone Oct 19, 2025
86d6103
refactor: improve logging structure in createApp by using child logge…
muneebhashone Oct 19, 2025
3ff551c
fix: enable authentication guard for admin dashboard in app initializ…
muneebhashone Oct 19, 2025
a83ec66
refactor: update module registration paths and improve user schema st…
muneebhashone Oct 19, 2025
183947e
refactor: enhance port availability check by using direct socket conn…
muneebhashone Oct 20, 2025
7009e81
refactor: update seeder registration paths and enhance error handling…
muneebhashone Oct 20, 2025
b37f6b7
chore: add robots.txt to disallow all web crawlers
muneebhashone Oct 20, 2025
3002294
feat: add Resend email provider and update email configuration option…
muneebhashone Oct 20, 2025
cb6868c
refactor: reorganize static asset paths and enhance HTML file referen…
muneebhashone Oct 20, 2025
dc69152
feat: implement queue authentication with login page and session mana…
muneebhashone Oct 20, 2025
9d24a84
feat: add custom CSS and JS injection for BullBoard with logout funct…
muneebhashone Oct 20, 2025
450bfaf
style: update BullBoard layout and theme with improved CSS overrides …
muneebhashone Oct 20, 2025
febd481
feat: add logo asset and enhance BullBoard theme with improved CSS st…
muneebhashone Oct 21, 2025
2d06fab
feat: implement TypeScript Backend Toolkit CLI with commands for gene…
muneebhashone Oct 21, 2025
037194a
feat: enhance CLI with options for seeder and factory generation, and…
muneebhashone Oct 21, 2025
604cf16
refactor: remove basicParserPlugin and streamline middleware usage in…
muneebhashone Oct 21, 2025
da70b6e
chore: update .gitignore to include cursor AI rules
muneebhashone Oct 26, 2025
cff4602
Merge branch 'main' into v2-bullboard
muneebhashone Oct 26, 2025
6e83685
fix: update module registration path in documentation and correct Typ…
muneebhashone Oct 26, 2025
4bb323a
Merge branch 'v2-bullboard' of github.com:muneebhashone/typescript-ba…
muneebhashone Oct 26, 2025
e3eee0e
feat: add basicparserPlugin for enhanced request parsing and middlewa…
muneebhashone Oct 27, 2025
9c94d0e
refactor: rename basicparserPlugin to basicParserPlugin for consisten…
muneebhashone Oct 27, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
180 changes: 180 additions & 0 deletions .cursor/commands/create-module.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
# Create a new module (tbk CLI)

## Overview

Scaffold a fully-typed module with controller, service, router, schema, and model files, then wire it into the application routing system.

## Inputs

- **moduleName**: module folder/name in `src/modules/` (e.g., `product`)
- **apiPath**: optional API root path; defaults to `/api` (e.g., `/api/v1`)

## Steps

1. **Generate module files**

```bash
pnpm tbk generate:module <moduleName> --path <apiPath>
```

Examples:

```bash
pnpm tbk generate:module product --path /api
pnpm tbk generate:module product --path /api/v1
```

This creates:

- `src/modules/<moduleName>/<moduleName>.dto.ts`
- `src/modules/<moduleName>/<moduleName>.model.ts`
- `src/modules/<moduleName>/<moduleName>.schema.ts`
- `src/modules/<moduleName>/<moduleName>.services.ts`
- `src/modules/<moduleName>/<moduleName>.controller.ts`
- `src/modules/<moduleName>/<moduleName>.router.ts` (exports `<MODULE>_ROUTER_ROOT` and default router)

2. **Register router in routes**
Add an import and `router.use(...)` in `src/routes/routes.ts`:

```ts
// add with other imports
import <moduleName>Router, { <MODULE_NAME>_ROUTER_ROOT } from '../modules/<moduleName>/<moduleName>.router';

// add with other router.use calls
router.use(<MODULE_NAME>_ROUTER_ROOT, <moduleName>Router);
```

- Replace `<moduleName>` with your actual module name (e.g., `product`)
- Replace `<MODULE_NAME>` with the uppercased module name (e.g., `PRODUCT`)

Example for `product`:

```ts
import productRouter, {
PRODUCT_ROUTER_ROOT,
} from '../modules/product/product.router';
router.use(PRODUCT_ROUTER_ROOT, productRouter);
```

3. **Rebuild OpenAPI documentation**

```bash
pnpm openapi
```

Auto-generates Swagger from MagicRouter + Zod schemas.

4. **Typecheck and lint**

```bash
pnpm typecheck && pnpm lint
```

5. **Register with admin dashboard** (if needed)

Add your module to `src/plugins/admin/registry.ts`:

```ts
import <ModuleName>Model from '../modules/<moduleName>/<moduleName>.model';

export const adminResources: AdminResource[] = [
// ... existing resources
{
name: '<moduleName>s',
label: '<ModuleName>s',
model: <ModuleName>Model,
readOnlyFields: ['_id', 'createdAt', 'updatedAt']
},
];
```

- Replace `<moduleName>` with your module name (e.g., `product`)
- Replace `<ModuleName>` with PascalCase version (e.g., `Product`)
- Adjust `readOnlyFields` as needed for your module

6. **Optional: Create seeder and factory**
```bash
pnpm tbk make:factory <moduleName>/<Name>
pnpm tbk make:seeder <moduleName>/<Name>
```

## Module Checklist

- [ ] Module files generated successfully
- [ ] Router registered in `src/routes/routes.ts`
- [ ] Module registered in admin dashboard (`src/plugins/admin/registry.ts`) (if needed)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

There's an inconsistency in the path for the admin registry file. This line mentions src/plugins/admin/registry.ts, but step 5 (line 75) refers to src/admin/registry.ts. Please ensure the documentation is consistent to avoid confusion.

- [ ] OpenAPI documentation rebuilt
- [ ] Code passes typecheck and lint
- [ ] Environment variables added to `src/config/env.ts` and `.env.sample` (if needed)
- [ ] Committed with Conventional Commits format

## Response Validation

Generated modules automatically use the **response validation system**:

- **Response schemas** defined in schema files using `R.success()`, `R.paginated()`, `R.error()` helpers
- **Response types** exported from schema files for type-safe controllers
- **Typed response helpers** (`res.ok()`, `res.created()`, `res.noContent()`) in controllers
- **OpenAPI documentation** includes accurate per-status response schemas
- **Runtime validation** ensures responses match schemas (configurable via `RESPONSE_VALIDATION` env var)

### Example from generated code:

**Schema file (module.schema.ts):**

```typescript
import { R } from '../../openapi/response.builders';
import { itemOutSchema } from './item.dto';

// Response schemas
export const getItemsResponseSchema = R.paginated(itemOutSchema);
export const createItemResponseSchema = R.success(itemOutSchema);

// Response types
export type GetItemsResponseSchema = z.infer<typeof getItemsResponseSchema>;
export type CreateItemResponseSchema = z.infer<typeof createItemResponseSchema>;
```

**Router (module.router.ts):**

```typescript
import { getItemsResponseSchema } from './module.schema';

router.get(
'/',
{
requestType: { query: getItemsSchema },
responses: {
200: getItemsResponseSchema,
},
},
canAccess(),
handleGetItems,
);
```

**Controller (module.controller.ts):**

```typescript
import type { ResponseExtended } from '../../types';
import type { GetItemsResponseSchema } from './module.schema';

export const handleGetItems = async (
req: Request<unknown, unknown, unknown, GetItemsSchemaType>,
res: ResponseExtended<GetItemsResponseSchema>,
) => {
const { results, paginatorInfo } = await getItems(req.query);
return res.ok?.({
success: true,
data: { items: results, paginator: paginatorInfo },
});
};
```

## Notes

- Routes must use `MagicRouter`; the generator already sets this up and defines `<MODULE>_ROUTER_ROOT` using the `--path` you pass
- Generated code uses **new response validation pattern** - see `docs/RESPONSE_VALIDATION.md` for details
- Legacy `successResponse()` still works but new pattern is recommended
- Keep environment configs valid, and update `src/config/env.ts` and `.env.sample` if you introduce new variables
- Commit with Conventional Commits (e.g., `feat(<moduleName>): add <feature>`)
131 changes: 131 additions & 0 deletions .cursor/commands/create-seeder.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
# Create a module-tied seeder + factory (tbk CLI)

## Overview

Scaffold a seeder and its factory for a module, register it in the database seeder, and populate your database with test data.

## Inputs

- **module**: existing module folder in `src/modules/` (e.g., `user`)
- **name**: base name used for both factory and seeder (CLI appends `Seeder`)

## Steps

1. **Generate factory and seeder files**

```bash
# 1) Factory (used inside the seeder)
pnpm tbk make:factory <module>/<Name>

# 2) Seeder (will import and use the factory)
pnpm tbk make:seeder <module>/<Name>
```

Examples:

```bash
pnpm tbk make:factory payment/Payment && pnpm tbk make:seeder payment/Payment
pnpm tbk make:factory user/User && pnpm tbk make:seeder user/User
```

This creates:

- `src/modules/<module>/factories/<name>.factory.ts` (lowercased file; exports `<camelName>Factory`)
- `src/modules/<module>/seeders/<Name>Seeder.ts`

2. **Implement seeder logic**
Edit `src/modules/<module>/seeders/<Name>Seeder.ts` to import the factory and insert documents via the module model:

```ts
import <Model> from '../<module>.model';
import { <camelName>Factory } from '../factories/<name>.factory';

export const <Name>Seeder = {
name: '<Name>Seeder',
groups: ['dev'],
// collections help --fresh drop only the affected collections
collections: ['<collection_name>'],
async run(ctx) {
ctx.logger.info('Running <Name>Seeder');

const docs = Array.from({ length: 10 }, (_, i) =>
<camelName>Factory.build(i + 1),
);

if (!ctx.env.dryRun) {
await <Model>.insertMany(docs);
}

// share references across seeders if needed
ctx.refs.set('<module>:seeded', docs.map((d) => d._id));
},
};
```

- Replace `<Model>` with your module's mongoose model (e.g., `Payment`)
- Replace `<camelName>`/`<name>` with the factory export/file (e.g., `paymentFactory`/`payment`)
- Replace `<collection_name>` with the underlying collection name

3. **Register seeder**
Add your seeder to `src/seeders/registry.ts`:

```ts
import { <Name>Seeder } from '../modules/<module>/seeders/<Name>Seeder';

export const seeders = [
// existing seeders...
<Name>Seeder,
];
```

4. **Run seeders**

```bash
# default: group=dev, transactions enabled
pnpm tbk seed

# choose specific group
pnpm tbk seed --group dev
pnpm tbk seed --group test
pnpm tbk seed --group demo

# run specific seeders only (comma-separated names)
pnpm tbk seed --only <Name>Seeder,OtherSeeder

# drop involved collections before seeding
pnpm tbk seed --fresh

# dry run (log only, no writes)
pnpm tbk seed --dry-run

# set random seed value
pnpm tbk seed --seed 42

# disable transactions globally
pnpm tbk seed --no-transaction

# allow in production (blocked unless forced)
pnpm tbk seed --force
```

## Seeder Checklist

- [ ] Factory file generated in `src/modules/<module>/factories/`
- [ ] Seeder file generated in `src/modules/<module>/seeders/`
- [ ] Factory implements `build(i, overrides)` method
- [ ] Seeder registered in `src/seeders/registry.ts`
- [ ] Collections specified in seeder config
- [ ] MongoDB service running (`docker compose up -d`)
- [ ] Seeder tested with `--dry-run` flag

## Advanced Options

- **Order dependencies**: Use `dependsOn` to order seeders (names must match other seeders' `name`)
- **Share data**: Use `ctx.refs.set()` and `ctx.refs.get()` to pass data between seeders
- **Group targeting**: Assign seeders to groups (`dev`, `test`, `demo`) for different environments

## Notes

- Factories live in `src/modules/<module>/factories/` and export `<camelName>Factory` with a `build(i, overrides)` helper
- Ensure MongoDB is reachable before seeding (`docker compose up -d`)
- Use transactions by default for data consistency; disable with `--no-transaction` if needed
79 changes: 79 additions & 0 deletions .cursor/rules/architecture.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
---
alwaysApply: true
description: Core architecture and patterns for the TypeScript backend toolkit
---

# Architecture Overview

This is a TypeScript Express.js backend toolkit with a modular, type-safe architecture.

## Core Patterns

### MagicRouter System

- All routes MUST use MagicRouter from [router.ts](mdc:src/plugins/magic/router.ts)
- MagicRouter automatically generates OpenAPI/Swagger documentation from Zod schemas
- Never use plain Express `app.get()` or `router.get()` - always use MagicRouter

### Module Structure

Modules live in [src/modules/](mdc:src/modules/) and follow this structure:

```
module-name/
├── module.controller.ts # Business logic handlers
├── module.router.ts # MagicRouter route definitions
├── module.service.ts # Database and external service interactions
├── module.schema.ts # Zod schemas for validation
├── module.model.ts # Mongoose models
└── module.dto.ts # TypeScript types/interfaces
```

### Validation & Type Safety

- ALWAYS use Zod schemas for request/response validation
- Runtime validation via [validate-zod-schema.ts](mdc:src/middlewares/validate-zod-schema.ts)
- Extend Zod with OpenAPI metadata using `.openapi()` method from [zod-extend.ts](mdc:src/plugins/magic/zod-extend.ts)
- Use TypeScript strict mode - no `any` types

### Configuration

- All config in [env.ts](mdc:src/config/env.ts)
- Environment variables validated with Zod
- Time values are in milliseconds (converted from strings like "1d" or "7d")

### Database

- MongoDB with Mongoose ODM
- Connection managed in [database.ts](mdc:src/lib/database.ts)
- Models defined per module (e.g., [user.model.ts](mdc:src/modules/user/user.model.ts))

### Background Jobs & Queues

- BullMQ with Redis for all background jobs
- Email queue in [email.queue.ts](mdc:src/queues/email.queue.ts)
- Admin dashboard at `/queues`

### Error Handling

- Global error handler in [error-handler.ts](mdc:src/middlewares/error-handler.ts)
- Throw errors with proper HTTP status codes
- Errors are automatically caught and formatted

## Technology Stack

- **Runtime**: Node.js with TypeScript
- **Framework**: Express.js
- **Validation**: Zod
- **Database**: MongoDB + Mongoose
- **Cache/Queue**: Redis + BullMQ
- **Auth**: JWT (with optional OTP)
- **Storage**: AWS S3
- **Email**: React Email + Mailgun
- **Real-time**: Socket.io
- **API Docs**: Swagger/OpenAPI (auto-generated)
- **Logger**: Pino

## Package Manager

ALWAYS use `pnpm` - never npm or yarn
Loading