Metadata-Version: 2.4
Name: nyxa
Version: 0.0.1
Summary: Standalone, convention-first backend framework for Python — AI-first
Keywords: framework,asgi,api,backend,ai,mcp
Author: Al-Amin Islam Nerob
Author-email: Al-Amin Islam Nerob <alamin@aincoder.com>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Web Environment
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Classifier: Typing :: Typed
Requires-Dist: pydantic>=2.9
Requires-Dist: orjson>=3.10
Requires-Dist: rich>=13
Requires-Dist: textual>=2.0
Requires-Dist: watchfiles>=1.0
Requires-Dist: nyxa-speedups>=0.0.1
Requires-Dist: nyxa-minijinja>=0.0.1
Requires-Dist: nyxa-forms>=0.0.1
Requires-Dist: nyxa[cli,starlette,blacksheep,granian,uvicorn,msgspec,postgres,mysql] ; extra == 'all'
Requires-Dist: blacksheep>=2.0 ; extra == 'blacksheep'
Requires-Dist: mcp>=1.23 ; extra == 'dev'
Requires-Dist: cryptography>=43 ; extra == 'encrypt'
Requires-Dist: granian[reload]>=2.0 ; extra == 'granian'
Requires-Dist: argon2-cffi>=23 ; extra == 'hash-argon2'
Requires-Dist: bcrypt>=4 ; extra == 'hash-bcrypt'
Requires-Dist: msgspec>=0.19 ; extra == 'msgspec'
Requires-Dist: asyncmy>=0.2 ; extra == 'mysql'
Requires-Dist: asyncpg>=0.30 ; extra == 'postgres'
Requires-Dist: nyxa-server>=0.0.1 ; extra == 'server'
Requires-Dist: starlette>=0.40 ; extra == 'starlette'
Requires-Dist: uvicorn>=0.30 ; extra == 'uvicorn'
Requires-Python: >=3.13
Project-URL: Homepage, https://nyxadev.com
Project-URL: Repository, https://github.com/NyxaDev/Nyxa
Project-URL: Documentation, https://docs.nyxadev.com
Project-URL: Issues, https://github.com/NyxaDev/Nyxa/issues
Provides-Extra: all
Provides-Extra: blacksheep
Provides-Extra: cli
Provides-Extra: dev
Provides-Extra: encrypt
Provides-Extra: granian
Provides-Extra: hash-argon2
Provides-Extra: hash-bcrypt
Provides-Extra: msgspec
Provides-Extra: mysql
Provides-Extra: postgres
Provides-Extra: server
Provides-Extra: speed
Provides-Extra: starlette
Provides-Extra: uvicorn
Description-Content-Type: text/markdown

# nyxa

Standalone, convention-first backend framework for Python — AI-first.

Nyxa is a batteries-included async web framework: a compiled router, a
dependency-injection container, an ORM with migrations and seeding, a
provider/plugin system, an Artisan-style console, and a first-party
package ecosystem (`nyxa-cache`, `nyxa-auth`, `nyxa-ai`, …). Apps are
convention projects — `nyxa.toml`, `config/`, `start/`, `app/` — that
boot through a provider lifecycle and serve over ASGI, RSGI, WSGI, or
the optional native Rust server.

