Rename djarea to mizan and fix React casing conventions

Rename the package from djarea to mizan across the entire codebase —
Python package, React library, generators, tests, and examples. Fix
JSX/hook casing (MizanProvider, useMizan, etc.) that broke when the
original PascalCase names were lowercased during the rename.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-31 20:01:03 -04:00
parent bf837e598b
commit c866142770
118 changed files with 1778 additions and 1433 deletions

335
README.md
View File

@@ -1,94 +1,84 @@
# DJAREA
# mizan
A modern Django + React Framework for perfectionists with deadlines.
Django + React server functions framework. RPC, not REST.
Write a Pydantic function, add the @client decorator, use configurable **Shape** types for your models.
Djarea generates the entire React client: all your type interfaces, function call hooks, autoatic JWT, and a simple `<DjangoContext/>` to make it all work.
No API routing, no serializers, no REST/CRUD bullshit.
You define Python functions. mizan generates typed React hooks. No API routes, no serializers, no endpoint boilerplate.
```python
@client
def current_user(request) -> UserShape:
return UserShape.query(lambda qs: qs.filter(pk=request.user.pk))[0]
# Django
@client(context='global')
def current_user(request) -> UserOutput:
return UserOutput(email=request.user.email)
```
```tsx
const user: UserShape = useCurrentUser() // typed, cached, SSR-hydrated
// React (generated)
const user = useCurrentUser() // typed, SSR-hydrated, auto-refreshed
```
The **Function** is the API contract. The **Shape** is the query. The hook is the artifact. That's it.
## Packages
Starts with session auth and upgrades to JWT on login. **It just works**.
| Package | Path | Install |
|---------|------|---------|
| `mizan` (Python) | `django/` | `uv add "mizan[channels] @ git+..."` |
| `@rythazhur/mizan` (TypeScript) | `react/` | `npm install @rythazhur/mizan@git+...` |
## What Djarea does
A `@client` function in Django becomes a callable hook in React. The function's type signature orchestrates the entire pipeline for you — input validation, output serialization, TypeScript interfaces, and SQL projection.
```python
class ArticleShape(Shape[Article]):
id: int | None = None
title: str
author: FlatAuthorShape
tags: list[TagShape] = []
```
One Djarea **Shape** does three things simultaneously:
- Defines the Pydantic model for validation and serialization
- Generates a django-readers spec for a lean, field-scoped SQL query
- Produces the TypeScript interface on the React side
Shapes are your codebase's **single source of truth** for backend/frontend data transfer.
## Quick start
## Quick Start
### 1. Django setup
```python
# settings.py
INSTALLED_APPS = [
"djarea",
"mizan",
"myapp",
]
# urls.py
from django.urls import include, path
urlpatterns = [
path("api/djarea/", include("djarea.urls")),
path("api/mizan/", include("mizan.urls")),
]
# asgi.py (for WebSocket support)
from djarea import wrap_asgi
from mizan import wrap_asgi
from django.core.asgi import get_asgi_application
application = wrap_asgi(get_asgi_application())
```
### 2. Define your client functions
### 2. Define server functions
```python
# myapp/clients.py
from djarea.client import client
from djarea.shapes import Shape
# myapp/mizan_clients.py
from django.http import HttpRequest
from mizan.client import client
from mizan.setup.registry import register
from pydantic import BaseModel
class EchoOutput(BaseModel):
message: str
@client
def echo(request, text: str) -> EchoOutput:
def echo(request: HttpRequest, text: str) -> EchoOutput:
return EchoOutput(message=text)
register(echo, "echo")
```
Functions in `clients.py` are discovered automatically — same convention as `models.py`.
### 3. Register in apps.py
### 3. Generate TypeScript
```python
class MyAppConfig(AppConfig):
name = "myapp"
To get your generated React client, set this up in your frontend root:
def ready(self):
import myapp.mizan_clients # noqa: F401
```
```javascript
// django.config.mjs
### 4. Generate TypeScript
```bash
# django.config.mjs
export default {
source: {
django: {
@@ -100,23 +90,27 @@ export default {
}
```
Run this command everytime your client needs updating. You can also throw this it on a file watcher pointed at your backend code:
```bash
npx djarea-generate
npx mizan-generate
```
### 4. Use in React
This produces typed hooks, a typed provider, form hooks with Zod validation, and channel hooks.
### 5. Use in React
```tsx
import { DjangoContext, useEcho, useCurrentUser, DjangoError } from '@/api'
// layout.tsx
import { DjangoContext } from '@/api'
// layout.tsx — one provider, handles everything
export default function Layout({ children }) {
return <DjangoContext>{children}</DjangoContext>
}
```
```tsx
// page.tsx
import { useEcho, useCurrentUser, DjangoError } from '@/api'
function MyComponent() {
const user = useCurrentUser()
const echo = useEcho()
@@ -127,80 +121,91 @@ function MyComponent() {
console.log(result.message) // typed
} catch (e) {
if (e instanceof DjangoError) {
console.log(e.code) // NOT_FOUND, VALIDATION_ERROR, etc.
e.getFieldErrors('email') // field-level errors
console.log(e.code) // NOT_FOUND, VALIDATION_ERROR, etc.
}
}
}
}
```
## Shapes
## Features
Shapes are Djarea's data protocol. A Shape defines exactly which fields to select from the database, validated through Pydantic and projected through django-readers. Different views get different Shapes — same model, different queries.
| Backend | Frontend (generated) | Transport |
|---------|---------------------|-----------|
| `@client` | `useXxx()` | HTTP |
| `@client(context='global')` | `useXxx()` + SSR hydration | HTTP |
| `@client(context='local')` | `useXxx()` with params | HTTP |
| `@client(websocket=True)` | `useXxx()` | WebSocket RPC |
| `@client(auth=True\|'staff'\|callable)` | Auth errors as `DjangoError` | HTTP |
| `mizanFormMixin` | `useXxxForm()` + Zod validation | HTTP |
| `ReactChannel` | `useXxxChannel()` | WebSocket |
| `@compose(...)` | Combined providers | varies |
```python
# Full detail page — joins books with chapters
class AuthorDetailShape(Shape[Author]):
id: int | None = None
name: str
bio: str
books: list[BookShape] = []
## Architecture
# Dropdown menu — two columns, no joins
class FlatAuthorShape(Shape[Author]):
id: int | None = None
name: str
```
React app
└─ <DjangoContext> ← generated provider (includes ChannelProvider)
├─ useCurrentUser() ← generated context hook (SSR-hydrated)
├─ useEcho() ← generated function hook
├─ useContactForm() ← generated form hook (Zod + server validation)
└─ useChatChannel() ← generated channel hook (WebSocket)
├─ HTTP: POST /api/mizan/call/ { fn: "echo", args: { text: "hi" } }
└─ WS: { action: "rpc", fn: "echo", args: { text: "hi" } }
Django executor
├─ Pydantic input validation
├─ Auth check (session, JWT, or custom)
├─ Function execution
└─ Pydantic output serialization
```
```python
# Detail page: SELECT id, name, bio + prefetch books
authors = AuthorDetailShape.query()
The generated `DjangoContext` is the **only provider** needed. It wraps `mizanProvider` + `ChannelProvider` and handles session init, CSRF, context auto-fetching, and WebSocket connection.
# Dropdown: SELECT id, name. That's it.
authors = FlatAuthorShape.query()
## Code Generation
`npx mizan-generate` reads Django schemas (no running server needed) and produces:
| File | Contents |
|------|----------|
| `generated.mizan.ts` | Pydantic model types (via openapi-typescript) |
| `generated.django.tsx` | `DjangoContext` provider + all typed hooks |
| `generated.django.server.ts` | SSR hydration helper (`getDjangoHydration`) |
| `generated.forms.ts` | Form hooks with Zod schemas (`useContactForm`, etc.) |
| `generated.channels.ts` | Channel message types |
| `generated.channels.hooks.tsx` | Channel hooks (`useChatChannel`, etc.) |
| `index.ts` | Consolidated re-exports |
## Error Handling
All errors from server functions are thrown as `DjangoError`:
```tsx
try {
await echo({ text: 'hello' })
} catch (e) {
if (e instanceof DjangoError) {
e.code // 'NOT_FOUND' | 'VALIDATION_ERROR' | 'UNAUTHORIZED' | 'FORBIDDEN' | ...
e.message // Human-readable message
e.details // Field-level validation errors, etc.
e.isAuthError()
e.isValidationError()
e.getFieldErrors('email')
}
}
```
Shapes also support diffing. When the frontend sends state back, the diff system compares incoming data against the current database state and tells you exactly what changed:
```python
@client
def update_articles(request, articles: list[ArticleShape]) -> dict:
for article, diff in ArticleShape.diff_many(articles):
if diff.is_new:
create_article(article)
elif diff.changed:
update_fields(article, diff.changed)
for tag in diff.tags.created:
add_tag(article, tag)
for tag_id in diff.tags.deleted:
remove_tag(article, tag_id)
return {"ok": True}
```
One query fetches all current state. The diff is per-field and per-nested-relation. Your service code only touches what actually changed.
## The `@client` decorator
The decorator controls transport, caching, auth, and SSR behavior:
| Decorator | React hook | What it does |
|-----------|-----------|--------------|
| `@client` | `useEcho()` | HTTP call, returns typed result |
| `@client(context='global')` | `useCurrentUser()` | Fetched once, cached in context, SSR-hydrated |
| `@client(context='local')` | `useArticle({ id })` | Cached per unique params |
| `@client(websocket=True)` | `useSearch()` | Runs over WebSocket instead of HTTP |
| `@client(auth=True)` | — | Requires authentication |
| `@client(auth='staff')` | — | Requires staff status |
| `@client(auth=my_check)` | — | Custom auth callable |
Error codes: `NOT_FOUND`, `VALIDATION_ERROR`, `UNAUTHORIZED`, `FORBIDDEN`, `BAD_REQUEST`, `INTERNAL_ERROR`, `NOT_IMPLEMENTED`.
## Forms
Django forms become typed React hooks with client-side Zod validation:
Django forms get typed React hooks with client-side Zod validation:
```python
class ContactForm(DjareaFormMixin, forms.Form):
djarea = DjareaFormMeta(
# Django
class ContactForm(mizanFormMixin, forms.Form):
mizan = mizanFormMeta(
name="contact",
title="Contact Us",
submit_label="Send",
@@ -216,22 +221,22 @@ class ContactForm(DjareaFormMixin, forms.Form):
```
```tsx
// React (generated)
const form = useContactForm()
form.schema // field metadata, title, submit label
form.schema // { fields: { name: {...}, email: {...} }, title, submit_label }
form.data // { name: '', email: '', message: '' }
form.set('email', v) // typed setter
form.errors // field-level errors (Zod + server)
form.submit() // → { success: true, data: { sent: true } }
```
Zod schemas are generated from the Django form definition. Validation runs client-side first, server-side second. No duplicated validation logic.
## Channels
WebSocket channels with typed messages:
```python
# Django
class ChatChannel(ReactChannel):
class Params(BaseModel):
room: str
@@ -252,6 +257,7 @@ class ChatChannel(ReactChannel):
```
```tsx
// React (generated)
const chat = useChatChannel({ room: 'general' })
chat.status // 'connecting' | 'connected' | 'disconnected'
@@ -259,111 +265,32 @@ chat.messages // ChatDjangoMessage[]
chat.send({ text: 'hello' })
```
## Architecture
```
React app
└─ <DjangoContext> ← generated provider (session, CSRF, WebSocket)
├─ useCurrentUser() ← context hook (SSR-hydrated)
├─ useEcho() ← function hook
├─ useContactForm() ← form hook (Zod + server validation)
└─ useChatChannel() ← channel hook (WebSocket)
├─ HTTP: POST /api/djarea/call/ { fn: "echo", args: { text: "hi" } }
└─ WS: { action: "rpc", fn: "echo", args: { text: "hi" } }
Django executor
├─ Pydantic input validation
├─ Auth check
├─ Function execution
└─ Pydantic output serialization
```
All transport goes through a single endpoint. The generated `DjangoContext` is the only provider. It handles session init, CSRF, context auto-fetching, and WebSocket connection.
## Code generation
`npx djarea-generate` reads Django schemas at build time (no running server) and produces:
| File | Contents |
|------|----------|
| `generated.djarea.ts` | Pydantic model types |
| `generated.django.tsx` | `DjangoContext` provider + typed hooks |
| `generated.django.server.ts` | SSR hydration helper |
| `generated.forms.ts` | Form hooks with Zod schemas |
| `generated.channels.ts` | Channel message types |
| `generated.channels.hooks.tsx` | Channel hooks |
| `index.ts` | Re-exports |
## Error handling
All errors from server functions throw as `DjangoError`:
```tsx
if (e instanceof DjangoError) {
e.code // 'NOT_FOUND' | 'VALIDATION_ERROR' | 'UNAUTHORIZED' | ...
e.message // human-readable
e.details // field-level validation errors
e.isAuthError()
e.isValidationError()
e.getFieldErrors('email')
}
```
## Why RPC instead of REST
REST exposes your database tables as CRUD endpoints and pushes business logic to the frontend. "Submit an application" becomes PATCH one resource, POST another, PUT a third — choreographed by client code.
Djarea keeps business logic on the server. You write functions that do things. The frontend calls them. The server knows what "submit" means. The client doesn't need to.
If you delete the frontend of a REST app, your backend is a database. If you delete the frontend of a Djarea app, your backend still has your entire application logic.
## Packages
| Package | Install |
|---------|---------|
| `djarea` (Python) | `pip install djarea` |
| `@rythazhur/djarea` (TypeScript) | `npm install @rythazhur/djarea` |
For WebSocket support: `pip install "djarea[channels]"`
## Testing
```bash
# Django
cd django && uv run pytest
# Django unit tests
cd django && uv sync --extra dev --extra channels && uv run pytest
# React
# React unit tests
cd react && npm test
# E2E (Playwright, real browser + real backend)
# E2E integration tests (real browser, real backend)
docker compose -f docker-compose.test.yml up -d
cd e2e/harness && npx djarea-generate && npx playwright test
cd e2e/harness && npm install && npx mizan-generate && npx vite --port 5174 &
npx playwright test
# Everything
# All at once
make test-all
```
## Project structure
## Project Structure
```
djarea/
django/ Python package
react/ TypeScript package
example/ Integration test backend
e2e/ Playwright E2E tests
mizan/
django/ Python package (mizan)
react/ TypeScript package (@rythazhur/mizan)
example/ Integration test backend (Docker)
desktop/ PyWebView desktop test app
e2e/ Playwright E2E tests + React harness
Makefile Test orchestration
```
## Disclosure
Djarea was developed with the assistance of IDE AI Assistance and later with Claude Code.
The architecture, design decisions, developer experience standards and technical direction are mine. I've been programming for 16 years and have a lot of opinions!
DX ideas are inspired by the amazing work of these projects and the hardworking folks behind them:
- Django Ninja
- Django Readers
- Django RAPID Architecture
- React
- Next.js