Metadata-Version: 2.5
Name: nexus-framework
Version: 0.1.0
Summary: Ultimate Simplicity, Uncompromising Power. Next-Gen Python Framework for Web, Data, and AI.
Project-URL: Homepage, https://github.com/nexus-framework/nexus
Project-URL: Documentation, https://nexus-framework.readthedocs.io
Project-URL: Repository, https://github.com/nexus-framework/nexus
Author: Nexus Team
License: MIT
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: pydantic-settings>=2.2.0
Requires-Dist: pydantic>=2.7.0
Requires-Dist: structlog>=24.1.0
Requires-Dist: typing-extensions>=4.10.0
Provides-Extra: ai
Requires-Dist: numpy>=1.26.0; extra == 'ai'
Provides-Extra: all
Requires-Dist: aiosqlite>=0.20.0; extra == 'all'
Requires-Dist: alembic>=1.13.1; extra == 'all'
Requires-Dist: asyncpg>=0.29.0; extra == 'all'
Requires-Dist: bandit>=1.7.8; extra == 'all'
Requires-Dist: httpx>=0.27.0; extra == 'all'
Requires-Dist: mypy>=1.9.0; extra == 'all'
Requires-Dist: numpy>=1.26.0; extra == 'all'
Requires-Dist: polars>=0.20.20; extra == 'all'
Requires-Dist: pyarrow>=15.0.2; extra == 'all'
Requires-Dist: pydantic>=2.7.0; extra == 'all'
Requires-Dist: pytest-asyncio>=0.23.6; extra == 'all'
Requires-Dist: pytest-cov>=5.0.0; extra == 'all'
Requires-Dist: pytest>=8.1.0; extra == 'all'
Requires-Dist: python-multipart>=0.0.9; extra == 'all'
Requires-Dist: ruff>=0.3.7; extra == 'all'
Requires-Dist: sqlalchemy[asyncio]>=2.0.29; extra == 'all'
Requires-Dist: uvicorn[standard]>=0.29.0; extra == 'all'
Provides-Extra: data
Requires-Dist: polars>=0.20.20; extra == 'data'
Requires-Dist: pyarrow>=15.0.2; extra == 'data'
Requires-Dist: pydantic>=2.7.0; extra == 'data'
Provides-Extra: db
Requires-Dist: aiosqlite>=0.20.0; extra == 'db'
Requires-Dist: alembic>=1.13.1; extra == 'db'
Requires-Dist: asyncpg>=0.29.0; extra == 'db'
Requires-Dist: sqlalchemy[asyncio]>=2.0.29; extra == 'db'
Provides-Extra: dev
Requires-Dist: bandit>=1.7.8; extra == 'dev'
Requires-Dist: mypy>=1.9.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23.6; extra == 'dev'
Requires-Dist: pytest-cov>=5.0.0; extra == 'dev'
Requires-Dist: pytest>=8.1.0; extra == 'dev'
Requires-Dist: ruff>=0.3.7; extra == 'dev'
Provides-Extra: web
Requires-Dist: httpx>=0.27.0; extra == 'web'
Requires-Dist: python-multipart>=0.0.9; extra == 'web'
Requires-Dist: uvicorn[standard]>=0.29.0; extra == 'web'
Description-Content-Type: text/markdown

# Nexus

> **Ultimate Simplicity, Uncompromising Power.**

Nexus is a next-generation Python framework built from the ground up to unify **Web**, **Data**, and **AI** applications into a single, cohesive developer experience.

---

## ⚡ The Philosophy

1. **Magical for Beginners, Unrestricted for Experts**
   - 3 levels of API for every feature:
     - **Level 1 (Magical)**: One-liner convention defaults (`from nexus import Nexus; app = Nexus()`).
     - **Level 2 (Configured)**: Explicit dependency injection, custom routers, middleware configuration, settings.
     - **Level 3 (Raw)**: Full low-level control (direct ASGI scope, raw receive/send, and stream control) with zero overhead.
2. **Enterprise Grade from Day Zero**
   - Clean Architecture: strict Separation of Concerns (SoC).
   - `core` has **zero external dependencies**.
   - Fully typed with `mypy --strict` compliance across all source files and test suites.
   - Comprehensive unit test coverage with strict CI threshold (currently **92.35%**).