[![PyPI](https://img.shields.io/pypi/v/nyxa)](https://pypi.org/project/nyxa/) [![Python](https://img.shields.io/pypi/pyversions/nyxa)](https://pypi.org/project/nyxa/)

## Features

- **Routing** — ambient `router` proxy replayed into the app at boot:
  `get/post/put/patch/delete`, groups with `prefix()`/`middleware()`,
  `resource()`, `view()`, `redirect()`, `fallback()`, named routes, and
  `ws()` WebSocket endpoints. Routes compile to dispatch plans; plugin
  `route_compilers()` extend the pipeline per route.
- **HTTP surface** — `HttpContext` per request, `Request`/`Response`
  plus `ResponseBuilder`, typed param extractors (`Query`, `Path`,
  `Body`, `Form`, `Files`, `Header`, `Cookie`, `Ip`), `accepts()`/
  `returns()` contract models (pydantic/msgspec), SSE helpers, and a
  full `HttpException` hierarchy with pluggable renderers.
- **Dependency injection** — `Container` with singleton/transient/scoped
  bindings, `Inject` markers, `Scope` control, and `CircularDependencyError`
  /`ResolutionError` diagnostics.
- **Provider lifecycle** — `ServiceProvider` hooks (`register` → `boot`
  → `ready` → `shutdown`) plus plugin surfaces: `commands()`, `config()`,
  `macros()`, `route_compilers()`, `contract_kinds()`, `queue_drivers()`,
  `cache_drivers()`, `adapters()`, `exception_renderers()`. The `Ignitor`
  orchestrates the boot sequence.
- **ORM & database** — `Model` (fillable guards, dirty tracking,
  `SoftDeletes`, relations via `@relation`, class-level
  `update`/`update_or_fail` with `RETURNING`), fluent `QueryBuilder`,
  `DB` facade, `Schema` builder, `Migration`s, `Factory`/`Seeder`, and
  `Connection.lease()`/`Model.using()` for pinning pooled connections.
  Drivers: SQLite built in, Postgres (`asyncpg`) and MySQL (`asyncmy`)
  via extras.
- **Console** — `Command` subclasses with Artisan-style `signature`
  strings (`"mail:send {user} {--f|force}"`), kernel-registered, lazily
  loaded plugin commands.
- **CLI** — `nyxa` entrypoint: `new`, `dev`, `start`, `build`, `deploy`,
  `add`, `make:*` scaffolding (~20 generators), `migrate`/`db:seed`
  family, `queue:*` family, `schedule:*`, `routes`, `doctor`, `repl`,
  `test`, `inspect`, `plugins`, `up`/`down`, `key:generate`, and more.
- **Config & env** — `config/*.py` files expose a `config` dict
  (namespaced by filename) read via `config.get`/`set` with typed
  getters; `define_config()` builds a standalone typed config object
  (env-overriding) for app code to import; `Env` loader with casts;
  `nyxa.toml` manifest sections (`[app]`, `[plugins]`, `[deploy]`).
- **Events, scheduling, queue** — `EventEmitter` (`app.events`),
  `app.schedule` entries (`call`/`job`/`command`/`exec` + `cron()`,
  `daily()`, `hourly()`, …) served by `nyxa schedule:work`, and a
  pluggable queue (`QueueProvider`, driver factories).
- **Testing** — `TestClient` (sync + async) over the in-process app,
  provider/config/route/publish assertions, a `pytest` plugin, and
  `fake()` utilities shipped by first-party packages.
- **OpenAPI & playground** — generated spec and interactive playground,
  gated by `app.debug`/`NYXA_ENV`.
- **Transports & deployment** — ASGI/WSGI/RSGI bridges, `nyxa build`
  frozen-bundle production boots, `nyxa deploy`/`promote`/`rollback`,
  deployment adapters, warmup, and process management (`Process`).

## Install

```bash
pip install nyxa
# or
uv add nyxa
```

The `nyxa` command and the Rust accelerators (`nyxa-speedups` +
`nyxa-minijinja`) are bundled by default — the `cli`/`speed` extras stay
declared for back-compat but add nothing. Accelerator wheels ship for
tier-1 platforms; elsewhere pip builds from the sdist (Rust toolchain)
or use `pip install --no-deps nyxa` plus the deps you want. Useful
extras: `starlette`,
`blacksheep`, `granian`, `uvicorn`, `msgspec`, `postgres`, `mysql`,
`encrypt`, `hash-argon2`, `hash-bcrypt`, `server` (native Rust server),
`all`.

## Usage

### A convention project

```bash
nyxa new my-api && cd my-api
nyxa dev
```

`nyxa new` scaffolds `nyxa.toml` (the manifest), `config/*.py`,
`start/routes.py`, `start/schedule.py`, `app/` (providers, middleware,
commands), and `bootstrap/app.py`. The `Application` resolves its root
from the manifest or an explicit path:

```python
from nyxa import Application

app = Application("path/to/project")  # or Application() inside a project
```

### Routing

Route files declare against the ambient `router` proxy; declarations
replay into the app router at boot:

```python
from nyxa import router

router.get("/health", lambda ctx: {"status": "ok"}).named("health")


async def show(ctx, id: int):  # path param injected by name
    return {"user": id}


def api(r):
    r.get("/users/:id", show)
    r.post("/users", "app.actions.create_user")


router.group(api, prefix="/api").name("api.").middleware(Auth)
```

Path patterns accept `:param`, `:param?`, `{param}`, `{param:int}`,
and `...name`/`...name?` catch-alls; converters and
`.where_ulid()`-style constraints are built in. Groups, `router.controller()`/`resource()` controllers,
`router.view()`, `router.redirect()`, `router.fallback()`,
`router.ws()` WebSockets, and `sse_stream`/`sse_event` server-sent
events are all first-class.

Middleware is a class with a `handle` coroutine — referenced per-route
via `.use(Cls)`/`route.use("name")` or on groups; `scope = "server"`
runs it globally:

```python
class Auth:
    async def handle(self, ctx, next):
        if ctx.request.header("authorization") is None:
            abort(401)
        return await next()
```

### Dependency injection & providers

```python
from nyxa import Inject, ServiceProvider


class Billing:
    def charge(self, cents: int) -> str: ...


class AppProvider(ServiceProvider):
    def register(self) -> None:
        self.app.container.singleton(Billing)


async def invoice(ctx, billing: Billing = Inject(Billing)):
    return {"id": billing.charge(500)}
```

### ORM

```python
from nyxa import Model


class Post(Model):
    fillable = ["title", "body"]


post = await Post.create({"title": "Hello", "body": "..."})
post = await Post.find(1)
posts = await Post.query().where("published", True).order_by("id").all()
await Post.update({"title": "Hi"}, "id", 1)  # class-level UPDATE
```

`nyxa migrate`, `nyxa make:model`, factories, and seeders cover the rest
of the lifecycle; `DB` and `Schema` facades handle raw queries and DDL.

### Console commands

```python
from nyxa import Command


class SendMail(Command):
    signature = "mail:send {user : user id} {--f|force : skip confirm}"

    async def handle(self, app, user: int, force: bool) -> int:
        ...
        return 0
```

Register via a provider's `commands()` or drop the class into
`app/commands/` — discovered lazily by the `nyxa` kernel.

### Testing

```python
from nyxa import Application, TestClient

app = Application("path/to/project")
client = TestClient(app)
response = client.get("/health")
assert response.status_code == 200
```

`nyxa.testing` also ships `assert_provider_registered`,
`assert_config_merged`, `assert_route_registered`, and
`assert_publish_tag` for package tests, plus a pytest plugin.

## Public API

The package surface (`from nyxa import …`, lazily bound) groups as:

- **App & lifecycle** — `Application`, `ServiceProvider`, `Env`,
  `define_config`, `__version__`
- **Container** — `Container`, `Provider`, `Inject`, `Scope`,
  `ContainerError`, `CircularDependencyError`, `ResolutionError`
- **Routing** — `router` (ambient proxy), `Router`, `Route`,
  `RouteError`, `Controller`, `Middleware`, `MiddlewareRegistry`
- **HTTP** — `HttpContext`, `Request`, `Response`, `ResponseBuilder`,
  `get_request`, `use`, `use_response`, `sse_event`, `sse_stream`,
  `Ws`, `WsClosed`; params `Query`, `Path`, `Body`, `Form`, `Files`,
  `Header`, `Cookie`, `Ip`
- **Exceptions** — `HttpException`, `abort`, `ExceptionHandler`,
  `HttpExceptionHandler`, `BadRequestException`, `UnauthorizedException`,
  `ForbiddenException`, `NotFoundException`, `MethodNotAllowedException`,
  `ConflictException`, `ValidationException`, `ModelNotFound`,
  `TooManyRequestsException`, `InternalServerErrorException`,
  `ServiceUnavailableException`, `NyxaError`
- **Database** — `Model`, `DB`, `Schema`, `Collection`, `Query` (param
  extractor — the builder is `Model.query()`), `Migration`, `Factory`,
  `Seeder`, `SoftDeletes`
- **Runtime** — `Command`, `Context`, `Process`, `EventEmitter`,
  `TestClient`

## Configuration

Project config lives in `config/*.py` files exporting a `config` dict
(namespaced by filename — `config/http.py` → `http.*`); `nyxa.toml`
carries `[app]` (`name`, `env`, `debug`, `providers_dir`,
`middleware_dir`, `env_file`, `auto_discover_plugins`), `[plugins]`
(`discover` allowlist), and `[deploy]` (`adapter`). Environment
resolution: `NYXA_ENV` → `[app] env` → `"development"`;
`NYXA_DEBUG`/`[app] debug`/`debug=` for the debug flag.

## License

MIT — see `LICENSE`.
