nest-scramble 3.0.2 β†’ 3.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,1103 +1,482 @@
1
- # Nest-Scramble
2
-
3
- > Zero-config API Documentation & Postman Generator for NestJS using static analysis
4
-
5
- [![npm version](https://badge.fury.io/js/nest-scramble.svg)](https://badge.fury.io/js/nest-scramble)
6
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
- [![GitHub stars](https://img.shields.io/github/stars/Eng-MMustafa/nest-scramble.svg)](https://github.com/Eng-MMustafa/nest-scramble)
8
- [![Author](https://img.shields.io/badge/Author-Mohamed%20Mustafa-blue.svg)](https://github.com/Eng-MMustafa)
9
- [![NestJS Compatibility](https://img.shields.io/badge/NestJS-10%20%7C%2011-blue.svg)](https://docs.nestjs.com)
10
- [![Node Version](https://img.shields.io/badge/node-%3E%3D18.10.0-brightgreen.svg)](https://nodejs.org)
11
- [![TypeScript](https://img.shields.io/badge/typescript-%3E%3D5.0.0-blue.svg)](https://www.typescriptlang.org)
12
-
13
- ## πŸ“‹ What's New in v3.0.0
14
-
15
- ### πŸš€ Major Version Update - NestJS 10 & 11 Focus
16
- - **⚑ Breaking**: Dropped NestJS 9 support - now requires NestJS 10.x or 11.x
17
- - **⚑ Breaking**: Minimum Node.js version is now 18.10.0
18
- - **⚑ Breaking**: Minimum TypeScript version is now 5.0.0
19
- - **πŸ”§ Enhanced**: Optimized for modern NestJS metadata patterns
20
- - **πŸ”§ Improved**: Better TypeScript 5.x type inference and AST analysis
21
- - **🎯 Feature**: Full compatibility with NestJS 11's latest features
22
-
23
- **Dashboard URLs now respect your configuration:**
24
- ```typescript
25
- NestScrambleModule.forRoot({
26
- baseUrl: 'http://127.0.0.1:4444' // βœ… Now works perfectly!
27
- })
28
- ```
29
-
30
- ### πŸ“– Full Changelog
31
- Check out the [CHANGELOG.md](CHANGELOG.md) for complete version history.
32
-
33
- ---
34
-
35
- ## πŸš€ Why Nest-Scramble?
36
-
37
- As a NestJS developer, I was tired of drowning in `@ApiProperty` decorators just to get basic API documentation. I longed for a zero-config solution where docs just worked without polluting my code. **Nest-Scramble changes that** by using static TypeScript analysis to automatically generate:
38
-
39
- - βœ… **OpenAPI 3.0 specifications** from your DTOs
40
- - βœ… **Interactive Scalar UI documentation** with zero configuration
41
- - βœ… **Postman collections** with smart mock data
42
- - βœ… **Live mocking** for rapid prototyping
43
-
44
- **Zero configuration. Zero decorators. Just pure TypeScript.**
45
-
46
- ## πŸ“– The Story Behind Nest-Scramble
47
-
48
- It all started with a vision: API documentation should be effortless. As a developer passionate about clean code and developer experience, I knew there had to be a better way than manual decorators and runtime reflection.
49
-
50
- When I switched to NestJS for its powerful architecture and TypeScript-first approach, I was disappointed by the lack of zero-config documentation tools. Hours wasted on `@ApiProperty({ type: String })` instead of building features.
51
-
52
- I knew there had to be a better way. Leveraging my expertise in static analysis and Abstract Syntax Trees (AST), I built Nest-Scramble to bring that same developer experience to the Node.js ecosystem. It's not just a toolβ€”it's my mission to make API documentation as effortless as it should be.
53
-
54
- ## πŸ† Features Gallery
55
-
56
- | Feature | Nest-Scramble | Swagger (@nestjs/swagger) |
57
- |---------|---------------|---------------------------|
58
- | Analysis Method | Static AST Traversal | Runtime Reflection |
59
- | Performance Impact | Zero Overhead | Decorator Runtime Cost |
60
- | Type Accuracy | Full TypeScript Inference | Partial Mapping |
61
- | Circular References | Auto-Detected & Resolved | Manual Workarounds |
62
- | Bundle Size | Minimal | Heavy with Decorators |
63
- | Code Purity | Zero Decorators | Decorator Pollution |
64
- | Future Compatibility | TypeScript Evolution Ready | Framework Dependent |
65
-
66
- ## 🧠 The Vision
67
-
68
- Nest-Scramble embodies my engineering philosophy: **Clean Code through Automation**. As a developer who values TypeScript's type safety and NestJS's architecture, I believe that documentation should never compromise code quality.
69
-
70
- This library represents a paradigm shiftβ€”from manual, error-prone decorators to intelligent, compile-time analysis. It's about empowering developers to focus on building features, not fighting frameworks.
71
-
72
- ## πŸ”¬ How it's Built
73
-
74
- Nest-Scramble is engineered using cutting-edge static analysis techniques that traditional tools cannot match:
75
-
76
- - **Abstract Syntax Tree (AST) Traversal**: Direct manipulation of TypeScript's AST using `ts-morph` for unparalleled type inference
77
- - **Zero-Decorator Architecture**: Pure TypeScript classes remain untouched, preserving domain integrity
78
- - **Compile-Time Intelligence**: All analysis happens at build-time, eliminating runtime performance costs
79
- - **Circular Reference Mastery**: Advanced algorithms detect and handle complex type relationships automatically
80
-
81
- This approach delivers what runtime reflection simply cannot: perfect accuracy, zero overhead, and future-proof compatibility with TypeScript's evolving type system.
82
-
83
- ## ⚑ Quick Start - Zero Config (2 Steps!)
84
-
85
- ### Option A: Auto-Injection (Recommended - 30 seconds!)
86
-
87
- ```bash
88
- # 1. Install
89
- npm install nest-scramble
90
-
91
- # 2. Auto-inject into your project
92
- npx nest-scramble init
93
-
94
- # 3. Start your app
95
- npm run start:dev
96
-
97
- # πŸŽ‰ Done! Visit http://localhost:3000/docs
98
- ```
99
-
100
- The `init` command automatically:
101
- - βœ… Adds the import statement to your `app.module.ts`
102
- - βœ… Injects `NestScrambleModule.forRoot()` into your imports
103
- - βœ… Uses smart defaults with zero configuration needed
104
-
105
- ### Option B: Manual Installation (3 Steps)
106
-
107
- #### 1. Install the Package
108
-
109
- ```bash
110
- # Using npm
111
- npm install nest-scramble
112
-
113
- # Using yarn
114
- yarn add nest-scramble
115
-
116
- # Using pnpm
117
- pnpm add nest-scramble
118
- ```
119
-
120
- #### 2. Import Module in Your NestJS App
121
-
122
- **Zero-Config (Recommended):**
123
- ```typescript
124
- import { Module } from '@nestjs/common';
125
- import { NestScrambleModule } from 'nest-scramble';
126
-
127
- @Module({
128
- imports: [
129
- NestScrambleModule.forRoot(), // 🎯 That's it! Zero config needed
130
- ],
131
- })
132
- export class AppModule {}
133
- ```
134
-
135
- **With Custom Options:**
136
- ```typescript
137
- import { Module } from '@nestjs/common';
138
- import { NestScrambleModule } from 'nest-scramble';
139
-
140
- @Module({
141
- imports: [
142
- NestScrambleModule.forRoot({
143
- sourcePath: 'src', // Auto-detected by default
144
- baseUrl: 'http://localhost:3000', // Auto-detected from PORT env
145
- enableMock: true, // Enabled by default
146
- autoExportPostman: false, // Disabled by default
147
- apiTitle: 'My API', // Auto-detected from package.json
148
- apiVersion: '1.0.0', // Auto-detected from package.json
149
- }),
150
- ],
151
- })
152
- export class AppModule {}
153
- ```
154
-
155
- #### 3. Start Your App and Visit Documentation
156
-
157
- ```bash
158
- npm run start:dev
159
- ```
160
-
161
- You'll see a beautiful dashboard in your terminal:
162
-
163
- ```
164
- β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
165
- β”‚ πŸš€ Nest-Scramble by Mohamed Mustafa is Active! β”‚
166
- β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
167
- β”‚ πŸ“– Docs: http://localhost:3000/docs β”‚
168
- β”‚ πŸ“„ JSON: http://localhost:3000/docs-json β”‚
169
- β”‚ 🎭 Mock: http://localhost:3000/scramble-mock β”‚
170
- β”‚ ✨ Scanning: src β”‚
171
- β”‚ 🎯 Controllers: 5 β”‚
172
- β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
173
- ```
174
-
175
- Then open your browser:
176
-
177
- - **πŸ“– Interactive API Docs (Scalar UI)**: http://localhost:3000/docs
178
- - **πŸ“„ OpenAPI JSON Spec**: http://localhost:3000/docs-json
179
- - **🎭 Mock Endpoints**: http://localhost:3000/scramble-mock/*
180
-
181
- **That's it!** Nest-Scramble automatically:
182
- - πŸ” Detects your project structure
183
- - πŸ“‚ Finds your controllers
184
- - πŸ“ Generates OpenAPI spec
185
- - 🎨 Serves beautiful documentation
186
- - 🎭 Provides mock endpoints
187
-
188
- ## πŸ”§ Compatibility & Requirements
189
-
190
- ### Supported Versions
191
- - **NestJS**: `^10.0.0 || ^11.0.0` (v10.x and v11.x only)
192
- - **Node.js**: `>=18.10.0` (required for NestJS 11)
193
- - **TypeScript**: `>=5.0.0` (modern features and better type inference)
194
- - **reflect-metadata**: `>=0.1.13` (optional)
195
-
196
- ### Migration from v2.x
197
- If you're upgrading from nest-scramble v2.x with NestJS 9:
198
- 1. Upgrade NestJS to v10 or v11: `npm install @nestjs/common@^10.0.0 @nestjs/core@^10.0.0`
199
- 2. Upgrade Node.js to v18.10.0 or higher
200
- 3. Upgrade TypeScript to v5.0.0 or higher
201
- 4. Then upgrade nest-scramble: `npm install nest-scramble@^3.0.0`
202
-
203
- ### Package Managers
204
- ```bash
205
- # npm
206
- npm install nest-scramble
207
-
208
- # yarn
209
- yarn add nest-scramble
210
-
211
- # pnpm
212
- pnpm add nest-scramble
213
- ```
214
-
215
- ### Auto-Detection Features
216
- Nest-Scramble automatically detects:
217
- - βœ… Project structure and source directories
218
- - βœ… API title and version from `package.json`
219
- - βœ… Base URL from `PORT` and `HOST` environment variables
220
- - βœ… TypeScript configuration and controller locations
221
- - βœ… Dependencies and module relationships
222
-
223
- ## βš™οΈ Configuration Options
224
-
225
- ```typescript
226
- NestScrambleModule.forRoot({
227
- // Source directory to scan for controllers
228
- sourcePath: 'src', // default: 'src'
229
-
230
- // API base URL for OpenAPI spec and dashboard display
231
- baseUrl: 'http://localhost:3000', // default: auto-detected from PORT/HOST env
232
-
233
- // Documentation path (customizable)
234
- path: '/docs', // default: '/docs'
235
-
236
- // Enable live mocking middleware
237
- enableMock: true, // default: true
238
-
239
- // Auto-export Postman collection on startup
240
- autoExportPostman: false, // default: false
241
-
242
- // Postman collection output path
243
- postmanOutputPath: 'collection.json', // default: 'collection.json'
244
-
245
- // UI Theme options
246
- theme: 'futuristic', // 'classic' | 'futuristic' (default: 'futuristic')
247
- primaryColor: '#00f2ff', // default: '#00f2ff'
248
- customDomainIcon: '', // default: ''
249
-
250
- // API metadata (auto-detected from package.json)
251
- apiTitle: 'My API', // default: auto-detected
252
- apiVersion: '1.0.0', // default: auto-detected
253
-
254
- // πŸ†• Advanced Features
255
- useIncrementalScanning: false, // Enable caching for faster startups
256
- enableWatchMode: false, // Auto-regenerate on file changes
257
- cacheTtl: 24 * 60 * 60 * 1000, // Cache TTL in milliseconds (24 hours)
258
- })
259
- ```
260
-
261
- ### Configuration Details
262
-
263
- | Option | Type | Default | Description |
264
- |--------|------|---------|-------------|
265
- | `sourcePath` | `string` | `'src'` | Directory where your NestJS controllers are located |
266
- | `baseUrl` | `string` | `auto-detected` | Base URL for your API (used in OpenAPI spec and dashboard URLs) |
267
- | `path` | `string` | `'/docs'` | Documentation endpoint path |
268
- | `enableMock` | `boolean` | `true` | Enable `/scramble-mock/*` endpoints for testing |
269
- | `autoExportPostman` | `boolean` | `false` | Automatically generate Postman collection file |
270
- | `postmanOutputPath` | `string` | `'collection.json'` | Output path for Postman collection |
271
- | `theme` | `string` | `'futuristic'` | UI theme: 'classic' or 'futuristic' |
272
- | `primaryColor` | `string` | `'#00f2ff'` | Primary accent color for UI |
273
- | `apiTitle` | `string` | `auto-detected` | API title (auto-detected from package.json) |
274
- | `apiVersion` | `string` | `auto-detected` | API version (auto-detected from package.json) |
275
- | `useIncrementalScanning` | `boolean` | `false` | Enable caching for faster startup times |
276
- | `enableWatchMode` | `boolean` | `false` | Auto-regenerate docs on file changes |
277
- | `cacheTtl` | `number` | `24h` | Cache time-to-live in milliseconds |
278
-
279
- ### 🎯 baseUrl Configuration
280
-
281
- The `baseUrl` option is now properly respected in the dashboard display:
282
-
283
- ```typescript
284
- // Example with custom baseUrl
285
- NestScrambleModule.forRoot({
286
- baseUrl: 'http://127.0.0.1:4444',
287
- path: '/api-docs'
288
- })
289
- ```
290
-
291
- **Dashboard Output:**
292
- ```
293
- β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
294
- β”‚ ✨ NEST-SCRAMBLE by Mohamed Mustafa β”‚
295
- β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
296
- β”‚ ● Documentation β”‚
297
- β”‚ β†’ http://127.0.0.1:4444/api-docs β”‚
298
- β”‚ ● OpenAPI Spec β”‚
299
- β”‚ β†’ http://127.0.0.1:4444/api-docs-json β”‚
300
- β”‚ ● Mock Server β”‚
301
- β”‚ β†’ http://127.0.0.1:4444/scramble-mock β”‚
302
- β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
303
- ```
304
-
305
- ## 🎭 Live Mocking Guide
306
-
307
- Nest-Scramble provides **instant API mocking** without writing controllers:
308
-
309
- ### How It Works
310
- 1. Define your DTOs and controllers normally
311
- 2. Enable `enableMock: true`
312
- 3. All requests to `/scramble-mock/*` return smart mock data
313
-
314
- ### Example
315
-
316
- **Controller:**
317
- ```typescript
318
- @Controller('users')
319
- export class UserController {
320
- @Get(':id')
321
- getUser(@Param('id') id: number): UserDto {
322
- // Your logic here
323
- }
324
- }
325
- ```
326
-
327
- **Mock Response:**
328
- ```bash
329
- GET /scramble-mock/users/123
330
- # Returns: { "id": 123, "name": "John Doe", "email": "john@example.com" }
331
- ```
332
-
333
- **Smart Mocking Examples:**
334
- - `email` β†’ `faker.internet.email()`
335
- - `name` β†’ `faker.person.fullName()`
336
- - `createdAt` β†’ `faker.date.recent()`
337
- - `posts` β†’ Array of mock posts
338
-
339
- ![Live mocking demo](mock-demo.gif)
340
-
341
- ## πŸ”§ Advanced Usage
342
-
343
- ### CLI Generation
344
-
345
- The Nest-Scramble CLI allows you to generate API documentation without running your NestJS application.
346
-
347
- #### Generate OpenAPI Specification
348
-
349
- ```bash
350
- # Using npx
351
- npx nest-scramble generate src
352
-
353
- # Using pnpm dlx
354
- pnpm dlx nest-scramble generate src
355
-
356
- # Using yarn dlx
357
- yarn dlx nest-scramble generate src
358
- ```
359
-
360
- #### CLI Options
361
-
362
- ```bash
363
- nest-scramble generate <sourcePath> [options]
364
-
365
- Options:
366
- -o, --output <file> Output file path (default: "openapi.json")
367
- -f, --format <type> Output format: openapi or postman (default: "openapi")
368
- -b, --baseUrl <url> Base URL for the API (default: "http://localhost:3000")
369
- -t, --title <title> API title (default: "NestJS API")
370
- -v, --apiVersion <version> API version (default: "1.0.0")
371
- -h, --help Display help for command
372
- ```
373
-
374
- #### Examples
375
-
376
- **Generate OpenAPI JSON:**
377
- ```bash
378
- pnpm dlx nest-scramble generate src --output openapi.json
379
- ```
380
-
381
- **Generate Postman Collection:**
382
- ```bash
383
- pnpm dlx nest-scramble generate src --format postman --output collection.json
384
- ```
385
-
386
- **Custom API Details:**
387
- ```bash
388
- pnpm dlx nest-scramble generate src \
389
- --output my-api.json \
390
- --title "My Awesome API" \
391
- --apiVersion "2.0.0" \
392
- --baseUrl "https://api.example.com"
393
- ```
394
-
395
- **Check Version:**
396
- ```bash
397
- pnpm dlx nest-scramble --version
398
- ```
399
-
400
- ### Programmatic API
401
-
402
- Use Nest-Scramble programmatically in your Node.js scripts:
403
-
404
- ```typescript
405
- import { ScannerService, OpenApiTransformer, PostmanCollectionGenerator } from 'nest-scramble';
406
- import * as fs from 'fs';
407
-
408
- // Scan controllers
409
- const scanner = new ScannerService();
410
- const controllers = scanner.scanControllers('src');
411
-
412
- // Generate OpenAPI spec
413
- const transformer = new OpenApiTransformer('http://localhost:3000');
414
- const openApiSpec = transformer.transform(
415
- controllers,
416
- 'My API',
417
- '1.0.0',
418
- 'http://localhost:3000'
419
- );
420
-
421
- // Save to file
422
- fs.writeFileSync('openapi.json', JSON.stringify(openApiSpec, null, 2));
423
-
424
- // Or generate Postman collection
425
- const postmanGen = new PostmanCollectionGenerator('http://localhost:3000');
426
- const collection = postmanGen.generateCollection(controllers);
427
- fs.writeFileSync('collection.json', JSON.stringify(collection, null, 2));
428
- ```
429
-
430
- ### CI/CD Integration
431
-
432
- Add to your CI/CD pipeline to auto-generate documentation:
433
-
434
- ```yaml
435
- # .github/workflows/docs.yml
436
- name: Generate API Docs
437
-
438
- on:
439
- push:
440
- branches: [main]
441
-
442
- jobs:
443
- generate-docs:
444
- runs-on: ubuntu-latest
445
- steps:
446
- - uses: actions/checkout@v3
447
- - uses: actions/setup-node@v3
448
- with:
449
- node-version: '18'
450
- - run: npm install
451
- - run: npx nest-scramble generate src --output openapi.json
452
- - uses: actions/upload-artifact@v3
453
- with:
454
- name: api-docs
455
- path: openapi.json
456
- ```
457
-
458
- ## ⚑ Incremental Scanning & Advanced Caching (NEW!)
459
-
460
- ### πŸš€ World-Class Performance Optimization
461
-
462
- Nest-Scramble now includes a **production-grade incremental scanning system** with intelligent caching and dependency tracking. This delivers **10-100x faster** re-scans during development and ensures zero stale data even in large monorepos.
463
-
464
- **Key Features:**
465
- - πŸ”₯ **Smart Caching** - MD5/SHA-256 hashing with file size verification
466
- - πŸ”— **Transitive Dependencies** - Tracks inheritance chains and indirect dependencies
467
- - 🎯 **Partial AST Updates** - Only re-scans modified files and their dependents
468
- - πŸ’Ύ **Persistent Cache** - Survives restarts with `scramble-cache.json`
469
- - πŸ›‘οΈ **Hash Collision Detection** - Multi-layer verification prevents stale data
470
- - 🧹 **Memory Management** - Proper cleanup for long dev sessions
471
-
472
- ### πŸ“Š Performance Benchmarks
473
-
474
- ```
475
- Traditional Scanner (no cache): 2000ms
476
- Incremental Scanner (cold cache): 2100ms (5% overhead for cache building)
477
- Incremental Scanner (warm cache): 50ms (40x faster!)
478
- Single file update: 20ms (100x faster!)
479
- DTO change (5 dependents): 100ms (20x faster!)
480
- ```
481
-
482
- ### 🎯 Use Cases
483
-
484
- **Development Mode:**
485
- ```typescript
486
- import { WatchModeService } from 'nest-scramble';
487
-
488
- const watchMode = new WatchModeService({
489
- sourcePath: 'src',
490
- outputPath: 'openapi.json',
491
- baseUrl: 'http://localhost:3000',
492
- useCache: true, // Enable smart caching
493
- });
494
-
495
- await watchMode.start();
496
- // βœ… Auto-regenerates docs on file changes
497
- // βœ… Only re-scans affected files
498
- // βœ… Tracks DTO inheritance chains
499
- ```
500
-
501
- **Programmatic API with Caching:**
502
- ```typescript
503
- import { IncrementalScannerService } from 'nest-scramble';
504
-
505
- const scanner = new IncrementalScannerService({
506
- useCache: true,
507
- cacheFilePath: '.scramble-cache.json',
508
- // Optional: Use SHA-256 for large projects (>1000 files)
509
- // hashAlgorithm: 'sha256',
510
- });
511
-
512
- // Initialize and perform full scan
513
- scanner.initialize('src');
514
- const controllers = scanner.scanControllers('src');
515
-
516
- // Process file changes incrementally
517
- const changes = [
518
- { type: 'change', filePath: 'src/users.controller.ts', hash: '...' }
519
- ];
520
- const results = scanner.processFileChanges(changes);
521
-
522
- // Cleanup when done
523
- scanner.cleanup();
524
- ```
525
-
526
- ### πŸ”— Transitive Dependency Tracking
527
-
528
- The system automatically tracks **inheritance chains** and **indirect dependencies**:
529
-
530
- **Example Scenario:**
531
- ```typescript
532
- // base.dto.ts
533
- export class BaseDto {
534
- id: number;
535
- createdAt: Date;
536
- }
537
-
538
- // update-user.dto.ts
539
- export class UpdateUserDto extends BaseDto {
540
- name: string;
541
- email: string;
542
- }
543
-
544
- // users.controller.ts
545
- @Controller('users')
546
- export class UsersController {
547
- @Put(':id')
548
- update(@Body() dto: UpdateUserDto) { }
549
- }
550
- ```
551
-
552
- **What happens when `BaseDto` changes:**
553
- 1. βœ… System detects `UpdateUserDto` inherits from `BaseDto`
554
- 2. βœ… System finds `UsersController` depends on `UpdateUserDto`
555
- 3. βœ… All three files are marked for re-scanning
556
- 4. βœ… **No stale data** - even with deep inheritance chains!
557
-
558
- ### πŸ” Hash Collision Prevention
559
-
560
- Multi-layer verification system ensures **zero stale data**:
561
-
562
- **Layer 1: Hash Comparison**
563
- - MD5 (default) - Fast, suitable for most projects
564
- - SHA-256 (optional) - More secure for large monorepos
565
-
566
- **Layer 2: File Size Verification**
567
- - Catches hash collisions automatically
568
- - Triggers re-scan if size differs
569
-
570
- **Layer 3: Collision Tracking**
571
- - Monitors and logs collision events
572
- - Auto-alerts after 3+ collisions
573
- - Recommends switching to SHA-256
574
-
575
- **Configuration:**
576
- ```typescript
577
- const scanner = new IncrementalScannerService({
578
- useCache: true,
579
- hashAlgorithm: 'sha256', // Use SHA-256 for large projects
580
- });
581
- ```
582
-
583
- ### πŸ“¦ Cache Invalidation Strategy
584
-
585
- The cache automatically invalidates when:
586
- - βœ… Cache version mismatch (after library upgrade)
587
- - βœ… TTL expiration (default: 24 hours, configurable)
588
- - βœ… `tsconfig.json` changes
589
- - βœ… File content hash changes
590
- - βœ… File size differs (collision detection)
591
- - βœ… File deletion
592
- - βœ… DTO dependency changes
593
- - βœ… Manual invalidation
594
-
595
- **Custom TTL:**
596
- ```typescript
597
- const cacheManager = new CacheManager({
598
- ttl: 12 * 60 * 60 * 1000, // 12 hours
599
- });
600
- ```
601
-
602
- ### 🎯 Best Practices
603
-
604
- **1. Add Cache to .gitignore:**
605
- ```gitignore
606
- # Nest-Scramble cache
607
- scramble-cache.json
608
- .scramble-cache.json
609
- ```
610
-
611
- **2. Use Watch Mode in Development:**
612
- ```bash
613
- # Terminal 1: Run your NestJS app
614
- npm run start:dev
615
-
616
- # Terminal 2: Run Nest-Scramble watch mode
617
- npx nest-scramble watch src -o openapi.json
618
- ```
619
-
620
- **3. Choose Hash Algorithm Based on Project Size:**
621
- - **Small/Medium (<1000 files):** Use MD5 (default, fastest)
622
- - **Large (>1000 files):** Use SHA-256 (more secure)
623
- - **Monorepos (10k+ files):** Use SHA-256 + monitor collisions
624
-
625
- **4. Monitor Cache Performance:**
626
- ```typescript
627
- const stats = scanner.getCacheManager().getStats();
628
- console.log(`Cache: ${stats.controllerCount} controllers`);
629
- console.log(`Hash algorithm: ${stats.hashAlgorithm}`);
630
- console.log(`Collisions: ${stats.hashCollisions}`);
631
- console.log(`Size: ${(stats.cacheSize / 1024).toFixed(2)} KB`);
632
- ```
633
-
634
- ### πŸ§ͺ Advanced Examples
635
-
636
- **Example 1: Dependency Analysis**
637
- ```typescript
638
- import { DependencyTracker } from 'nest-scramble';
639
-
640
- const tracker = scanner.getDependencyTracker();
641
- const info = tracker.getDependencyInfo('src/users.controller.ts');
642
-
643
- console.log('Dependencies:', info.dependencies);
644
- console.log('Dependents:', info.dependents);
645
- console.log('Inheritance chain:', info.inheritanceChain);
646
- console.log('Transitive affected:', info.transitiveAffected);
647
- ```
648
-
649
- **Example 2: Cache Performance Test**
650
- ```typescript
651
- // See: src/examples/cache-performance-test.ts
652
- import { runPerformanceTest } from 'nest-scramble/examples';
653
-
654
- await runPerformanceTest();
655
- // Compares traditional vs incremental scanning
656
- // Shows real performance metrics
657
- ```
658
-
659
- **Example 3: Hash Collision Detection**
660
- ```typescript
661
- // See: src/examples/hash-collision-demo.ts
662
- import { demonstrateHashCollisionDetection } from 'nest-scramble/examples';
663
-
664
- await demonstrateHashCollisionDetection();
665
- // Shows multi-layer verification in action
666
- // Compares MD5 vs SHA-256 performance
667
- ```
668
-
669
- ### πŸ“š Additional Resources
670
-
671
- - **[Advanced Dependency Tracking Example](./src/examples/advanced-dependency-tracking.ts)** - Transitive dependencies demo
672
- - **[Hash Collision Demo](./src/examples/hash-collision-demo.ts)** - Multi-layer verification
673
- - **[Cache Performance Test](./src/examples/cache-performance-test.ts)** - Benchmark comparisons
674
- - **[Complete Integration Example](./src/examples/complete-integration-example.ts)** - Production-ready setup
675
-
676
- ## 🎨 Documentation UI - Professional API Dashboard
677
-
678
- ### ✨ Elite Dashboard Design (NEW!)
679
-
680
- Nest-Scramble features a **professional, high-end API dashboard** inspired by Stripe and Postman, with refined typography and a polished dark palette for long reading sessions.
681
-
682
- **πŸš€ Key Features:**
683
- - **Sidebar-Only Navigation** - Fixed 320px sidebar with controller grouping
684
- - **Single-Request Per Page** - Each endpoint gets its own dedicated view
685
- - **Three-Column Elite Layout** - Information | Request Editor | Test Panel
686
- - **Soft Dark Background** - Refined deep blues for a premium, eye-friendly dark mode
687
- - **Cyber-Cyan Accents** - `#00f2ff` for active states and primary actions
688
- - **Vibrant HTTP Method Badges** - Color-coded with glow effects:
689
- - GET = Royal Blue (`#3B82F6`)
690
- - POST = Emerald Green (`#10B981`)
691
- - PUT = Amber Orange (`#F59E0B`)
692
- - PATCH = Violet Purple (`#8B5CF6`)
693
- - DELETE = Vibrant Red (`#EF4444`)
694
- - **Glassmorphism Effects** - Backdrop blur on request/response panels
695
- - **40px Spacious Padding** - Premium whitespace throughout
696
- - **Terminal-Style Response** - Black box with green text for API responses
697
- - **High-Contrast Labels** - Required, Type, and Default badges
698
- - **Custom Scrollbars** - Gradient cyan-to-purple styling
699
- - **Plus Jakarta Sans Typography** - Modern, professional font family with optimized sizing
700
- - **Clear Sidebar Text** - Slightly larger nav fonts for effortless scanning
701
- - **Powered by Badge** - Animated branding with pulse effect
702
-
703
- ### πŸ“ Three-Column Elite Interface
704
-
705
- The dashboard uses a professional three-column layout for each endpoint:
706
-
707
- **Column 1 (Left) - Information Panel:**
708
- - Endpoint title with large, bold typography
709
- - HTTP method badge with vibrant colors and glow
710
- - Endpoint description and documentation
711
- - Clean parameters table with high-contrast labels
712
- - Type information and required field indicators
713
-
714
- **Column 2 (Middle) - Request Body Editor:**
715
- - Glassmorphism design with backdrop blur
716
- - Auto-filled mock data examples
717
- - JSON editor with syntax highlighting
718
- - Copy-to-clipboard functionality
719
- - Real-time validation
720
-
721
- **Column 3 (Right) - Test Request Panel:**
722
- - Enhanced glassmorphism with cyan border glow
723
- - Large "Send Request" button with gradient animation
724
- - Terminal-style response viewer (black background, green text)
725
- - Status code indicators
726
- - Response headers display
727
-
728
- ### 🎨 Theme Customization
729
-
730
- **Futuristic Theme (Default):**
731
- ```typescript
732
- NestScrambleModule.forRoot({
733
- theme: 'futuristic', // Professional dark dashboard
734
- primaryColor: '#00f2ff', // Cyber-Cyan (default)
735
- customDomainIcon: '/logo.png', // Your brand favicon
736
- apiTitle: 'My Awesome API',
737
- })
738
- ```
739
-
740
- **Classic Theme:**
741
- ```typescript
742
- NestScrambleModule.forRoot({
743
- theme: 'classic', // Clean, light, professional
744
- primaryColor: '#0066cc', // Corporate blue
745
- apiTitle: 'Enterprise API',
746
- })
747
- ```
748
-
749
- **Custom Color Branding:**
750
- ```typescript
751
- // One line changes the entire UI color scheme!
752
- NestScrambleModule.forRoot({
753
- primaryColor: '#a855f7', // Electric Purple
754
- // or '#10b981' for Emerald Green
755
- // or '#f59e0b' for Amber Orange
756
- // or any hex color you want!
757
- })
758
- ```
759
-
760
- ### 🎭 UI Configuration Options
761
-
762
- | Option | Type | Default | Description |
763
- |--------|------|---------|-------------|
764
- | `theme` | `'classic' \| 'futuristic'` | `'futuristic'` | UI theme selection |
765
- | `primaryColor` | `string` | `'#00f2ff'` | Primary accent color (hex) |
766
- | `customDomainIcon` | `string` | `''` | Custom favicon URL |
767
- | `apiTitle` | `string` | Auto-detected | API documentation title |
768
- | `apiVersion` | `string` | Auto-detected | API version number |
769
-
770
- ### 🌟 Interactive Features
771
-
772
- When you visit `http://localhost:3000/docs`, you'll experience:
773
-
774
- - 🎯 **Single-Request Navigation** - Each endpoint on its own dedicated page
775
- - πŸ“‚ **Controller Grouping** - Organized sidebar with uppercase section headers
776
- - 🎨 **Active State Glow** - Cyber-cyan highlight for selected endpoints
777
- - πŸ“ **Auto-generated Examples** - Pre-filled mock data in request editor
778
- - πŸ§ͺ **Live Testing** - Send requests directly from the three-column interface
779
- - πŸ’» **Terminal Response** - Black box with green text for authentic feel
780
- - πŸ” **Quick Search** - Press 'K' to search endpoints instantly
781
- - πŸ“± **Responsive Design** - Adapts to mobile, tablet, and desktop
782
- - ✨ **Animated Branding** - Pulsing "Powered by Nest-Scramble" badge
783
- - 🎭 **Developer Easter Eggs** - Check your browser console for surprises!
784
-
785
- ### πŸ–₯️ Terminal Dashboard
786
-
787
- The startup dashboard now features **gradient styling** with ANSI colors:
788
-
789
- ```
790
- ╔═══════════════════════════════════════════════════════════════╗
791
- β•‘ ✨ NEST-SCRAMBLE by Mohamed Mustafa β•‘
792
- β•‘ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ β•‘
793
- β•‘ β•‘
794
- β•‘ ● Documentation β•‘
795
- β•‘ β†’ http://localhost:3000/docs β•‘
796
- β•‘ β•‘
797
- β•‘ ● OpenAPI Spec β•‘
798
- β•‘ β†’ http://localhost:3000/docs-json β•‘
799
- β•‘ β•‘
800
- β•‘ ● Mock Server β•‘
801
- β•‘ β†’ http://localhost:3000/scramble-mock β•‘
802
- β•‘ β•‘
803
- β•‘ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ β•‘
804
- β•‘ πŸ“¦ Source Path: src β•‘
805
- β•‘ 🎯 Controllers: 5 β•‘
806
- β•‘ 🎨 Theme: Futuristic β•‘
807
- β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
808
- ```
809
-
810
- ### πŸ“š More UI Documentation
811
-
812
- For complete UI customization guide, see:
813
- - **[UI_FEATURES.md](./UI_FEATURES.md)** - Comprehensive feature documentation
814
- - **[examples/futuristic-ui-example.ts](./examples/futuristic-ui-example.ts)** - Usage examples
815
-
816
- ### Available Endpoints
817
-
818
- | Endpoint | Description |
819
- |----------|-------------|
820
- | `GET /docs` | Interactive Scalar UI documentation |
821
- | `GET /docs-json` | OpenAPI 3.0 JSON specification |
822
- | `GET /docs/json` | Legacy endpoint (same as above) |
823
- | `GET /docs/spec` | OpenAPI spec as JSON response |
824
-
825
- ### Accessing the OpenAPI Spec
826
-
827
- You can use the OpenAPI JSON with other tools:
828
-
829
- ```bash
830
- # Download the spec
831
- curl http://localhost:3000/docs-json > openapi.json
832
-
833
- # Use with Swagger UI
834
- docker run -p 8080:8080 -e SWAGGER_JSON=/openapi.json -v $(pwd):/usr/share/nginx/html/openapi.json swaggerapi/swagger-ui
835
-
836
- # Import into Postman
837
- # File > Import > Link > http://localhost:3000/docs-json
838
- ```
839
-
840
- ## βœ… Supported Features
841
-
842
- ### Type Analysis
843
- - βœ… Primitive types (string, number, boolean)
844
- - βœ… Arrays and nested objects
845
- - βœ… Union types
846
- - βœ… Enums
847
- - βœ… Optional properties
848
- - βœ… Circular references (auto-detected)
849
-
850
- ### HTTP Methods
851
- - βœ… GET, POST, PUT, DELETE, PATCH
852
- - βœ… Path parameters (@Param)
853
- - βœ… Query parameters (@Query)
854
- - βœ… Request bodies (@Body)
855
-
856
- ### Code Generation
857
- - βœ… Curl commands
858
- - βœ… JavaScript Fetch
859
- - βœ… TypeScript with types
860
-
861
- ## πŸ§ͺ Testing with Demo Controller
862
-
863
- The library includes a `DemoController` with complex DTOs:
864
-
865
- ```typescript
866
- // Complex DTOs with circular references
867
- export class UserDto {
868
- id: number;
869
- name: string;
870
- email: string;
871
- role: UserRole; // Enum
872
- address: AddressDto; // Nested
873
- posts: PostDto[]; // Circular reference
874
- }
875
-
876
- export class PostDto {
877
- id: number;
878
- title: string;
879
- content: string;
880
- author: UserDto; // Circular reference
881
- }
882
- ```
883
-
884
- Run the demo to verify everything works perfectly.
885
-
886
- ## πŸ—ΊοΈ Roadmap
887
-
888
- - [ ] GraphQL support
889
- - [ ] Custom mock data providers
890
- - [ ] Authentication integration
891
- - [ ] API versioning
892
- - [ ] Performance optimizations
893
- - [ ] Plugin system for custom analyzers
894
-
895
- ## πŸ”§ Troubleshooting
896
-
897
- ### Common Issues
898
-
899
- #### 1. **"No controllers found" Warning**
900
-
901
- If you see this warning on startup:
902
- ```
903
- [Nest-Scramble] No controllers found in /src. Please check your sourcePath config.
904
- ```
905
-
906
- **Solution:**
907
- - Ensure your `sourcePath` option points to the correct directory containing your controllers
908
- - Check that your controllers use the `@Controller()` decorator from `@nestjs/common`
909
- - Verify your project structure matches the configured path
910
-
911
- ```typescript
912
- NestScrambleModule.forRoot({
913
- sourcePath: 'src', // Make sure this matches your project structure
914
- })
915
- ```
916
-
917
- #### 2. **UI Not Loading / Blank Page at /docs**
918
-
919
- **Solution:**
920
- - Clear your browser cache and hard refresh (Ctrl+Shift+R / Cmd+Shift+R)
921
- - Check browser console for errors
922
- - Verify the `/docs-json` endpoint returns valid JSON
923
- - Ensure you're using version 3.0.0 or higher: `npm list nest-scramble`
924
- - Verify NestJS version compatibility (v10.x or v11.x required)
925
- - Check Node.js version: `node --version` (must be >=18.10.0)
926
- - Check TypeScript version: `npx tsc --version` (must be >=5.0.0)
927
-
928
- #### 3. **TypeScript Compilation Errors**
929
-
930
- If you get errors like `Cannot find module 'nest-scramble'`:
931
-
932
- **Solution:**
933
- ```bash
934
- # Clear node_modules and reinstall
935
- rm -rf node_modules package-lock.json
936
- npm install
937
-
938
- # Rebuild your project
939
- npm run build
940
- ```
941
-
942
- #### 4. **"Unauthorized" (401) Error on /docs Endpoint**
943
-
944
- If you have a Global AuthGuard and get 401 Unauthorized when accessing `/docs` or `/docs-json`:
945
-
946
- **Solution:**
947
-
948
- Nest-Scramble automatically marks its documentation endpoints as public using `@SetMetadata('isPublic', true)`. However, your AuthGuard needs to respect this metadata.
949
-
950
- Update your AuthGuard to check for the `isPublic` metadata:
951
-
952
- ```typescript
953
- import { Injectable, ExecutionContext } from '@nestjs/common';
954
- import { Reflector } from '@nestjs/core';
955
- import { AuthGuard } from '@nestjs/passport';
956
-
957
- @Injectable()
958
- export class JwtAuthGuard extends AuthGuard('jwt') {
959
- constructor(private reflector: Reflector) {
960
- super();
961
- }
962
-
963
- canActivate(context: ExecutionContext) {
964
- // Check if route is marked as public
965
- const isPublic = this.reflector.getAllAndOverride<boolean>('isPublic', [
966
- context.getHandler(),
967
- context.getClass(),
968
- ]);
969
-
970
- if (isPublic) {
971
- return true; // Allow access to public routes
972
- }
973
-
974
- return super.canActivate(context);
975
- }
976
- }
977
- ```
978
-
979
- **Alternative Solution - Exclude /docs path:**
980
-
981
- ```typescript
982
- import { Module } from '@nestjs/common';
983
- import { APP_GUARD } from '@nestjs/core';
984
-
985
- @Module({
986
- providers: [
987
- {
988
- provide: APP_GUARD,
989
- useClass: JwtAuthGuard,
990
- },
991
- ],
992
- })
993
- export class AppModule {}
994
-
995
- // In your AuthGuard:
996
- canActivate(context: ExecutionContext) {
997
- const request = context.switchToHttp().getRequest();
998
-
999
- // Skip authentication for documentation endpoints
1000
- if (request.url.startsWith('/docs')) {
1001
- return true;
1002
- }
1003
-
1004
- return super.canActivate(context);
1005
- }
1006
- ```
1007
-
1008
- #### 5. **pnpm Dependency Conflicts**
1009
-
1010
- If using pnpm and getting peer dependency warnings:
1011
-
1012
- **Solution:**
1013
- Nest-Scramble v1.1.0+ properly declares peer dependencies. Update to the latest version:
1014
- ```bash
1015
- pnpm update nest-scramble
1016
- ```
1017
-
1018
- #### 6. **Controllers Not Being Scanned**
1019
-
1020
- The scanner looks in your **host project's** `src` folder, not the library's folder.
1021
-
1022
- **Diagnostic Steps:**
1023
- 1. Check the startup logs - they show exactly where the scanner is looking:
1024
- ```
1025
- [Nest-Scramble] Scanning directory: /path/to/your/project/src
1026
- [Nest-Scramble] Found X controller(s)
1027
- ```
1028
-
1029
- 2. Ensure your controllers are in TypeScript files (`.ts`) not JavaScript (`.js`)
1030
-
1031
- 3. Verify your `tsconfig.json` exists in the project root
1032
-
1033
- #### 7. **Mock Endpoints Not Working**
1034
-
1035
- If `/scramble-mock/*` returns 404:
1036
-
1037
- **Solution:**
1038
- - Ensure `enableMock: true` in your configuration
1039
- - The middleware applies to all routes matching `/scramble-mock/*`
1040
- - Example: `http://localhost:3000/scramble-mock/users/123`
1041
-
1042
- #### 8. **OpenAPI Spec is Empty or Incomplete**
1043
-
1044
- **Solution:**
1045
- - Ensure your DTOs are TypeScript classes or interfaces (not plain objects)
1046
- - Check that your controller methods have proper return type annotations
1047
- - Verify decorators are imported from `@nestjs/common`
1048
-
1049
- ```typescript
1050
- // βœ… Good - Explicit return type
1051
- @Get(':id')
1052
- getUser(@Param('id') id: string): UserDto {
1053
- return this.userService.findOne(id);
1054
- }
1055
-
1056
- // ❌ Bad - No return type
1057
- @Get(':id')
1058
- getUser(@Param('id') id: string) {
1059
- return this.userService.findOne(id);
1060
- }
1061
- ```
1062
-
1063
- ### Getting Help
1064
-
1065
- If you're still experiencing issues:
1066
-
1067
- 1. **Check the logs** - Nest-Scramble provides detailed diagnostic output on startup
1068
- 2. **Verify your version** - Run `npm list nest-scramble` (should be 3.0.0+)
1069
- 3. **Check NestJS compatibility** - Verify you're using NestJS v10.x or v11.x (v9 is no longer supported)
1070
- 4. **Check Node.js version** - Run `node --version` (must be >=18.10.0)
1071
- 5. **Check TypeScript version** - Run `npx tsc --version` (must be >=5.0.0)
1072
- 6. **Open an issue** - [GitHub Issues](https://github.com/Eng-MMustafa/nest-scramble/issues)
1073
-
1074
- When reporting issues, please include:
1075
- - Nest-Scramble version (3.0.0+)
1076
- - NestJS version (v10.x or v11.x)
1077
- - Node.js version (>=18.10.0)
1078
- - TypeScript version (>=5.0.0)
1079
- - Package manager (npm/yarn/pnpm)
1080
- - Startup logs
1081
- - Sample controller code
1082
-
1083
- ## 🀝 Contributing
1084
-
1085
- We welcome contributions! Please:
1086
-
1087
- 1. Fork the repository
1088
- 2. Create a feature branch
1089
- 3. Add tests for new features
1090
- 4. Submit a pull request
1091
-
1092
- ## πŸ“„ License
1093
-
1094
- MIT License - see [LICENSE](LICENSE) file.
1095
-
1096
- ## β€πŸ’» About the Author
1097
-
1098
- ![Mohamed Mustafa](https://via.placeholder.com/150x150?text=Mohamed+Mustafa)
1099
-
1100
- Mohamed Mustafa is a passionate full-stack developer with a deep love for TypeScript and modern web frameworks. His mission is to build tools that enhance developer experience and eliminate repetitive tasks. When he's not crafting open-source libraries, you'll find him exploring new technologies, contributing to the developer community, or sharing insights through technical writing.
1101
-
1102
- - [GitHub](https://github.com/Eng-MMustafa)
1103
- - [LinkedIn](https://www.linkedin.com/in/engmohammedmustafa/)
1
+ # Nest-Scramble
2
+
3
+ > Zero-config API Documentation, Postman Generator & Typed Client SDK for NestJS β€” powered by static TypeScript analysis
4
+
5
+ [![npm version](https://badge.fury.io/js/nest-scramble.svg)](https://badge.fury.io/js/nest-scramble)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+ [![GitHub stars](https://img.shields.io/github/stars/Eng-MMustafa/nest-scramble.svg)](https://github.com/Eng-MMustafa/nest-scramble)
8
+ [![Author](https://img.shields.io/badge/Author-Mohamed%20Mustafa-blue.svg)](https://github.com/Eng-MMustafa)
9
+ [![NestJS Compatibility](https://img.shields.io/badge/NestJS-10%20%7C%2011-blue.svg)](https://docs.nestjs.com)
10
+ [![Node Version](https://img.shields.io/badge/node-%3E%3D18.10.0-brightgreen.svg)](https://nodejs.org)
11
+ [![TypeScript](https://img.shields.io/badge/typescript-%3E%3D5.0.0-blue.svg)](https://www.typescriptlang.org)
12
+
13
+ ---
14
+
15
+ ## What's New in v3.0.4
16
+
17
+ ### Typed HTTP Client SDK Generation ✨
18
+
19
+ The biggest quality-of-life addition yet. Nest-Scramble can now **generate a fully-typed TypeScript API client** directly from your NestJS controllers β€” no OpenAPI tooling required, no extra decorators, zero dependencies in the output.
20
+
21
+ ```bash
22
+ npx nest-scramble generate src --format client --output ./api-client.ts
23
+ ```
24
+
25
+ **Generated output (`api-client.ts`):**
26
+
27
+ ```typescript
28
+ // Auto-generated by nest-scramble v3.0.4 β€” do not edit manually
29
+ // Re-generate: npx nest-scramble generate src --format client
30
+
31
+ export class UsersApiClient {
32
+ constructor(private readonly baseUrl: string) {}
33
+
34
+ async getUsers(page?: number, limit?: number): Promise<UserListDto[]> {
35
+ const url = new URL(`${this.baseUrl}/users`);
36
+ if (page !== undefined) url.searchParams.set('page', String(page));
37
+ if (limit !== undefined) url.searchParams.set('limit', String(limit));
38
+ const res = await fetch(url.toString());
39
+ return res.json();
40
+ }
41
+
42
+ async createUser(body: CreateUserDto): Promise<UserDto> {
43
+ const res = await fetch(`${this.baseUrl}/users`, {
44
+ method: 'POST',
45
+ headers: { 'Content-Type': 'application/json' },
46
+ body: JSON.stringify(body),
47
+ });
48
+ return res.json();
49
+ }
50
+
51
+ async deleteUser(id: string): Promise<void> {
52
+ await fetch(`${this.baseUrl}/users/${id}`, { method: 'DELETE' });
53
+ }
54
+ }
55
+ ```
56
+
57
+ **Use it anywhere β€” frontend, E2E tests, microservices:**
58
+
59
+ ```typescript
60
+ import { UsersApiClient } from './api-client';
61
+
62
+ const client = new UsersApiClient('http://localhost:3000');
63
+ const users = await client.getUsers(1, 10); // fully typed βœ…
64
+ ```
65
+
66
+ No extra runtime packages. Uses native `fetch`. Stays in sync with your controllers by re-running the command.
67
+
68
+ ### Other v3.0.4 changes
69
+
70
+ - Controller-based sidebar grouping is now the default (no config needed)
71
+ - Route param normalisation `:id` β†’ `{id}` for full OpenAPI compliance
72
+ - Scalar standalone HTML integration for more reliable docs rendering
73
+ - `baseUrl` is now respected exactly as configured in the dashboard
74
+
75
+ ---
76
+
77
+ ## Why Nest-Scramble
78
+
79
+ No `@ApiProperty` decorators. No runtime overhead. Nest-Scramble reads your TypeScript source using AST analysis and automatically produces:
80
+
81
+ | | Nest-Scramble | @nestjs/swagger |
82
+ |---|---|---|
83
+ | Analysis | Static AST (compile-time) | Runtime reflection |
84
+ | Decorators required | None | `@ApiProperty` everywhere |
85
+ | Circular references | Auto-detected | Manual workarounds |
86
+ | Performance overhead | Zero | Decorator cost on every request |
87
+ | Postman collection | Built-in | Third-party export |
88
+ | Typed client SDK | βœ… v3.0.4 | βœ— |
89
+
90
+ ---
91
+
92
+ ## Quick Start
93
+
94
+ ### Option A β€” Auto-inject (30 seconds)
95
+
96
+ ```bash
97
+ npm install nest-scramble
98
+ npx nest-scramble init
99
+ npm run start:dev
100
+ # Visit http://localhost:3000/docs
101
+ ```
102
+
103
+ The `init` command patches your `app.module.ts` automatically.
104
+
105
+ ### Option B β€” Manual
106
+
107
+ **1. Install**
108
+
109
+ ```bash
110
+ npm install nest-scramble
111
+ # yarn add nest-scramble
112
+ # pnpm add nest-scramble
113
+ ```
114
+
115
+ **2. Register the module**
116
+
117
+ ```typescript
118
+ import { Module } from '@nestjs/common';
119
+ import { NestScrambleModule } from 'nest-scramble';
120
+
121
+ @Module({
122
+ imports: [NestScrambleModule.forRoot()], // zero-config
123
+ })
124
+ export class AppModule {}
125
+ ```
126
+
127
+ **3. Start your app**
128
+
129
+ ```bash
130
+ npm run start:dev
131
+ ```
132
+
133
+ Terminal output:
134
+
135
+ ```
136
+ ╔═══════════════════════════════════════════════════════╗
137
+ β•‘ ✨ NEST-SCRAMBLE by Mohamed Mustafa β•‘
138
+ β•‘ β•‘
139
+ β•‘ ● Docs β†’ http://localhost:3000/docs β•‘
140
+ β•‘ ● OpenAPI β†’ http://localhost:3000/docs-json β•‘
141
+ β•‘ ● Mock β†’ http://localhost:3000/scramble-mock β•‘
142
+ β•‘ β•‘
143
+ β•‘ πŸ“¦ Source: src 🎯 Controllers: 5 β•‘
144
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
145
+ ```
146
+
147
+ ---
148
+
149
+ ## Configuration
150
+
151
+ ```typescript
152
+ NestScrambleModule.forRoot({
153
+ sourcePath: 'src', // default: 'src'
154
+ baseUrl: 'http://localhost:3000', // default: auto-detected from PORT/HOST
155
+ path: '/docs', // default: '/docs'
156
+ enableMock: true, // default: true
157
+ autoExportPostman: false, // default: false
158
+ postmanOutputPath: 'collection.json', // default: 'collection.json'
159
+ theme: 'futuristic', // 'classic' | 'futuristic'
160
+ primaryColor: '#00f2ff', // any hex colour
161
+ customDomainIcon: '', // favicon URL
162
+ apiTitle: 'My API', // default: from package.json
163
+ apiVersion: '1.0.0', // default: from package.json
164
+ useIncrementalScanning: false, // faster startup via caching
165
+ enableWatchMode: false, // auto-regenerate on file changes
166
+ cacheTtl: 86400000, // cache TTL in ms (default: 24h)
167
+ })
168
+ ```
169
+
170
+ | Option | Type | Default | Description |
171
+ |--------|------|---------|-------------|
172
+ | `sourcePath` | `string` | `'src'` | Directory containing your controllers |
173
+ | `baseUrl` | `string` | auto | Base URL shown in docs and mock server |
174
+ | `path` | `string` | `'/docs'` | Documentation UI endpoint |
175
+ | `enableMock` | `boolean` | `true` | Enable `/scramble-mock/*` proxy endpoints |
176
+ | `autoExportPostman` | `boolean` | `false` | Write Postman collection on startup |
177
+ | `theme` | `'classic' \| 'futuristic'` | `'futuristic'` | UI theme |
178
+ | `primaryColor` | `string` | `'#00f2ff'` | Accent colour (hex) |
179
+ | `useIncrementalScanning` | `boolean` | `false` | Cache AST results between restarts |
180
+ | `enableWatchMode` | `boolean` | `false` | Re-scan on file save |
181
+ | `cacheTtl` | `number` | `86400000` | Cache lifetime in milliseconds |
182
+
183
+ ---
184
+
185
+ ## CLI Reference
186
+
187
+ ```bash
188
+ # Generate OpenAPI JSON
189
+ npx nest-scramble generate src -o openapi.json
190
+
191
+ # Generate Postman collection
192
+ npx nest-scramble generate src --format postman -o collection.json
193
+
194
+ # Generate typed TypeScript client (NEW in v3.0.4)
195
+ npx nest-scramble generate src --format client -o api-client.ts
196
+
197
+ # Custom options
198
+ npx nest-scramble generate src \
199
+ -o my-api.json \
200
+ -t "My API" \
201
+ -v "2.0.0" \
202
+ -b "https://api.example.com"
203
+
204
+ # Check version
205
+ npx nest-scramble --version
206
+ ```
207
+
208
+ **All `generate` options:**
209
+
210
+ | Flag | Description | Default |
211
+ |------|-------------|---------|
212
+ | `-o, --output <file>` | Output file path | `openapi.json` |
213
+ | `-f, --format <type>` | `openapi` \| `postman` \| `client` | `openapi` |
214
+ | `-b, --baseUrl <url>` | API base URL | `http://localhost:3000` |
215
+ | `-t, --title <title>` | API title | `NestJS API` |
216
+ | `-v, --apiVersion <ver>` | API version | `1.0.0` |
217
+
218
+ ---
219
+
220
+ ## Programmatic API
221
+
222
+ ```typescript
223
+ import { ScannerService, OpenApiTransformer, PostmanCollectionGenerator } from 'nest-scramble';
224
+ import * as fs from 'fs';
225
+
226
+ const scanner = new ScannerService();
227
+ const controllers = scanner.scanControllers('src');
228
+
229
+ // OpenAPI spec
230
+ const transformer = new OpenApiTransformer('http://localhost:3000');
231
+ const spec = transformer.transform(controllers, 'My API', '1.0.0', 'http://localhost:3000');
232
+ fs.writeFileSync('openapi.json', JSON.stringify(spec, null, 2));
233
+
234
+ // Postman collection
235
+ const postman = new PostmanCollectionGenerator('http://localhost:3000');
236
+ const collection = postman.generateCollection(controllers);
237
+ fs.writeFileSync('collection.json', JSON.stringify(collection, null, 2));
238
+ ```
239
+
240
+ ---
241
+
242
+ ## Advanced: Incremental Scanning & Watch Mode
243
+
244
+ Enable for **10–100Γ— faster restarts** on large projects.
245
+
246
+ ```typescript
247
+ NestScrambleModule.forRoot({
248
+ useIncrementalScanning: true, // cache AST results to scramble-cache.json
249
+ enableWatchMode: true, // recompute only changed files
250
+ cacheTtl: 86400000, // invalidate after 24h
251
+ })
252
+ ```
253
+
254
+ Cache is invalidated automatically when file content, file size, `tsconfig.json`, or the library version changes.
255
+
256
+ **Add to `.gitignore`:**
257
+
258
+ ```gitignore
259
+ scramble-cache.json
260
+ .scramble-cache.json
261
+ ```
262
+
263
+ **Benchmark (typical project):**
264
+
265
+ | Scenario | Time |
266
+ |---|---|
267
+ | Cold start (no cache) | ~2100 ms |
268
+ | Warm cache (full) | ~50 ms |
269
+ | Single file changed | ~20 ms |
270
+ | DTO changed (5 dependents) | ~100 ms |
271
+
272
+ **Programmatic incremental scanner:**
273
+
274
+ ```typescript
275
+ import { IncrementalScannerService } from 'nest-scramble';
276
+
277
+ const scanner = new IncrementalScannerService({ useCache: true });
278
+ scanner.initialize('src');
279
+ const controllers = scanner.scanControllers('src');
280
+ scanner.cleanup();
281
+ ```
282
+
283
+ ---
284
+
285
+ ## Live Mocking
286
+
287
+ With `enableMock: true` (default), all routes are available under `/scramble-mock/*` with realistic auto-generated data β€” no database, no environment setup needed.
288
+
289
+ ```bash
290
+ GET /scramble-mock/users/1
291
+ # β†’ { "id": 1, "name": "Jane Smith", "email": "jane@example.com", "createdAt": "..." }
292
+ ```
293
+
294
+ Mock values are field-name-aware:
295
+ - `email` β†’ `faker.internet.email()`
296
+ - `name` / `fullName` β†’ `faker.person.fullName()`
297
+ - `createdAt` / `updatedAt` β†’ `faker.date.recent()`
298
+ - `id` β†’ incremental integer
299
+ - Arrays β†’ 2–5 auto-generated items
300
+
301
+ ---
302
+
303
+ ## Documentation UI
304
+
305
+ Visit `/docs` for the interactive dashboard:
306
+
307
+ - **Sidebar navigation** β€” endpoints grouped by controller, collapsible
308
+ - **Three-column layout** β€” Info | Request Editor | Test Panel
309
+ - **Live request sender** β€” test endpoints directly in the browser
310
+ - **Pre-filled mock data** β€” request bodies auto-populated
311
+ - **Theme options** β€” `futuristic` (dark, cyan accents) or `classic` (light)
312
+ - **Search** β€” press `K` to filter endpoints instantly
313
+
314
+ **Custom branding:**
315
+
316
+ ```typescript
317
+ NestScrambleModule.forRoot({
318
+ theme: 'futuristic',
319
+ primaryColor: '#a855f7', // electric purple
320
+ customDomainIcon: '/logo.png',
321
+ apiTitle: 'My Platform API',
322
+ })
323
+ ```
324
+
325
+ **Available endpoints:**
326
+
327
+ | Endpoint | Description |
328
+ |----------|-------------|
329
+ | `GET /docs` | Interactive Scalar UI |
330
+ | `GET /docs-json` | OpenAPI 3.0 JSON spec |
331
+ | `GET /docs/spec` | OpenAPI spec as JSON response |
332
+
333
+ ---
334
+
335
+ ## CI/CD Integration
336
+
337
+ ```yaml
338
+ # .github/workflows/docs.yml
339
+ name: Generate API Docs
340
+ on:
341
+ push:
342
+ branches: [main]
343
+
344
+ jobs:
345
+ generate:
346
+ runs-on: ubuntu-latest
347
+ steps:
348
+ - uses: actions/checkout@v3
349
+ - uses: actions/setup-node@v3
350
+ with: { node-version: '20' }
351
+ - run: npm install
352
+ - run: npx nest-scramble generate src -o openapi.json
353
+ - uses: actions/upload-artifact@v3
354
+ with:
355
+ name: openapi-spec
356
+ path: openapi.json
357
+ ```
358
+
359
+ ---
360
+
361
+ ## Supported Types & Decorators
362
+
363
+ **TypeScript types:**
364
+ - Primitives: `string`, `number`, `boolean`
365
+ - Arrays, nested objects, union types
366
+ - Enums, optional properties
367
+ - Circular references (auto-detected and resolved)
368
+
369
+ **NestJS decorators:**
370
+ - HTTP methods: `@Get`, `@Post`, `@Put`, `@Patch`, `@Delete`
371
+ - Parameters: `@Param`, `@Query`, `@Body`
372
+ - Controllers: `@Controller` (path & group name)
373
+
374
+ ---
375
+
376
+ ## Troubleshooting
377
+
378
+ **No controllers found**
379
+
380
+ Verify `sourcePath` points to the directory containing your `@Controller()` classes. On startup, Nest-Scramble logs the exact path it is scanning.
381
+
382
+ ```typescript
383
+ NestScrambleModule.forRoot({ sourcePath: 'src' })
384
+ ```
385
+
386
+ **`/docs` returns 401 Unauthorized**
387
+
388
+ Your global `AuthGuard` is blocking the docs route. Add an `isPublic` bypass:
389
+
390
+ ```typescript
391
+ @Injectable()
392
+ export class JwtAuthGuard extends AuthGuard('jwt') {
393
+ constructor(private reflector: Reflector) { super(); }
394
+
395
+ canActivate(context: ExecutionContext) {
396
+ const isPublic = this.reflector.getAllAndOverride<boolean>('isPublic', [
397
+ context.getHandler(),
398
+ context.getClass(),
399
+ ]);
400
+ return isPublic ? true : super.canActivate(context);
401
+ }
402
+ }
403
+ ```
404
+
405
+ Nest-Scramble marks its own endpoints with `@SetMetadata('isPublic', true)` automatically.
406
+
407
+ **OpenAPI spec is empty or incomplete**
408
+
409
+ Ensure your controller methods declare an explicit return type:
410
+
411
+ ```typescript
412
+ // βœ… Good
413
+ @Get(':id')
414
+ getUser(@Param('id') id: string): UserDto { ... }
415
+
416
+ // ❌ Missing return type β€” DTO cannot be inferred
417
+ @Get(':id')
418
+ getUser(@Param('id') id: string) { ... }
419
+ ```
420
+
421
+ **TypeScript compilation errors after install**
422
+
423
+ ```bash
424
+ rm -rf node_modules package-lock.json
425
+ npm install
426
+ npm run build
427
+ ```
428
+
429
+ **When reporting an issue, include:** Nest-Scramble version, NestJS version, Node.js version, TypeScript version, startup log output.
430
+
431
+ ---
432
+
433
+ ## Requirements
434
+
435
+ | Requirement | Minimum Version |
436
+ |---|---|
437
+ | Node.js | 18.10.0 |
438
+ | TypeScript | 5.0.0 |
439
+ | NestJS | 10.x or 11.x |
440
+ | reflect-metadata | 0.1.13 (optional) |
441
+
442
+ ### Upgrading from v2.x
443
+
444
+ ```bash
445
+ npm install @nestjs/common@^10 @nestjs/core@^10
446
+ npm install nest-scramble@latest
447
+ ```
448
+
449
+ ---
450
+
451
+ ## Roadmap
452
+
453
+ - [x] OpenAPI 3.0 generation (static AST)
454
+ - [x] Interactive Scalar UI with controller grouping
455
+ - [x] Postman collection export
456
+ - [x] Live mock server
457
+ - [x] Incremental scanning & watch mode
458
+ - [x] Transitive dependency tracking
459
+ - [x] Typed TypeScript client SDK (v3.0.4)
460
+ - [ ] Insomnia / Bruno collection export
461
+ - [ ] `@ScrambleDoc()` lightweight metadata decorator
462
+ - [ ] GraphQL schema support
463
+ - [ ] Plugin API for custom analyzers
464
+
465
+ ---
466
+
467
+ ## Contributing
468
+
469
+ 1. Fork the repository
470
+ 2. Create a feature branch
471
+ 3. Add tests for new behaviour
472
+ 4. Submit a pull request
473
+
474
+ ---
475
+
476
+ ## License
477
+
478
+ MIT β€” see [LICENSE](LICENSE).
479
+
480
+ ## Author
481
+
482
+ **Mohamed Mustafa** β€” [GitHub](https://github.com/Eng-MMustafa) Β· [LinkedIn](https://www.linkedin.com/in/engmohammedmustafa/)