3. **No Compromises**
   - Built custom where identity matters (e.g., the high-speed **NX Template Engine** — zero external template dependencies).
   - Async-first internally, seamless for synchronous handlers.

---

## 📊 Development Progress & Roadmap Status

| Phase | Domain | Component | Status | Details |
|:---:|:---:|:---|:---:|:---|
| **Phase 0** | **Foundation** | Tooling & Core Architecture | ✅ **100% Complete** | Hatchling, PEP 621, Ruff, Mypy Strict, Pytest-cov, CI GitHub Actions, Base Exceptions, Entities, Protocols, Pydantic Settings, Structlog. |
| **Phase 1.1** | **Web** | ASGI 3.0 Adapter & Lifespan | ✅ **100% Complete** | `build_nexus_request`, `send_nexus_response`, Async Lifespan manager (`on_startup`, `on_shutdown`). |
| **Phase 1.2** | **Web** | Radix-Tree Router | ✅ **100% Complete** | $O(k)$ Radix tree, typed path parameters (`{id:int}`, `{price:float}`, `{id:uuid}`), wildcards (`{path:path}`), 405 Method Not Allowed handling. |
| **Phase 1.3** | **Web** | NexusApp Core Orchestrator | ✅ **100% Complete** | `NexusApp` / `Nexus`, 3-Level API, sync & async handlers auto-execution, auto-response normalization (`dict` $\rightarrow$ JSON, `str` $\rightarrow$ text, `None` $\rightarrow$ 204), error boundary. |
| **Phase 1.4** | **Web** | Request & Response Deepening | ✅ **100% Complete** | `request.json()`, `request.form()`, `request.cookies`, `request.client_ip`, `JSONResponse`, `HTMLResponse`, `PlainTextResponse`, `RedirectResponse`, `FileResponse`, `StreamingResponse`. |
| **Phase 1.5** | **Web** | Built-in Middlewares | ✅ **100% Complete** | `CORSMiddleware`, `SecurityHeadersMiddleware`, `TimingMiddleware` (`X-Response-Time`), `RequestIdMiddleware` (`X-Request-ID`), `GZipMiddleware`. |
| **Phase 1.6** | **Web** | Static File Serving | ✅ **100% Complete** | `StaticFiles`, path traversal security defense, MIME detection, weak ETags & 304 conditional cache, RFC 7233 Range Requests (HTTP 206), `app.mount_static()`. |
| **Phase 1.7** | **Web** | Request Validation & Body Parsing | ✅ **100% Complete** | Automatic Pydantic model validation from body, automatic query parameter coercion, `422 UnprocessableEntityError`, `UploadFile` multipart file streaming. |
| **Phase 1.8** | **Web** | Cookie & Session Management | ✅ **100% Complete** | HMAC-SHA256 cookie signing & tampering defense, `SessionMiddleware`, pluggable `SessionBackend` (`MemorySessionBackend`), `HttpOnly` security. |
| **Phase 1.9** | **Web** | Custom NX Template Engine | ✅ **100% Complete** | Custom `.nx` syntax, pure-Python Lexer, AST Parser, Runtime Compiler, 14 built-in filters, template inheritance (`@extends`, `@block`), includes (`@include`), macros (`@macro`), auto-escaping, LRU AST cache. |
| **Phase 1 Complete** | **Web** | **Web Core Complete & Hardened** | ✅ **100% Complete** | Full Roadmap Exit Criteria fulfilled: `WebSocket` bidirectional pub/sub & `WebSocketGroup`, `RateLimitMiddleware`, `TrustedHostMiddleware`, `Blueprint` modular routing, duplicate route detection, `url_for`, and full end-to-end REST API integration test suite. |
| **Phase 2** | **Core Magic** | **Magic Layer (DI Engine & Introspection)** | ✅ **100% Complete** | Framework-agnostic type-based `DIContainer`, Scopes (`singleton`, `per_request`, `transient`), sub-dependency graph resolution, sync & async provider resolution, fail-fast circular dependency detection (`validate_dependencies`), test provider overrides (`app.override`), dependency tree visualization, and smart cached signature analysis (`introspect_callable`). |
| **Phase 3.1** | **Security** | **JWT Authentication & RBAC Engine** | ✅ **100% Complete** | Pure-Python zero-dependency JWT engine (HS256, timing-safe verification, base64url), access & refresh token pair generation, refresh token rotation, `TokenBlacklist` revocation, `CurrentUser` per-request DI injection, route-level auth checks (`auth=True`, `auth="admin"`, `auth=["admin", "moderator"]`), HTTP 401 Unauthorized & 403 Forbidden enforcement. |
| **Phase 3.2** | **Security** | OAuth2 / Social Auth | ⏩ **Skipped (Deferred)** | OAuth2 protocol adapter and social providers (deferred per user request). |
| **Phase 3.3** | **Security** | **Session-Based Authentication** | ✅ **100% Complete** | `UserSession` dict wrapper with dirty tracking, session ID rotation (Anti-Session Fixation attack defense), one-time flash messages (`flash`, `get_flashes`), `SessionAuthManager` (`login`, `logout`), pluggable backends (`MemorySessionBackend`, `SignedCookieSessionBackend`), signed HTTP-only tamper-proof cookies, and automatic DI injection of `UserSession` & `CurrentUser`. |
| **Phase 3.4** | **Security** | **Permission & Role System (RBAC)** | ✅ **100% Complete** | Granular permissions enforcement, wildcard permissions (`*` and `domain:*`), transitive `RoleHierarchy` inheritance, `PermissionRegistry` mapping, route decorators (`permissions='users:write'`), `@require_roles` / `@require_permissions`, detailed 403 Forbidden responses. |
| **Phase 3.5** | **Security** | **API Key Authentication** | ✅ **100% Complete** | High-performance API key engine (`APIKey`, `APIKeyAuthManager`, `MemoryAPIKeyStore`), secure prefix-dot-secret generation (`nxk_prefix.secret`), SHA-256 hash storage with timing-safe verification, expiration checks, extraction via `X-API-Key` header or `?api_key=` query parameter, seamless integration with route RBAC and DI. |
| **Phase 3.6** | **Security** | **Security Hardening (CSRF, Headers, Rate Limiting)** | ✅ **100% Complete** | Cryptographic Double-Submit Cookie CSRF protection (`CSRFMiddleware`), automatic token issuance on safe requests, constant-time header & form token validation on state-changing requests, path/custom exemptions, `TrustedHostMiddleware`, `RateLimitMiddleware` sliding-window throttling, and enterprise `SecurityHeadersMiddleware`. |
| **Phase 4.1** | **Testing** | **Built-in Testing Utilities (`TestClient`)** | ✅ **100% Complete** | Production-ready synchronous & asynchronous `TestClient`, zero external dependencies, ASGI dispatch, HTTP method wrappers (`get`, `post`, `put`, `delete`, `patch`, `head`), `TestResponse` assertions (`res.json`, `res.text`, `res.raise_for_status()`), persistent cookie jar (`client.cookies`), user simulation context (`client.as_user()`), DI provider overrides (`client.override()`), and synchronous `WebSocketTestSession` (`ws_connect()`, `send_text`, `send_json`, `send_bytes`, `receive_text`, `receive_json`, `receive_bytes`). |
| **Phase 4.2** | **Observability** | **Prometheus, OTel & Health Probes** | ✅ **100% Complete** | Zero external dependencies Prometheus metric collectors (`Counter`, `Gauge`, `Histogram`) and auto-mounted `/metrics` exposition, OpenTelemetry-compatible `Tracer` with W3C `traceparent` propagation, auto-registered `/health` (liveness) & `/ready` (readiness) probes with pluggable async/sync checks (`HealthCheckManager`), and structured JSON access logging with request ID, user ID, duration, and trace IDs. |
| **Phase 4.3** | **Performance** | **Performance Hardening & Caching** | ✅ **100% Complete** | Route-level in-memory response caching (`@app.get('/', cache=60)`), SHA-256 ETag generation and 304 Not Modified validation with `If-None-Match`, connection keep-alive header auto-injection, enforced configurable request body size limits (`max_body_size`, HTTP 413 `PayloadTooLargeError`), and automatic slow request detection with structured warning logs. |
| **Phase 4.4** | **Production** | **Production Deployment Readiness** | ✅ **100% Complete** | `GracefulShutdownManager` in-flight request tracking & draining, SIGTERM/SIGINT signal handling, multi-worker supervisor support (`run_app`), production multi-stage Dockerfile generator (`generate_dockerfile`), and environment variable documentation generator (`generate_env_documentation`). |
| **Phase 4.5** | **Documentation** | **Web Domain Documentation & Cookbooks** | ✅ **100% Complete** | Getting Started 5-minute walkthrough (`docs/getting_started.md`), Flask & FastAPI migration guide (`docs/migration_guide.md`), real-world cookbook recipes (`docs/cookbook.md`), defense-in-depth security guide (`docs/security_guide.md`), and comprehensive API reference (`docs/api_reference.md`). |
| **Phase 4 Complete** | **Milestone** | **Web Domain Complete (`v0.3.0`)** | 🏆 **100% Complete** | Complete Web Domain production hardened and verified across all test suites, type gates, security scanners, and documentation. |
| **Phase 5** | **Database** | **Unified Database & ORM Layer** | ✅ **100% Complete** | 3-Level Architecture: Level 1 Magic DB (`nexus.db`), Level 2 Active-Record Model System (`nexus.db.Model`, `Field`, `Relationship`, soft-delete, chainable queries), Level 3 Raw AsyncSession injection (`nexus.db.AsyncSession`), Async connection pooling (`aiosqlite`, `asyncpg`), read-replica master/replica routing, Alembic migrations automation (`init_migrations`, `generate_migration`, `apply_migrations`). |
| **Phase 6–7** | **Data** | Data Pipelines & Hardening | 📋 **Next in Queue** | Polars/Arrow integration, ETL transforms, automated scheduling. |
| **Phase 8–10** | **AI** | Agentic AI & RAG Runtime | 📋 Planned | LLM abstractions, multi-model providers, `@app.ai` decorator, vector search. |
| **Phase 11–13**| **Ecosystem**| CLI, Plugins & Release | 📋 Planned | `nexus` CLI, extension ecosystem, public release benchmarks. |

