nest-scramble
v5.5.0
Published
A next-generation, decorator-free API documentation engine with Postman generation, live mocking, and typed client SDK generation for NestJS 10 and 11, engineered by Mohamed Mustafa
Downloads
1,347
Maintainers
Readme
🚀 Nest-Scramble
The zero-config API platform for NestJS — living documentation, live consoles for REST + WebSocket + GraphQL, contract testing, drift detection and typed SDKs. All from static TypeScript analysis. You never write a single annotation.
Why Nest-Scramble?
Every other tool makes you decorate your code to death: @ApiProperty(), @ApiResponse(), @ApiTags() on every line. Nest-Scramble reads your TypeScript instead.
| | Swagger / @nestjs/swagger | Nest-Scramble |
|---|---|---|
| Setup | Decorators on every DTO & route | One CLI command |
| Return types | @ApiResponse per status | Inferred — even return { total, items } with no annotation |
| Validation docs | @ApiProperty duplicating rules | Read from class-validator automatically |
| Error responses | Manual @ApiResponse({ status: 404 }) | Extracted from your throw statements |
| WebSockets | Not covered | Scanned + live multi-user console |
| GraphQL | Separate tooling | Scanned + live query console |
| Contract testing | Not covered | Generated scenarios, drift detection, CI diff gate |
| Runtime dependencies | Several | Zero |
Everything below is discovered automatically from your source code. No decorators. No YAML. No config files.
Quick Start — 30 seconds, zero lines of code
npm install nest-scramble
npx nest-scramble init # injects the module into app.module.ts for you
npm run start:dev # open http://localhost:3000/docsThat's it. init writes the one required line into your AppModule:
NestScrambleModule.forRoot({ path: '/docs', sourcePath: 'src' })The scanner walks your TypeScript AST and produces the full documentation, consoles, mock server and OpenAPI 3.0 document — before your app even finishes booting.
🧭 The Postman-style Workspace
A complete, self-contained API client served at /docs — no CDN, no external fonts, works offline.
- Smart request bodies — generated from your DTOs with realistic values:
customerEmailbecomes a real email, nestedshippingAddressanditems[]arrays are fully assembled, and numbers respect your@Min/@Maxconstraints. Hit Send and get a real201 Created.
- Params · Auth · Headers · Body · Docs · Code tabs — path/query params sync live with the URL bar, per-request or global auth (Bearer/API-key/Basic), generated snippets for curl, fetch, axios and more.
- Auth panel — per-request or global Bearer, API-key or Basic credentials.
- File uploads —
multipart/form-dataendpoints get a drag-and-ready file picker plus URL/base64 sources.
- Environments & share links — Postman-style
{{variables}}with a base-URL per environment, and one-click links that encode the entire request in the URL hash. - Request history and Postman collection export, straight from the topbar.
Everything you see was inferred: the enum values, the validation constraints (minLength, minimum, format: email), the 404/409 responses from your throw new NotFoundException(...) statements, and even envelopes returned without a type annotation.
🔌 WebSocket — scanned gateways + a live multi-user console
@WebSocketGateway() and @SubscribeMessage() handlers are scanned exactly like controllers: payload and response DTOs become schemas, served at /docs-ws-json, and the docs grow a live console.
- Connect over Socket.IO or raw WebSocket — the Socket.IO client is served by your own server, no CDN.
- Press Send cold and the console auto-connects, queues your event, and delivers it when the socket opens.
- Everything is visible live: your outgoing event ▲, the server ack ▼, broadcasts from other clients ▼, and system events — each timestamped, with a live event counter.
It's genuinely multi-user. Open two tabs (or send a share link to a teammate): when user A sends chat.send, user B sees the chat.newMessage broadcast instantly — joins, presence updates and message history included:
◈ GraphQL — scanned resolvers + a live query console
@Resolver(), @Query(), @Mutation() and @Subscription() are discovered statically — the resolver doesn't even need to be registered in a module for the docs to see it. Arguments and return types become schemas, an SDL sketch is generated per operation, and the document is served at /docs-graphql-json.
- Operations grouped by resolver in the sidebar with
QRY/MUT/SUBbadges. - The query editor is pre-filled from the response schema, and variables are pre-filled with realistic values derived from the argument types — the query above filtered by
unreadOnly: truewithout the user typing anything. - Response with status and timing, right under the editors.
🧪 Contract Testing — scenarios your API writes for itself
# Generate ready-to-run test scenarios from your source — one file per tag
npx nest-scramble test src --generate -o scenarios/
# Run them against a live server, with contract validation
npx nest-scramble test scenarios/ --spec srcThe generator applies the heuristics a developer would:
- Log in first when a login endpoint with a token-shaped response exists, and thread the captured token through every request as a
Bearerheader — registration is ordered before the login that needs the account. - Create → list → read → update → delete, with the created
idcaptured and reused for the/:idroutes. - Deterministic realistic bodies from your documented schemas.
matchesSpecassertions: every response is validated against the generated document — status, shape, types.
✅ Orders flow
✓ Log in with any /users email and password "SecurePassword123!". (201, 3 ms)
✓ Places an order — the total is computed server-side from the items. (201, 2 ms)
✓ Paginated order list — filter by status, page through results. (200, 2 ms)
✓ Attaches a PDF invoice to the order (multipart upload). (201, 4 ms)
✓ One order with its items and shipping address. (200, 1 ms)
✓ Moves an order through its lifecycle — cancelled orders are final. (200, 2 ms)
✓ Cancels and removes a pending order. (204, 2 ms)Scenario files are plain JSON — chained requests, {{variable}} capture between steps, status/body assertions — commit them and run them in CI with a proper exit code.
🩺 Docs that police themselves
Drift detection (opt-in) — enableDriftDetection: true samples real JSON responses in development and warns, once per finding, when the running API disagrees with the documentation: missing fields, unexpected fields, type mismatches, undocumented routes and statuses.
nest-scramble doctor — a documentation health score (0–100) with the exact fix for every issue: opaque return types, untyped parameters, missing JSDoc, unvalidated body DTOs. --min-score 80 turns it into a CI gate.
nest-scramble diff — compares two versions of your API (spec files or source checkouts) and classifies every change as breaking / warning / safe. --fail-on-breaking fails the pipeline before your consumers find out.
nest-scramble changelog — a consumer-facing Markdown changelog between any two API versions, breaking changes first.
⚙️ CI/CD — the repository doubles as a GitHub Action
# .github/workflows/api-check.yml
name: API Check
on: [pull_request]
jobs:
api-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 } # the diff needs the base branch
- uses: actions/setup-node@v4
with: { node-version: '20', cache: 'npm' }
- run: npm ci
- uses: Eng-MMustafa/nest-scramble@v5
with:
source: src
base-ref: ${{ github.base_ref }}
fail-on-breaking: 'true'
min-score: '70'Three with: lines give every pull request a documentation health gate and breaking-change detection against the base branch. Optional scenario tests against a booted app too — see examples/api-check.workflow.yml.
🎭 Live Mock Server
Every documented route is served with generated data under /scramble-mock — including the routes you just wrote and haven't implemented yet. Front-end teams can build against the contract from day one.
curl http://localhost:3000/scramble-mock/orders📦 Typed Client SDK & Postman export
# TypeScript client with real interfaces generated from your DTOs
npx nest-scramble generate src --format client -o api-client.ts
# Postman collection with example bodies
npx nest-scramble generate src --format postman -o collection.json
# Plain OpenAPI 3.0
npx nest-scramble generate src -o openapi.jsonThe generated client is dependency-free fetch code with one typed method per endpoint — inherited DTO properties, mapped types (PartialType, PickType…), generics (PaginatedDto<UserDto>) and enums all resolve to real TypeScript interfaces.
What the scanner understands — automatically
- Controllers & routes:
@Get/@Post/@Put/@Patch/@Delete/@All/@Options/@Head, object-form@Controller({ path }),app.setGlobalPrefix()viaglobalPrefix,@HttpCode. - Parameters:
@Param,@Query(scalar or DTO),@Body,@Headers,@UploadedFile→multipart/form-data. - Types: DTO classes and interfaces, inheritance chains,
@nestjs/mapped-typeshelpers, instantiated generics, enums, string-literal unions,Promise<T>unwrapping, arrays — and anonymous inferred returns likereturn { total, items }. - Validation:
class-validatordecorators become schema constraints (@IsEmail→format: email,@Min/@Max,@Length,@ArrayMinSize,@IsEnum,@IsOptional…) and the generated example data satisfies them. - Errors:
throw new NotFoundException('...')documents a404with that exact message; all built-inHttpExceptionsubclasses plusHttpStatusenums are recognized. - JSDoc: method comments become operation summaries/descriptions;
@deprecatedflags the operation. - WebSockets:
@WebSocketGatewayoptions (port, namespace),@SubscribeMessagepayloads and return types. - GraphQL:
@Resolver,@Query,@Mutation,@Subscription,@Args— with JSDoc and types.
Both Express and Fastify adapters are verified end-to-end in CI, on NestJS 10 and 11.
Configuration
NestScrambleModule.forRoot({
path: '/docs', // docs URL
sourcePath: 'src', // where your controllers live
apiTitle: 'My API',
apiVersion: '1.0.0',
baseUrl: 'http://localhost:3000',
theme: 'futuristic', // 'classic' (light) | 'futuristic' (dark)
primaryColor: '#0ea5e9',
enableMock: true, // /scramble-mock/* mock server
enableDriftDetection: false, // runtime docs-vs-reality warnings (dev)
globalPrefix: '', // mirrors app.setGlobalPrefix()
useIncrementalScanning: true, // rescan only changed files in watch mode
})| Endpoint | Purpose |
|----------|---------|
| GET /docs | The workspace UI |
| GET /docs-json | OpenAPI 3.0 document |
| GET /docs-ws-json | WebSocket gateways document |
| GET /docs-graphql-json | GraphQL resolvers document |
| GET /scramble-mock/* | Live mock server |
CLI Reference
npx nest-scramble init # inject the module — zero code written by you
npx nest-scramble generate src -o openapi.json # OpenAPI | postman | client via --format
npx nest-scramble doctor src --min-score 80 # docs health gate
npx nest-scramble diff ./main/src ./src --fail-on-breaking
npx nest-scramble changelog ./v1/src ./src --to-label v2.0.0
npx nest-scramble test src --generate -o scenarios/ # write scenarios from the contract
npx nest-scramble test scenarios/ --spec src # run them with contract validationProgrammatic API
import {
ScannerService, OpenApiTransformer, // source → OpenAPI
diffSpecs, formatApiChangelog, // contract diffing
diagnose, // docs health report
generateScenarios, runScenario, // contract testing
scanGateways, buildWsDocument, // WebSocket document
scanResolvers, buildGraphQLDocument, // GraphQL document
} from 'nest-scramble';Every CLI feature is exported as a typed function — build your own tooling on top.
What's New in v5.5.0
- Polished docs UI — redesigned workspace with refined dark/light themes, glassmorphism topbar, animated panels and improved readability.
- Professional REST console — cleaner request bar, syntax-highlighted body editor, formatted responses with copy/download, and per-request auth.
- Live WebSocket console — connect via Socket.IO or raw WebSocket, send events, see acks/broadcasts with timestamps and a live event counter.
- GraphQL query runner — pre-filled operations and variables, one-click execution against your endpoint with timing and status.
- Unified
globalPrefixsupport — OpenAPI, Postman, typed client, mock server and dashboard URLs all respectapp.setGlobalPrefix(). - Smarter optional detection —
param?: stringis correctly marked optional regardless ofstrictNullChecks. - Conditional security schemes —
bearerAuth/apiKeyappear only when routes actually require auth.
Full history in the CHANGELOG.
Requirements
- Node.js ≥ 18.10
- NestJS 10 or 11 (Express or Fastify)
- TypeScript ≥ 5.0 (your project's own compiler is used — it's a peer dependency)
- Zero runtime dependencies — installing nest-scramble adds ~0.8 MB
Roadmap
Shipped: OpenAPI 3.0 from static AST · Postman-style workspace · typed client SDK · Postman export · live mock server · incremental scanning · class-validator constraints · error responses from throw · breaking-change diff · docs doctor · drift detection · declarative scenarios + generation · WebSocket console (multi-user) · GraphQL console · environments & share links · GitHub Action · Express + Fastify, NestJS 10 + 11.
Next: Insomnia/Bruno export · scenario recording from real traffic · GraphQL subscription execution over WS.
Contributing
- Fork the repository
- Create a feature branch
- Add tests for new behaviour (627 tests keep this project honest)
- Submit a pull request
License
Crafted with ❤️ for the NestJS community — if Nest-Scramble saves you time, a ⭐ on GitHub helps others find it.