---

## 📦 Architecture Layers

```
nexus/
├── nexus/
│   ├── core/           # Pure Python, 0 external dependencies (Protocols, Entities, Exceptions)
│   ├── config/         # pydantic-settings type-safe configuration
│   ├── logging/        # structlog structured logger
│   ├── magic/          # DI and auto-wiring engine
│   ├── web/            # ASGI adapter, Router, Middleware, StaticFiles, Validation, Session, NX Template Engine
│   ├── db/             # Unified Database Layer (Phase 5)
│   ├── data/           # High-speed data processing (Phase 6)
│   └── ai/             # Agentic AI & LLM runtime (Phase 8)
```

---

## 🚀 Quick Example

```python
from nexus import Nexus, NexusRequest, UploadFile
from pydantic import BaseModel, Field

app = Nexus(title="My Nexus App")


class Item(BaseModel):
    name: str
    price: float = Field(gt=0)


# Level 1 Magic Route with automatic Pydantic validation
@app.post("/items")
def create_item(item: Item) -> dict[str, object]:
    return {"status": "created", "item": item.model_dump()}


# Path parameter with automatic type coercion
@app.get("/items/{id:int}")
def get_item(id: int) -> dict[str, object]:
    return {"item_id": id, "name": "Sample Item"}


# Mount static files with path traversal security & range streaming
app.mount_static("/static", "./public")
```

---

## 🧪 Developer Setup & Testing

Requires **Python 3.11+**.

```bash
# Clone the repository
git clone https://github.com/nexus-framework/nexus.git
cd nexus

# Install development & web extras
pip install -e ".[dev,web]"

# Run Ruff linter and formatter checks
ruff check .

# Run strict type checking
mypy nexus tests

# Run full test suite with coverage
pytest --cov=nexus --cov-report=term-missing
```

---

## 🗺️ Detailed Roadmap

For the exhaustive 13-phase development specification, refer to [ROADMAP.md](ROADMAP.md).
