dinou 9.0.3 → 9.2.0

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,503 +1,520 @@
1
- # Dinou
2
-
3
- [![Documentation](https://img.shields.io/badge/docs-dinou.dev-blue?style=flat-square)](https://dinou.dev)
4
- [![Version](https://img.shields.io/badge/version-9.0.3-orange?style=flat-square)](https://www.npmjs.com/package/dinou)
5
- [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg?style=flat-square)](./LICENSE.md)
6
-
7
- **The Ejectable Full-Stack React 19 Framework.**
8
-
9
- Build full-stack web applications with native **React Server Components (RSC)**, progressive streaming SSR, compile-time type-safe routing, **3-Dimensional Caching** (**Horizontal Segmentation**, **Vertical `<DinouCacheSlot>` Micro-ISR**, and **Partial Prerendering / PPR**), **Dual-Mode Vendoring**, and universal multi-platform deployment (**Node.js**, **Bun**, **Deno**, **Cloudflare Workers**, **Netlify**, and **Static Export**) with zero vendor lock-in.
10
-
11
- > 📚 **Full Documentation, Guides & Interactive Tutorials:** **[https://dinou.dev](https://dinou.dev)**
12
- >
13
- > 🤖 **AI Agent Ready:** This `README.md` is intentionally engineered as a **high-density, single-pass technical specification (< 700 lines / < 38 KB)** so AI coding agents can read the entire framework architecture, public APIs, and caching invariants in a single tool call.
14
-
15
- ---
16
-
17
- ## Table of Contents
18
-
19
- 1. [Quick Start & CLI](#1-quick-start--cli)
20
- 2. [Project Structure & File Conventions](#2-project-structure--file-conventions)
21
- 3. [Routing, Parallel Slots & Type-Safe Routing](#3-routing-parallel-slots--type-safe-routing)
22
- 4. [Route Lifecycles (`page_functions.ts` & `layout_functions.ts`)](#4-route-lifecycles-page_functionsts--layout_functionsts)
23
- 5. [The 3-Dimensional Caching & Rendering Engine](#5-the-3-dimensional-caching--rendering-engine)
24
- - [5.1. Dimension 1: Horizontal Segmentation (Layout vs. Page Isolation)](#51-dimension-1-horizontal-segmentation-layout-vs-page-isolation)
25
- - [5.2. Dimension 2: Partial Prerendering (PPR)](#52-dimension-2-partial-prerendering-ppr)
26
- - [5.3. Dimension 3: Vertical Segmentation (`<DinouCacheSlot>` Micro-ISR)](#53-dimension-3-vertical-segmentation-dinoucacheslot-micro-isr)
27
- - [5.4. The Triple Synergy (HS + PPR + `<DinouCacheSlot>`)](#54-the-triple-synergy-hs--ppr--dinoucacheslot)
28
- 6. [Client Navigation, Router Cache & Hooks](#6-client-navigation-router-cache--hooks)
29
- 7. [Server Functions (`"use server"`), Context & The Dinou Pattern](#7-server-functions-use-server-context--the-dinou-pattern)
30
- 8. [Configuration (`dinou.config.mjs`), Middleware (`onRequest`) & Storage Adapters](#8-configuration-dinouconfigmjs-middleware-onrequest--storage-adapters)
31
- 9. [Styling, Assets, Environment Variables & Aliases](#9-styling-assets-environment-variables--aliases)
32
- 10. [Bundlers, Deployment Targets, Dual-Mode Vendoring & Eject](#10-bundlers-deployment-targets-dual-mode-vendoring--eject)
33
- 11. [Complete Public Exports Cheat-Sheet](#11-complete-public-exports-cheat-sheet)
34
-
35
- ---
36
-
37
- ## 1. Quick Start & CLI
38
-
39
- ### Prerequisites
40
- - **Node.js 20.6.0+** (Required)
41
- - **Bun 1.1+** / **Deno 2.0+** / **Wrangler** (Optional, for target-specific builds/compiles)
42
-
43
- ### Create a New App
44
- ```bash
45
- npx create-dinou@latest my-app
46
- cd my-app
47
- npm run dev
48
- ```
49
-
50
- ### Core CLI Commands (`npx dinou <command>`)
51
-
52
- All commands accept the global **`-u` / `--unvendorized`** flag (or `DINOU_UNVENDORIZED=true`) to resolve internal toolchain dependencies from standard `node_modules` instead of Dinou's pre-bundled `dinou/compiled/` vendor bundles.
53
-
54
- | Command | Bundler Variants (`:esbuild` default, `:rollup`, `:webpack`) | Description |
55
- | :--- | :--- | :--- |
56
- | `dinou dev` | `dev:esbuild`, `dev:rollup`, `dev:webpack` | Start development server with HMR & Fast Refresh. |
57
- | `dinou build` / `build:node` | `build:node:{esbuild,rollup,webpack}` | Build production bundle and pre-render static routes for Node.js. |
58
- | `dinou start` / `start:node` | `start:node:{esbuild,rollup,webpack}` | Start production Node.js server. |
59
- | `dinou build:cloudflare` | `build:cloudflare:{esbuild,rollup,webpack}` | Build for Cloudflare Workers (`workerd` + KV). |
60
- | `dinou build:bun` / `start:bun` | `build:bun:{esbuild,rollup,webpack}` | Build and start for Bun runtime (`build:bun:pure` runs 100% under Bun). |
61
- | `dinou build:deno` / `start:deno` | `build:deno:{esbuild,rollup,webpack}` | Build and seed Deno KV for Deno / Deno Deploy. |
62
- | `dinou build:{node,bun,deno}:compile` | `...compile:{linux,linux_arm,mac,win}:{bundler}` | Compile standalone single-file native executable (`dist/`). |
63
- | `dinou export-static` | `export-static:{esbuild,rollup,webpack}` | Export pure static site to `dist/` (HTML + RSC payloads + assets). |
64
- | `dinou eject` | — | Eject full Dinou compiler & runtime into `./dinou` at project root. |
65
-
66
- ---
67
-
68
- ## 2. Project Structure & File Conventions
69
-
70
- Routes live directly inside **`src/`** (not `src/app/`). A directory becomes a route if it contains a `page.{tsx,jsx,ts,js}` file.
71
-
72
- ```text
73
- my-app/
74
- ├── public/ # Static files served at "/" (copied to .dinou/dist3)
75
- ├── src/
76
- │ ├── layout.tsx # Root Layout (wraps<html>, <head>, <body>)
77
- │ ├── layout_functions.ts # Root Layout server lifecycle (getProps, revalidate, getCacheTags, ppr)
78
- │ ├── page.tsx # Home route ("/")
79
- │ ├── page_functions.ts # Home route server lifecycle (getProps, revalidate, getCacheTags, ppr)
80
- │ ├── error.tsx # Root 500 error boundary page
81
- │ ├── not_found.tsx # Root 404 page
82
- │ └── blog/
83
- │ └── [slug]/
84
- │ ├── page.tsx # Dynamic route ("/blog/:slug")
85
- │ └── page_functions.ts
86
- ├── dinou.config.mjs # Optional framework config, plugins, storage & middleware
87
- ├── dinou.setup.ts # Optional early setup/polyfill file injected into all environments
88
- └── tsconfig.json # TypeScript config (includes ".dinou/types/routes.d.ts")
89
- ```
90
-
91
- ### Special Route Files (`src/**/`)
92
-
93
- | File | Scope | Role & Behavior |
94
- | :--- | :--- | :--- |
95
- | `page.{tsx,jsx,ts,js}` | Universal (`async` RSC or `"use client"`) | Primary UI for the URL segment. Receives `{ params }` plus all props returned by `getProps`. |
96
- | `layout.{tsx,jsx,ts,js}` | Universal (`async` RSC or `"use client"`) | Persistent wrapper around child routes. Does **not** remount on child SPA navigation. Receives `{ children, params, ...parallelSlots }` plus props from `layout_functions.ts` `getProps`. |
97
- | `page_functions.{ts,js}` | Server-Only | Exports `getProps`, `getStaticPaths`, `validateParams`, `allowISG`, `revalidate`, `getCacheTags`, `ppr`. |
98
- | `layout_functions.{ts,js}` | Server-Only | Exports `getProps`, `validateParams`, `revalidate`, `getCacheTags`, `ppr` for the layout segment independently of child pages. |
99
- | `error.{tsx,jsx,ts,js}` | Universal | Renders when an unhandled error occurs in the segment or its descendants (bubbles up to closest ancestor `error.*`). Receives `{ error, params }`. |
100
- | `not_found.{tsx,jsx,ts,js}` | Universal | Renders on unmatched URLs or when `validateParams` returns `false` / `allowISG = false` (bubbles up to closest ancestor `not_found.*`). Receives `{ params }` plus props from `getProps` if present. |
101
-
102
- ### Layout Control Flags (Empty 0-Byte Files)
103
- Create an empty file (no extension) inside any route folder to alter layout inheritance:
104
- - `no_layout`: Renders `page.tsx` bare without **any** ancestor layouts.
105
- - `reset_layout`: Discards ancestor layouts above this folder; this folder's `layout.tsx` becomes the new root layout for this subtree.
106
- - `no_layout_error`: Renders `error.tsx` without ancestor layouts.
107
- - `no_layout_not_found`: Renders `not_found.tsx` without ancestor layouts.
108
-
109
- ---
110
-
111
- ## 3. Routing, Parallel Slots & Type-Safe Routing
112
-
113
- ### Folder Naming Patterns
114
-
115
- | Pattern | Example Path | URL Matched | Inferred `params` Type |
116
- | :--- | :--- | :--- | :--- |
117
- | `about` | `src/about/page.tsx` | `/about` | `{}` |
118
- | `[slug]` | `src/blog/[slug]/page.tsx` | `/blog/hello` | `{ slug: string }` |
119
- | `[[slug]]` | `src/item/[[slug]]/page.tsx` | `/item`, `/item/42` | `{ slug?: string }` |
120
- | `[...slug]` | `src/docs/[...slug]/page.tsx` | `/docs/a/b/c` (1+ segments) | `{ slug: string[] }` |
121
- | `[[...slug]]` | `src/shop/[[...slug]]/page.tsx` | `/shop`, `/shop/a/b` (0+ segments) | `{ slug?: string[] }` |
122
- | `(group)` | `src/(marketing)/pricing/page.tsx` | `/pricing` | Organization group (omitted from URL). |
123
- | `_escaped` | `src/_legacy/page.tsx` | *(Ignored)* | Folders starting with `_` are ignored by the route scanner. |
124
- | `@slot` | `src/dashboard/@analytics/page.tsx` | `/dashboard` | **Parallel Route Slot:** injected as prop `analytics` into `src/dashboard/layout.tsx`. Isolated error boundary per slot. |
125
-
126
- > **Strict No-Gap Rule:** Every intermediate route segment that has a `layout.tsx` or dynamic parameter along a branch should be properly structured; however, pass-through folders without `page.tsx` (e.g. `src/api/v1/users/page.tsx`) are supported and resolved in memory.
127
-
128
- ### Compile-Time Type-Safe Routing (`.dinou/types/routes.d.ts`)
129
- Dinou automatically generates `.dinou/types/routes.d.ts` during `dev` and `build`. Include it in `tsconfig.json`:
130
- ```json
131
- {
132
- "include": ["src", ".dinou/types/routes.d.ts"]
133
- }
134
- ```
135
- Use the exported types from `"dinou"`:
136
- ```tsx
137
- import type { PageProps, LayoutProps, ErrorProps, PageFunctions, LayoutFunctions } from "dinou";
138
-
139
- // src/blog/[slug]/page_functions.ts
140
- export const getProps: PageFunctions<"/blog/[slug]">["getProps"] = async (params) => {
141
- // params is typed as { slug: string }
142
- return { title: `Post ${params.slug}` };
143
- };
144
-
145
- // src/blog/[slug]/page.tsx
146
- export default async function BlogPage({
147
- params,
148
- title,
149
- }: PageProps<"/blog/[slug]"> & { title: string }) {
150
- return <h1>{title} ({params.slug})</h1>;
151
- }
152
- ```
153
-
154
- ---
155
-
156
- ## 4. Route Lifecycles (`page_functions.ts` & `layout_functions.ts`)
157
-
158
- Both `page_functions.ts` and `layout_functions.ts` share the `RouteSegmentConfig` contract:
159
-
160
- | Export | Signature / Type | Default | Behavior |
161
- | :--- | :--- | :--- | :--- |
162
- | `revalidate` | `number \| false \| (() => number \| false \| Promise<...>)` | `false` | **`false`**: Permanent SSG/ISG until on-demand invalidation.<br>**`0` (or `< 1`)**: Dynamic SSR on every request.<br>**`>= 1`**: Time-based ISR (TTL in seconds; stale-while-revalidate in background). |
163
- | `ppr` | `boolean \| (() => boolean \| Promise<boolean>)` | `false` (or global `dinou.config.mjs`) | Enables **Partial Prerendering** for this segment (static shell + streaming `<Suspense>` holes). |
164
- | `getCacheTags` | `string[] \| ((params) => string[] \| Promise<string[]>)` | `[]` | Tags associated with this page or layout segment for surgical invalidation via `revalidateTag(tag)`. |
165
- | `getProps` | `(params) => TProps \| Promise<TProps>` | `{}` | Server-only data loader. Returned object properties are spread directly as props onto `page.tsx` (and `not_found.tsx`) or `layout.tsx`. |
166
- | `getStaticPaths` | `StaticPathItem[] \| (() => StaticPathsResult)` | `[]` | *(Pages/Layouts)* Pre-generates paths at build time. Supports returning strings (`["a", "b"]`), numbers, string arrays for catch-all (`[["a", "b"]]`), or param objects (`[{ slug: "a" }]`). |
167
- | `validateParams` | `(params) => boolean \| Promise<boolean>` | `() => true` | Perimeter guard evaluated **before** `getProps` or rendering. Returning `false` halts execution and renders `not_found.tsx` with HTTP 404. In `layout_functions.ts`, protects the entire child subtree. |
168
- | `allowISG` | `boolean \| (() => boolean \| Promise<boolean>)` | `true` | When `true`, dynamic paths not returned by `getStaticPaths` are generated on-demand on first visit and cached (ISG). When `false`, unknown paths immediately return HTTP 404. |
169
-
170
- ---
171
-
172
- ## 5. The 3-Dimensional Caching & Rendering Engine
173
-
174
- Dinou v9.0.3 features three orthogonal caching and rendering dimensions that work standalone or in **Triple Synergy**:
175
-
176
- ```
177
- ┌─────────────────────────────────────────────────────────────────────────┐
178
- │ 1. HORIZONTAL SEGMENTATION (HS) │
179
- │ Independent Layout Cache (layout.rsc) !== Page Cache (page.rsc) │
180
- ├─────────────────────────────────────────────────────────────────────────┤
181
- │ 2. PARTIAL PRERENDERING (PPR) │
182
- │ Instant Static Shell (shell.html) + Streaming <Suspense> Holes │
183
- ├─────────────────────────────────────────────────────────────────────────┤
184
- │ 3. VERTICAL SEGMENTATION (<DinouCacheSlot> Micro-ISR) │
185
- │ Sub-tree RSC payload cached & refreshed independently by ID or Tag │
186
- └─────────────────────────────────────────────────────────────────────────┘
187
- ```
188
-
189
- ### 5.1. Dimension 1: Horizontal Segmentation (Layout vs. Page Isolation)
190
-
191
- In Dinou, **`layout.tsx` (`layout_functions.ts`)** and **`page.tsx` (`page_functions.ts`)** have **completely independent cache lifecycles** and storage artifacts:
192
- - Layout artifacts: `layout.rsc` + `layout.metadata.json` (with its own `revalidate` TTL and `getCacheTags`).
193
- - Page artifacts: `page.rsc` + `index.html` + `metadata.json` (with its own `revalidate` TTL and `getCacheTags`).
194
-
195
- #### Asymmetric Combinations Supported:
196
- 1. **Static Layout (`revalidate = false`) + Dynamic Page (`revalidate = 0`)**: On every request or SPA navigation, the layout is served from cache (`layout.rsc`) without re-executing `layout.tsx`, while `page.tsx` renders dynamically.
197
- 2. **Dynamic Layout (`revalidate = 0`) + Static Page (`revalidate = false`)**: The page payload (`page.rsc`) stays cached while the layout evaluates dynamically per request.
198
- 3. **Independent ISR Timers**: e.g., Layout `revalidate = 3600` (1h) + Page `revalidate = 10` (10s).
199
-
200
- #### Surgical Revalidation & Zero Hydration Mismatch (`Lazy HTML Re-Composition`):
201
- When you invalidate **only** a layout (`revalidateLayout("/dashboard")` or `revalidateTag("layout-tag")`):
202
- - Dinou regenerates **only** `layout.rsc` without re-executing child `page.tsx` components (preserving all cached child `page.rsc` payloads).
203
- - Whenever a hard request (`GET /dashboard/settings`) or F5 reload arrives and detects that the ancestor `layout.rsc` is newer than the child's cached `index.html`, Dinou **lazily re-composes `index.html`** from the fresh `layout.rsc` + the existing cached `page.rsc` (and synchronizes the hydration RSC payload). This guarantees **zero React hydration mismatch** on hard reloads without cascading page re-renders.
204
-
205
- ---
206
-
207
- ### 5.2. Dimension 2: Partial Prerendering (PPR)
208
-
209
- Enable PPR globally in `dinou.config.mjs` (`ppr: true`) or per-route/layout in `page_functions.ts` / `layout_functions.ts` (`export const ppr = true`).
210
-
211
- #### How Automatic Static Bailout & Streaming Holes Work:
212
- 1. **Static Shell Extraction:** During build (or background revalidation), Dinou pre-renders the static shell (`shell.html` and static RSC shell).
213
- 2. **Request-Scope Bailout Triggers:** Any component wrapped inside a `<Suspense fallback={...}>` boundary that reads request-specific data:
214
- - `getContext()` (reading `req.cookies`, `req.headers`, `req.query`, or mutating `res`)
215
- - `useSearchParams()`
216
- automatically bails out during static shell generation. Its `<Suspense>` fallback is baked into `shell.html`.
217
- 3. **Single-Request Streaming:** On incoming HTTP requests, Dinou flushes the cached `shell.html` immediately and concurrently streams the personalized `<Suspense>` holes over the same HTTP response stream.
218
- 4. **Dynamic Hole Collapse Optimization:** If an `async` component inside `<Suspense>` only awaits slow I/O (e.g., a database query) and **never** calls `getContext()` or `useSearchParams()`, Dinou resolves it at build time and collapses it directly into the static shell (`shell.html`) for instant delivery.
219
-
220
- ---
221
-
222
- ### 5.3. Dimension 3: Vertical Segmentation (`<DinouCacheSlot>` Micro-ISR)
223
-
224
- `<DinouCacheSlot>` (imported from `"dinou/server"`) caches an arbitrary React Server Component subtree independently from its host page or layout.
225
-
226
- ```tsx
227
- import { DinouCacheSlot } from "dinou/server";
228
-
229
- export default async function DashboardPage() {
230
- return (
231
- <main>
232
- {/* Cached for 30s and tagged with "Gold-Price" and "market" */}
233
- <DinouCacheSlot id="gold-ticker" revalidate={30} tags={["Gold-Price", "market"]}>
234
- {() => <LiveGoldTicker />}
235
- </DinouCacheSlot>
236
- </main>
237
- );
238
- }
239
- ```
240
-
241
- #### Key Capabilities & Rules of `<DinouCacheSlot>`:
242
- - **Props:**
243
- - `id?: string`: Explicit slot identifier (auto-derived if omitted, though explicit `id` is recommended for live client `refreshSlot`).
244
- - `tag?: string` / `tags?: string[]`: Semantic cache tags for `revalidateTag(tag)` and `refreshSlot(tag)`.
245
- - `revalidate?: number`: Slot TTL in seconds (`0` = never cached; `> 0` = time-based Micro-ISR; omitted = cached until invalidated).
246
- - `children`: Either JSX (`<AsyncServerComponent />`) or a lazy factory function (`() => <AsyncServerComponent />`).
247
- - **Works in Both Dynamic & Static Hosts:**
248
- - Inside a **Dynamic Page (`revalidate = 0`)**: The host page re-renders on every request, while `<DinouCacheSlot>` subtrees hit cache without re-running their DB queries.
249
- - Inside a **Static Page (`revalidate = false`)**: When a slot is invalidated via `revalidateTag(tag)` or its `revalidate` TTL expires, Dinou updates the slot and lazily re-composes the static host page so subsequent reloads serve the updated slot HTML without changing the rest of the static page.
250
- - **Nested `<DinouCacheSlot>` Isolation:** A `<DinouCacheSlot>` can contain inner `<DinouCacheSlot>` components. Invalidating or refreshing the **inner** slot re-evaluates **only** the inner slot while the outer slot stays cached.
251
- - **Client Components & Server Action Props Inside Slots:** `<DinouCacheSlot>` subtrees can render `"use client"` components and pass `"use server"` functions as props; Dinou preserves client reference manifests and action bindings across slot serialization.
252
- - **Stampede Protection:** Concurrent cache-miss requests for the same slot key are deduplicated in-flight onto a single render promise.
253
- - **Live Client-Side Surgical Refresh (`refreshSlot`):**
254
- Call `refreshSlot(idOrTag, { fresh?: boolean })` (from `"dinou"`) or `useRouter().refreshSlot(idOrTag, { fresh?: boolean })` from any Client Component:
255
- - Targets a specific slot by **`id`**, by **`tag`**, or **all mounted slots via wildcard `"*"`**.
256
- - `{ fresh: true }` forces a cache bypass and updates the server slot cache; `{ fresh: false }` (default) serves from cache unless expired/invalidated.
257
- - **100% State Preservation:** Updating a slot in the browser surgically patches only that slot's Virtual DOM subtree; sibling Client Components in the layout, page, or other slots keep 100% of their local React state (`useState`, inputs, counters).
258
-
259
- ---
260
-
261
- ### 5.4. The Triple Synergy (HS + PPR + `<DinouCacheSlot>`)
262
-
263
- All three dimensions compose simultaneously in the same route tree:
264
- - **Layout Level:** Can be Static (HS), Dynamic (HS), or PPR (`layout_functions.ts` with `ppr = true`), and can contain `<DinouCacheSlot>` components both in the **Layout Static Shell** and inside **Layout Dynamic `<Suspense>` Holes**.
265
- - **Page Level:** Can be Static (HS), Dynamic (HS), or PPR (`page_functions.ts` with `ppr = true`), and can contain `<DinouCacheSlot>` components both in the **Page Static Shell** and inside **Page Dynamic `<Suspense>` Holes** (including nested slots and slots wrapped around or inside `<Suspense>`).
266
- - **Synergy Invalidation Invariants:**
267
- 1. Invalidating a `<DinouCacheSlot>` inside a **PPR Dynamic Hole** (`revalidateTag("hole-slot")`) updates only that slot on the next request without regenerating `shell.html` or sibling slots.
268
- 2. Invalidating a `<DinouCacheSlot>` inside a **PPR Static Shell** (`revalidateTag("shell-slot")`) purges the slot and automatically enqueues background regeneration of the host `shell.html` (and `layout.rsc` if the slot lives in the layout shell), while leaving sibling cached slots untouched.
269
- 3. Calling `refreshSlot(idOrTag, { fresh: true })` (or `refreshSlot("*", { fresh: true })`) from the browser updates slots live in the DOM across the Layout Shell, Layout Holes, Page Shell, and Page Holes simultaneously, **and** enqueues background regeneration of any affected static shells so a subsequent F5 hard reload serves the exact updated slot tokens with **zero hydration mismatch**.
270
-
271
- ---
272
-
273
- ## 6. Client Navigation, Router Cache & Hooks
274
-
275
- Import navigation primitives from `"dinou"`:
276
-
277
- ```tsx
278
- "use client";
279
- import {
280
- Link,
281
- ClientRedirect,
282
- redirect,
283
- useRouter,
284
- usePathname,
285
- useSearchParams,
286
- useNavigationLoading,
287
- refreshSlot,
288
- } from "dinou";
289
- ```
290
-
291
- | Primitive | Scope | Signature / Props | Key Behavior |
292
- | :--- | :--- | :--- | :--- |
293
- | `<Link>` | Universal | `href` (or `to`), `prefetch?: boolean` (`true`), `fresh?: boolean` (`false`) | Performs soft SPA navigation. Prefetches RSC payload on hover when `prefetch={true}`. Pass `fresh` to bypass the client-side router cache (`pageCache`). Supports relative paths (`"sub"`, `"../other"`). |
294
- | `useRouter()` | Client | `{ push, replace, back, forward, refresh, refreshSlot }` | `push(href, { fresh? })`, `replace(href, { fresh? })`, `refresh({ layout?: boolean })` (re-fetches current page RSC payload; pass `{ layout: true }` to also re-fetch layouts), `refreshSlot(idOrTag, { fresh? })`. |
295
- | `usePathname()` | Universal | `() => string` | Returns current URL pathname (e.g. `"/blog/hello"`). Works in both Server Components and Client Components. |
296
- | `useSearchParams()` | Universal | `() => URLSearchParams` | Returns read-only `URLSearchParams`. Works in both Server Components (triggers dynamic/PPR bailout) and Client Components. |
297
- | `useNavigationLoading()` | Client | `() => boolean` | Returns `true` while a client-side route transition is in flight. |
298
- | `redirect(url)` | Universal | `(destination: string) => ReactNode` | In `getProps` or Server Functions/Components before headers flush: sends real HTTP `307 Temporary Redirect` (or `X-Dinou-Redirect` in RPC). If streaming has already started or on client: renders `<ClientRedirect to={destination} />`. |
299
- | `<ClientRedirect>` | Client | `<ClientRedirect to="/login" />` | Triggers immediate client-side `replace` navigation upon mount. |
300
- | `refreshSlot()` | Client | `(slotIdOrTag: string, opts?: { fresh?: boolean }) => void` | Standalone helper (identical to `useRouter().refreshSlot`) to refresh one or all (`"*"`) `<DinouCacheSlot>` instances live in the browser. |
301
-
302
- ---
303
-
304
- ## 7. Server Functions (`"use server"`), Context & The Dinou Pattern
305
-
306
- ### Server Functions & Actions (`"use server"`)
307
- Any file or async function marked with `"use server"` runs exclusively on the server and can be imported directly into Client Components (`"use client"`):
308
- - Supports standard React 19 form actions (`<form action={myAction}>`, `useActionState`, `useFormStatus`, `useOptimistic`) and direct RPC calls (`await myAction(arg1, arg2)`), including `FormData` uploads.
309
- - **Security:** Bundlers automatically strip the implementation from the client bundle and replace it with a Flight RPC proxy (`/____server_function____`).
310
-
311
- ### Reading & Mutating Request Context (`getContext()`)
312
- Call `getContext()` (from `"dinou"`) synchronously inside any Server Component, `getProps`, `validateParams`, or `"use server"` function:
313
- ```ts
314
- import { getContext } from "dinou";
315
-
316
- export async function updateThemeAction(theme: string) {
317
- "use server";
318
- const ctx = getContext();
319
- if (!ctx) return; // undefined during static build time if no request is active
320
-
321
- const currentCookie = ctx.req.cookies["theme"];
322
- const userAgent = ctx.req.headers["user-agent"];
323
-
324
- ctx.res.cookie("theme", theme, { path: "/", httpOnly: true, maxAge: 86400 });
325
- ctx.res.setHeader("X-Custom-Header", "updated");
326
- }
327
- ```
328
- - `ctx.req`: `{ query, cookies, headers, path, method, env, ctx }`
329
- - `ctx.res`: `{ cookie(name, val, opts?), clearCookie(name, opts?), setHeader(name, val), status(code), redirect(statusOrUrl, url?) }`
330
- - `ctx.env` / `ctx.ctx`: Platform bindings (e.g., Cloudflare Workers `env.DB`, `env.KV`, `ctx.waitUntil`).
331
-
332
- ### The Dinou Pattern (Streaming Server Components from Server Functions)
333
- In Dinou, a `"use server"` function can return **rendered JSX (including async Server Components and `<Suspense>` trees)** directly to a Client Component over React Flight RPC:
334
- ```tsx
335
- // src/actions.tsx
336
- "use server";
337
- export async function searchProductsView(query: string) {
338
- const items = await db.products.search(query);
339
- return (
340
- <ul>
341
- {items.map((item) => <li key={item.id}>{item.name}</li>)}
342
- </ul>
343
- );
344
- }
345
- ```
346
- ```tsx
347
- // src/search-client.tsx
348
- "use client";
349
- import { useState, Suspense } from "react";
350
- import { searchProductsView } from "./actions";
351
-
352
- export function SearchBox() {
353
- const [viewPromise, setViewPromise] = useState<Promise<React.ReactNode> | null>(null);
354
- return (
355
- <div>
356
- <button onClick={() => setViewPromise(searchProductsView("shoes"))}>Search</button>
357
- <Suspense fallback={<p>Loading...</p>}>{viewPromise}</Suspense>
358
- </div>
359
- );
360
- }
361
- ```
362
-
363
- ### On-Demand Server Cache Invalidation (`"dinou/server"`)
364
- ```ts
365
- import {
366
- revalidateTag,
367
- revalidatePath,
368
- revalidatePage,
369
- revalidateLayout,
370
- } from "dinou/server";
371
-
372
- await revalidateTag("products"); // Purges all pages, layouts & DinouCacheSlots with tag "products"
373
- await revalidatePath("/blog/hello"); // Purges both layout (if any) and page at "/blog/hello"
374
- await revalidatePage("/dashboard/stats"); // Purges only page.rsc + index.html (preserves cached layout.rsc)
375
- await revalidateLayout("/dashboard"); // Purges only layout.rsc (preserves child page.rsc payloads; lazily re-composes index.html)
376
- ```
377
-
378
- ---
379
-
380
- ## 8. Configuration (`dinou.config.mjs`), Middleware (`onRequest`) & Storage Adapters
381
-
382
- Create `dinou.config.mjs` (or `.js` / `.ts`) at the project root using `defineConfig` from `"dinou"` (or `"dinou/config"`):
383
-
384
- ```js
385
- import { defineConfig } from "dinou";
386
- import { RedisStorage } from "dinou/server";
387
-
388
- export default defineConfig({
389
- reactStrictMode: true, // Default: true
390
- ppr: false, // Global PPR default (can be overridden per route/layout)
391
- setupFiles: ["./dinou.setup.ts"],
392
- // storage: new RedisStorage(redisClient, "dinou:"),
393
- plugins: [
394
- {
395
- name: "auth-and-webhooks",
396
- // 1. Universal Web Standards HTTP Middleware & Webhook Handler
397
- async onRequest(request, context) {
398
- const url = new URL(request.url);
399
-
400
- // Short-circuit webhooks or API endpoints (<2ms, bypasses React)
401
- if (url.pathname === "/api/health") {
402
- return Response.json({ ok: true });
403
- }
404
-
405
- // Mutate context for downstream Server Components & Server Functions
406
- context.user = { id: request.headers.get("x-user-id") ?? "guest" };
407
- },
408
-
409
- // 2. Optional Node.js HTTP Server Hook (WebSockets, raw Node middleware)
410
- configureServer({ server, isDev, use }) {
411
- use((req, res, next) => {
412
- res.setHeader("X-Powered-By", "Dinou");
413
- next();
414
- });
415
- },
416
- },
417
- ],
418
- });
419
- ```
420
-
421
- ### Pluggable ISR Storage Adapters (`"dinou/server"`)
422
- - `FileSystemStorage(baseDir?)`: Default on Node.js & Bun (persists to `.dinou/cache`).
423
- - `CloudflareKVStorage(kvNamespace)`: Default on Cloudflare Workers when `env.DINOU_CACHE` KV binding is present.
424
- - `DenoKVStorage(kvInstance?)`: Default on Deno / Deno Deploy.
425
- - `MemoryStorage()`: In-memory fallback when no persistent store is configured.
426
- - `RedisStorage(redisClient, prefix?)`: Distributed cluster cache for multi-instance deployments.
427
- - Custom adapter: extend `StorageAdapter` (`get(key)`, `set(key, content, metadata?)`, `has(key)`, `delete(key)`) or call `setStorageAdapter(adapter)`.
428
-
429
- ---
430
-
431
- ## 9. Styling, Assets, Environment Variables & Aliases
432
-
433
- - **Global CSS & Tailwind CSS v4:** Import `./styles.css` in `src/layout.tsx` (compiled automatically via PostCSS + `@tailwindcss/postcss` + `autoprefixer` into `/styles.css`) and link it in `<head>`:
434
- ```tsx
435
- import "./styles.css";
436
- // Inside RootLayout <head>:
437
- <link rel="stylesheet" href="/styles.css" precedence="default" />
438
- ```
439
- - **CSS Modules:** Any `*.module.css` file returns scoped class names (`import styles from "./card.module.css"`).
440
- - **Media & Asset Imports:** Import 21+ formats (`.png`, `.jpg`, `.jpeg`, `.gif`, `.svg`, `.webp`, `.avif`, `.ico`, `.mp4`, `.webm`, `.ogg`, `.mp3`, `.wav`, `.flac`, `.aac`, `.woff`, `.woff2`, `.eot`, `.ttf`, `.otf`, `.pdf`) directly in Server or Client Components to receive their hashed public URL string. Add `/// <reference types="dinou/env" />` in `src/env.d.ts` for TypeScript support.
441
- - **Public Directory (`public/`):** Files in `public/` are copied verbatim to `.dinou/dist3/` and served at the root URL (`/favicon.ico`, `/robots.txt`).
442
- - **Path Aliases (`tsconfig.json`):** Configure `compilerOptions.paths` (e.g. `"@/*": ["./src/*"]`) in `tsconfig.json`. Dinou automatically resolves aliases across TypeScript/JSX, CSS `@import`, and asset imports in all three bundlers (esbuild, Rollup, Webpack).
443
- - **Environment Variables:** `.env` files are loaded on the server via `dotenv`. For security, `process.env` secrets are **server-only** and never bundled into client code; pass public values explicitly as props from Server Components to Client Components.
444
-
445
- ---
446
-
447
- ## 10. Bundlers, Deployment Targets, Dual-Mode Vendoring & Eject
448
-
449
- ### Multi-Bundler Parity
450
- Dinou provides 100% feature parity across three bundlers:
451
- - **esbuild** (Default): Fastest builds and HMR.
452
- - **Rollup** (`:rollup`): Clean ES module output.
453
- - **Webpack** (`:webpack`): Includes `babel-plugin-react-compiler` automatic memoization in production builds.
454
-
455
- ### Deployment Targets
456
- - **Node.js:** `npm run build && npm start` (entry: `dinou/adapters/node`).
457
- - **Cloudflare Workers:** `npm run build:cloudflare && npx wrangler deploy` (generates `.dinou/cloudflare/worker.js`).
458
- - **Bun:** `npm run build:bun && npm run start:bun` (or `npm run build:bun:compile` for standalone binary).
459
- - **Deno:** `npm run build:deno && npm run start:deno` (or `npm run build:deno:compile` for standalone binary).
460
- - **Netlify:** Uses `dinou/adapters/netlify` serverless entry.
461
- - **Static Export:** `npm run export-static` outputs a self-contained static site into `dist/`.
462
-
463
- ### Dual-Mode Vendoring (`--unvendorized` / `-u`)
464
- By default, Dinou runs in **Vendorized Mode**, resolving Babel, PostCSS, Tailwind, Rollup/Webpack plugins, `ws`, `chokidar`, etc. from pre-compiled zero-install bundles in `dinou/compiled/` via `package.json` `#imports`.
465
- Pass `-u` / `--unvendorized` (e.g. `npx dinou dev -u` or `DINOU_UNVENDORIZED=true`) to resolve those packages from standard `node_modules` via Node's `--conditions=unvendorized`.
466
-
467
- ### Ejecting (`npx dinou eject`)
468
- Running `npx dinou eject` copies the complete Dinou framework into `./dinou` at your project root and rewrites `package.json` scripts and imports to use `./dinou/index.js`, `./dinou/server.js`, and `./dinou/cli.js`, giving you 100% ownership of the compiler and runtime.
469
-
470
- ---
471
-
472
- ## 11. Complete Public Exports Cheat-Sheet
473
-
474
- ### Package `"dinou"`
475
- | Export | Kind | Description |
476
- | :--- | :--- | :--- |
477
- | `Link` | Component | Client SPA navigation `<Link href="..." prefetch? fresh? />` |
478
- | `ClientRedirect` | Component | Client mount redirect `<ClientRedirect to="..." />` |
479
- | `redirect` | Function | Universal redirect `redirect("/path")` (HTTP 307 or SPA redirect) |
480
- | `useRouter` | Hook (Client) | `{ push, replace, back, forward, refresh, refreshSlot }` |
481
- | `usePathname` | Hook (Universal) | Current URL pathname string |
482
- | `useSearchParams` | Hook (Universal) | Current `URLSearchParams` |
483
- | `useNavigationLoading` | Hook (Client) | Boolean pending navigation state |
484
- | `refreshSlot` | Function (Client) | `refreshSlot(slotIdOrTag, { fresh?: boolean })` (supports `"*"` wildcard) |
485
- | `getContext` | Function (Server) | Returns `{ req, res, env, ctx, ...custom }` from `AsyncLocalStorage` |
486
- | `defineConfig` | Function | Type-safe helper for `dinou.config.mjs` |
487
- | `PageProps<T>`, `LayoutProps<T>`, `ErrorProps<T>`, `PageFunctions<T, P>`, `LayoutFunctions<T, P>`, `RouteParams<T>`, `DinouRoute`, `DinouRoutePattern` | TypeScript Types | Compile-time type-safe routing helpers |
488
-
489
- ### Package `"dinou/server"`
490
- | Export | Kind | Description |
491
- | :--- | :--- | :--- |
492
- | `DinouCacheSlot` | Server Component | `<DinouCacheSlot id? tag? tags? revalidate?>{children}</DinouCacheSlot>` |
493
- | `revalidateTag` | Function (Server) | `await revalidateTag(tag)` — invalidates tagged pages, layouts & slots |
494
- | `revalidatePath` | Function (Server) | `await revalidatePath(path)` — invalidates route layout + page |
495
- | `revalidatePage` | Function (Server) | `await revalidatePage(path)` — invalidates only `page.rsc` + `index.html` |
496
- | `revalidateLayout` | Function (Server) | `await revalidateLayout(path)` — invalidates only `layout.rsc` (lazy HTML re-composition) |
497
- | `StorageAdapter`, `FileSystemStorage`, `CloudflareKVStorage`, `DenoKVStorage`, `MemoryStorage`, `RedisStorage`, `getStorageAdapter`, `setStorageAdapter` | Storage API | Pluggable cache storage engines for SSG / ISR / PPR / `DinouCacheSlot` |
498
-
499
- ---
500
-
501
- ## License
502
-
503
- [MIT](./LICENSE.md)
1
+ # Dinou
2
+
3
+ [![Documentation](https://img.shields.io/badge/docs-dinou.dev-blue?style=flat-square)](https://dinou.dev)
4
+ [![Version](https://img.shields.io/badge/version-9.2.0-orange?style=flat-square)](https://www.npmjs.com/package/dinou)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg?style=flat-square)](./LICENSE.md)
6
+
7
+ **The Ejectable Full-Stack React 19 Framework.**
8
+
9
+ Build full-stack web applications with native **React Server Components (RSC)**, progressive streaming SSR, compile-time type-safe routing, **3-Dimensional Caching** (**Horizontal Segmentation**, **Vertical `<DinouCacheSlot>` Micro-ISR**, and **Temporal Segmentation / Partial Prerendering (PPR)**), **Dual-Mode Vendoring**, and universal multi-platform deployment (**Node.js**, **Bun**, **Deno**, **Cloudflare Workers**, **Netlify**, and **Static Export**) with zero vendor lock-in.
10
+
11
+ > 📚 **Full Documentation, Guides & Interactive Tutorials:** **[https://dinou.dev](https://dinou.dev)**
12
+ >
13
+ > 🤖 **AI Agent Ready:** This `README.md` is intentionally engineered as a **high-density, single-pass technical specification (< 700 lines / < 38 KB)** so AI coding agents can read the entire framework architecture, public APIs, and caching invariants in a single tool call.
14
+
15
+ ---
16
+
17
+ ## Table of Contents
18
+
19
+ 1. [Quick Start & CLI](#1-quick-start--cli)
20
+ 2. [Project Structure & File Conventions](#2-project-structure--file-conventions)
21
+ 3. [Routing, Parallel Slots & Type-Safe Routing](#3-routing-parallel-slots--type-safe-routing)
22
+ 4. [Route Lifecycles (`page_functions.ts` & `layout_functions.ts`)](#4-route-lifecycles-page_functionsts--layout_functionsts)
23
+ 5. [The 3-Dimensional Caching & Rendering Engine](#5-the-3-dimensional-caching--rendering-engine)
24
+ - [5.1. Dimension 1: Horizontal Segmentation (Layout vs. Page Isolation)](#51-dimension-1-horizontal-segmentation-layout-vs-page-isolation)
25
+ - [5.2. Dimension 2: Vertical Segmentation (`<DinouCacheSlot>` Micro-ISR)](#52-dimension-2-vertical-segmentation-dinoucacheslot-micro-isr)
26
+ - [5.3. Dimension 3: Temporal Segmentation — Partial Prerendering (PPR)](#53-dimension-3-temporal-segmentation--partial-prerendering-ppr)
27
+ - [5.4. The Triple Synergy (Horizontal + Vertical + Temporal / PPR)](#54-the-triple-synergy-horizontal--vertical--temporal--ppr)
28
+ 6. [Client Navigation, Router Cache & Hooks](#6-client-navigation-router-cache--hooks)
29
+ 7. [Server Functions (`"use server"`), Context & The Dinou Pattern](#7-server-functions-use-server-context--the-dinou-pattern)
30
+ 8. [Configuration (`dinou.config.mjs`), Middleware (`onRequest`) & Storage Adapters](#8-configuration-dinouconfigmjs-middleware-onrequest--storage-adapters)
31
+ 9. [Styling, Assets, Environment Variables & Aliases](#9-styling-assets-environment-variables--aliases)
32
+ 10. [Bundlers, Deployment Targets, Dual-Mode Vendoring & Eject](#10-bundlers-deployment-targets-dual-mode-vendoring--eject)
33
+ 11. [Complete Public Exports Cheat-Sheet](#11-complete-public-exports-cheat-sheet)
34
+
35
+ ---
36
+
37
+ ## 1. Quick Start & CLI
38
+
39
+ ### Prerequisites
40
+ - **Node.js 20.6.0+** (Required)
41
+ - **Bun 1.1+** / **Deno 2.0+** / **Wrangler** (Optional, for target-specific builds/compiles)
42
+
43
+ ### Create a New App
44
+ ```bash
45
+ npx create-dinou@latest my-app
46
+ cd my-app
47
+ npm run dev
48
+ ```
49
+
50
+ ### Core CLI Commands (`npx dinou <command>`)
51
+
52
+ All commands accept the global **`-u` / `--unvendorized`** flag (or `DINOU_UNVENDORIZED=true`) to resolve internal toolchain dependencies from standard `node_modules` instead of Dinou's pre-bundled `dinou/compiled/` vendor bundles.
53
+
54
+ | Command | Bundler Variants (`:esbuild` default, `:rollup`, `:webpack`) | Description |
55
+ | :--- | :--- | :--- |
56
+ | `dinou dev` | `dev:esbuild`, `dev:rollup`, `dev:webpack` | Start development server with HMR & Fast Refresh. |
57
+ | `dinou build` / `build:node` | `build:node:{esbuild,rollup,webpack}` | Build production bundle and pre-render static routes for Node.js. |
58
+ | `dinou start` / `start:node` | `start:node:{esbuild,rollup,webpack}` | Start production Node.js server. |
59
+ | `dinou build:cloudflare` | `build:cloudflare:{esbuild,rollup,webpack}` | Build for Cloudflare Workers (`workerd` + KV). |
60
+ | `dinou build:bun` / `start:bun` | `build:bun:{esbuild,rollup,webpack}` | Build and start for Bun runtime (`build:bun:pure` runs 100% under Bun). |
61
+ | `dinou build:deno` / `start:deno` | `build:deno:{esbuild,rollup,webpack}` | Build and seed Deno KV for Deno / Deno Deploy. |
62
+ | `dinou build:{node,bun,deno}:compile` | `...compile:{linux,linux_arm,mac,win}:{bundler}` | Compile standalone single-file native executable (`dist/`). |
63
+ | `dinou export-static` | `export-static:{esbuild,rollup,webpack}` | Export pure static site to `dist/` (HTML + RSC payloads + assets). |
64
+ | `dinou eject` | — | Eject full Dinou compiler & runtime into `./dinou` at project root. |
65
+
66
+ ---
67
+
68
+ ## 2. Project Structure & File Conventions
69
+
70
+ Routes live directly inside **`src/`** (not `src/app/`). A directory becomes a route if it contains a `page.{tsx,jsx,ts,js}` file.
71
+
72
+ ```text
73
+ my-app/
74
+ ├── public/ # Static files served at "/" (copied to .dinou/dist3)
75
+ ├── src/
76
+ │ ├── layout.tsx # Root Layout (wraps<html>, <head>, <body>)
77
+ │ ├── layout_functions.ts # Root Layout server lifecycle (getProps, revalidate, getCacheTags, ppr)
78
+ │ ├── page.tsx # Home route ("/")
79
+ │ ├── page_functions.ts # Home route server lifecycle (getProps, revalidate, getCacheTags, ppr)
80
+ │ ├── error.tsx # Root 500 error boundary page
81
+ │ ├── not_found.tsx # Root 404 page
82
+ │ └── blog/
83
+ │ └── [slug]/
84
+ │ ├── page.tsx # Dynamic route ("/blog/:slug")
85
+ │ └── page_functions.ts
86
+ ├── dinou.config.mjs # Optional framework config, plugins, storage & middleware
87
+ ├── dinou.setup.ts # Optional early setup/polyfill file injected into all environments
88
+ └── tsconfig.json # TypeScript config (includes ".dinou/types/routes.d.ts")
89
+ ```
90
+
91
+ ### Special Route Files (`src/**/`)
92
+
93
+ | File | Scope | Role & Behavior |
94
+ | :--- | :--- | :--- |
95
+ | `page.{tsx,jsx,ts,js}` | Universal (`async` RSC or `"use client"`) | Primary UI for the URL segment. Receives `{ params }` plus all props returned by `getProps`. |
96
+ | `layout.{tsx,jsx,ts,js}` | Universal (`async` RSC or `"use client"`) | Persistent wrapper around child routes. Does **not** remount on child SPA navigation. Receives `{ children, params, ...parallelSlots }` plus props from `layout_functions.ts` `getProps`. |
97
+ | `page_functions.{ts,js}` | Server-Only | Exports `getProps`, `getStaticPaths`, `validateParams`, `allowISG`, `revalidate`, `getCacheTags`, `ppr`. |
98
+ | `layout_functions.{ts,js}` | Server-Only | Exports `getProps`, `validateParams`, `revalidate`, `getCacheTags`, `ppr` for the layout segment independently of child pages. |
99
+ | `error.{tsx,jsx,ts,js}` | Universal | Renders when an unhandled error occurs in the segment or its descendants (bubbles up to closest ancestor `error.*`). Receives `{ error, params }`. |
100
+ | `not_found.{tsx,jsx,ts,js}` | Universal | Renders on unmatched URLs or when `validateParams` returns `false` / `allowISG = false` (bubbles up to closest ancestor `not_found.*`). Receives `{ params }` plus props from `getProps` if present. |
101
+
102
+ ### Layout Control Flags (Empty 0-Byte Files)
103
+ Create an empty file (no extension) inside any route folder to alter layout inheritance:
104
+ - `no_layout`: Renders `page.tsx` bare without **any** ancestor layouts.
105
+ - `reset_layout`: Discards ancestor layouts above this folder; this folder's `layout.tsx` becomes the new root layout for this subtree.
106
+ - `no_layout_error`: Renders `error.tsx` without ancestor layouts.
107
+ - `no_layout_not_found`: Renders `not_found.tsx` without ancestor layouts.
108
+
109
+ ---
110
+
111
+ ## 3. Routing, Parallel Slots & Type-Safe Routing
112
+
113
+ ### Folder Naming Patterns
114
+
115
+ | Pattern | Example Path | URL Matched | Inferred `params` Type |
116
+ | :--- | :--- | :--- | :--- |
117
+ | `about` | `src/about/page.tsx` | `/about` | `{}` |
118
+ | `[slug]` | `src/blog/[slug]/page.tsx` | `/blog/hello` | `{ slug: string }` |
119
+ | `[[slug]]` | `src/item/[[slug]]/page.tsx` | `/item`, `/item/42` | `{ slug?: string }` |
120
+ | `[...slug]` | `src/docs/[...slug]/page.tsx` | `/docs/a/b/c` (1+ segments) | `{ slug: string[] }` |
121
+ | `[[...slug]]` | `src/shop/[[...slug]]/page.tsx` | `/shop`, `/shop/a/b` (0+ segments) | `{ slug?: string[] }` |
122
+ | `(group)` | `src/(marketing)/pricing/page.tsx` | `/pricing` | Organization group (omitted from URL). |
123
+ | `_escaped` | `src/_legacy/page.tsx` | *(Ignored)* | Folders starting with `_` are ignored by the route scanner. |
124
+ | `@slot` | `src/dashboard/@analytics/page.tsx` | `/dashboard` | **Parallel Route Slot:** injected as prop `analytics` into `src/dashboard/layout.tsx`. Isolated error boundary per slot. |
125
+
126
+ > **Strict No-Gap Rule:** Every intermediate route segment that has a `layout.tsx` or dynamic parameter along a branch should be properly structured; however, pass-through folders without `page.tsx` (e.g. `src/api/v1/users/page.tsx`) are supported and resolved in memory.
127
+
128
+ ### Compile-Time Type-Safe Routing (`.dinou/types/routes.d.ts`)
129
+ Dinou automatically generates `.dinou/types/routes.d.ts` during `dev` and `build`. Include it in `tsconfig.json`:
130
+ ```json
131
+ {
132
+ "include": ["src", ".dinou/types/routes.d.ts"]
133
+ }
134
+ ```
135
+ Use the exported types from `"dinou"`:
136
+ ```tsx
137
+ import type { PageProps, LayoutProps, ErrorProps, PageFunctions, LayoutFunctions } from "dinou";
138
+
139
+ // src/blog/[slug]/page_functions.ts
140
+ export const getProps: PageFunctions<"/blog/[slug]">["getProps"] = async (params) => {
141
+ // params is typed as { slug: string }
142
+ return { title: `Post ${params.slug}` };
143
+ };
144
+
145
+ // src/blog/[slug]/page.tsx
146
+ export default async function BlogPage({
147
+ params,
148
+ title,
149
+ }: PageProps<"/blog/[slug]"> & { title: string }) {
150
+ return <h1>{title} ({params.slug})</h1>;
151
+ }
152
+ ```
153
+
154
+ ---
155
+
156
+ ## 4. Route Lifecycles (`page_functions.ts` & `layout_functions.ts`)
157
+
158
+ Both `page_functions.ts` and `layout_functions.ts` share the `RouteSegmentConfig` contract:
159
+
160
+ | Export | Signature / Type | Default | Behavior |
161
+ | :--- | :--- | :--- | :--- |
162
+ | `revalidate` | `number \| false \| (() => number \| false \| Promise<...>)` | `false` | **`false`**: Permanent SSG/ISG until on-demand invalidation.<br>**`0` (or `< 1`)**: Dynamic SSR on every request.<br>**`>= 1`**: Time-based ISR (TTL in seconds; stale-while-revalidate in background). |
163
+ | `ppr` | `boolean \| (() => boolean \| Promise<boolean>)` | `false` (or global `dinou.config.mjs`) | Enables **Partial Prerendering** for this segment (static shell + streaming `<Suspense>` holes). |
164
+ | `getCacheTags` | `string[] \| ((params) => string[] \| Promise<string[]>)` | `[]` | Tags associated with this page or layout segment for surgical invalidation via `revalidateTag(tag)`. |
165
+ | `getProps` | `(params) => TProps \| Promise<TProps>` | `{}` | Server-only data loader. Returned object properties are spread directly as props onto `page.tsx` (and `not_found.tsx`) or `layout.tsx`. |
166
+ | `getStaticPaths` | `StaticPathItem[] \| (() => StaticPathsResult)` | `[]` | *(Pages/Layouts)* Pre-generates paths at build time. Supports returning strings (`["a", "b"]`), numbers, string arrays for catch-all (`[["a", "b"]]`), or param objects (`[{ slug: "a" }]`). |
167
+ | `validateParams` | `(params) => boolean \| Promise<boolean>` | `() => true` | Perimeter guard evaluated **before** `getProps` or rendering. Returning `false` halts execution and renders `not_found.tsx` with HTTP 404. In `layout_functions.ts`, protects the entire child subtree. |
168
+ | `allowISG` | `boolean \| (() => boolean \| Promise<boolean>)` | `true` | When `true`, dynamic paths not returned by `getStaticPaths` are generated on-demand on first visit and cached (ISG). When `false`, unknown paths immediately return HTTP 404. |
169
+
170
+ ---
171
+
172
+ ## 5. The 3-Dimensional Caching & Rendering Engine
173
+
174
+ Dinou features three orthogonal caching and rendering dimensions—**Horizontal**, **Vertical**, and **Temporal**—that work standalone or in **Triple Synergy**:
175
+
176
+ ```
177
+ ┌─────────────────────────────────────────────────────────────────────────┐
178
+ │ 1. HORIZONTAL SEGMENTATION (HS) │
179
+ │ Independent Layout Cache (layout.rsc) !== Page Cache (page.rsc) │
180
+ ├─────────────────────────────────────────────────────────────────────────┤
181
+ │ 2. VERTICAL SEGMENTATION (<DinouCacheSlot> Micro-ISR) │
182
+ │ Sub-tree RSC payload cached & refreshed independently by ID or Tag │
183
+ ├─────────────────────────────────────────────────────────────────────────┤
184
+ │ 3. TEMPORAL SEGMENTATION — PARTIAL PRERENDERING (PPR) │
185
+ │ Instant Static Shell (shell.html) + Streaming <Suspense> Holes │
186
+ └─────────────────────────────────────────────────────────────────────────┘
187
+ ```
188
+
189
+ ### 5.1. Dimension 1: Horizontal Segmentation (Layout vs. Page Isolation)
190
+
191
+ In Dinou, **`layout.tsx` (`layout_functions.ts`)** and **`page.tsx` (`page_functions.ts`)** have **completely independent cache lifecycles** and storage artifacts:
192
+ - Layout artifacts: `layout.rsc` + `layout.metadata.json` (with its own `revalidate` TTL and `getCacheTags`).
193
+ - Page artifacts: `page.rsc` + `index.html` + `metadata.json` (with its own `revalidate` TTL and `getCacheTags`).
194
+
195
+ #### Asymmetric Combinations Supported:
196
+ 1. **Static Layout (`revalidate = false`) + Dynamic Page (`revalidate = 0`)**: On every request or SPA navigation, the layout is served from cache (`layout.rsc`) without re-executing `layout.tsx`, while `page.tsx` renders dynamically.
197
+ 2. **Dynamic Layout (`revalidate = 0`) + Static Page (`revalidate = false`)**: The page payload (`page.rsc`) stays cached while the layout evaluates dynamically per request.
198
+ 3. **Independent ISR Timers**: e.g., Layout `revalidate = 3600` (1h) + Page `revalidate = 10` (10s).
199
+
200
+ #### Surgical Revalidation & Zero Hydration Mismatch (`Lazy HTML Re-Composition`):
201
+ When you invalidate **only** a layout (`revalidateLayout("/dashboard")` or `revalidateTag("layout-tag")`):
202
+ - Dinou regenerates **only** `layout.rsc` without re-executing child `page.tsx` components (preserving all cached child `page.rsc` payloads).
203
+ - Whenever a hard request (`GET /dashboard/settings`) or F5 reload arrives and detects that the ancestor `layout.rsc` is newer than the child's cached `index.html`, Dinou **lazily re-composes `index.html`** from the fresh `layout.rsc` + the existing cached `page.rsc` (and synchronizes the hydration RSC payload). This guarantees **zero React hydration mismatch** on hard reloads without cascading page re-renders.
204
+
205
+ ---
206
+
207
+ ### 5.2. Dimension 2: Vertical Segmentation (`<DinouCacheSlot>` Micro-ISR)
208
+
209
+ While Horizontal Segmentation isolates route segments (`layout.tsx` vs. `page.tsx`), **Vertical Segmentation** isolates individual component subtrees *inside* a layout or page. `<DinouCacheSlot>` (imported from `"dinou/server"`) caches an arbitrary React Server Component subtree independently from its host page or layout.
210
+
211
+ ```tsx
212
+ import { DinouCacheSlot } from "dinou/server";
213
+
214
+ export default async function DashboardPage() {
215
+ return (
216
+ <main>
217
+ {/* Cached for 30s and tagged with "Gold-Price" and "market" */}
218
+ <DinouCacheSlot id="gold-ticker" revalidate={30} tags={["Gold-Price", "market"]}>
219
+ {() => <LiveGoldTicker />}
220
+ </DinouCacheSlot>
221
+ </main>
222
+ );
223
+ }
224
+ ```
225
+
226
+ #### Key Capabilities & Rules of `<DinouCacheSlot>`:
227
+ - **Props:**
228
+ - `id?: string`: Explicit slot identifier (auto-derived if omitted, though explicit `id` is recommended for live client `refreshSlot`).
229
+ - `tag?: string` / `tags?: string[]`: Semantic cache tags for `revalidateTag(tag)` and `refreshSlot(tag)`.
230
+ - `revalidate?: number`: Slot TTL in seconds (`0` = never cached; `> 0` = time-based Micro-ISR; omitted = cached until invalidated).
231
+ - `children`: Either JSX (`<AsyncServerComponent />`) or a lazy factory function (`() => <AsyncServerComponent />`).
232
+ - **Works in Both Dynamic & Static Hosts:**
233
+ - Inside a **Dynamic Page (`revalidate = 0`)**: The host page re-renders on every request, while `<DinouCacheSlot>` subtrees hit cache without re-running their DB queries.
234
+ - Inside a **Static Page (`revalidate = false` or `ppr = true` Static Shell)**: When a slot is invalidated via `revalidateTag(tag)`, Dinou updates the slot and re-composes the static host page/shell. When a Static Shell slot's `revalidate` TTL expires (`revalidate >= 1`), Dinou uses **non-blocking Background Stale-While-Revalidate (SWR)**: the incoming request serves the cached `index.html` / `shell.html` immediately (`0ms` TTFB) while regenerating the expired `slot.json` and recomposing the host HTML/RSC in the background.
235
+ - **Nested `<DinouCacheSlot>` Isolation:** A `<DinouCacheSlot>` can contain inner `<DinouCacheSlot>` components. Invalidating or refreshing the **inner** slot re-evaluates **only** the inner slot while the outer slot stays cached.
236
+ - **Client Components & Server Action Props Inside Slots:** `<DinouCacheSlot>` subtrees can render `"use client"` components and pass `"use server"` functions as props; Dinou preserves client reference manifests and action bindings across slot serialization.
237
+ - **Stampede Protection:** Concurrent cache-miss requests for the same slot key are deduplicated in-flight onto a single render promise.
238
+ - **Live Client-Side Surgical Refresh (`refreshSlot`):**
239
+ Call `refreshSlot(idOrTag, { fresh?: boolean })` (from `"dinou"`) or `useRouter().refreshSlot(idOrTag, { fresh?: boolean })` from any Client Component:
240
+ - Targets a specific slot by **`id`**, by **`tag`**, or **all mounted slots via wildcard `"*"`**.
241
+ - `{ fresh: true }` forces a cache bypass and updates the server slot cache; `{ fresh: false }` (default) serves from cache unless expired/invalidated.
242
+ - **100% State Preservation:** Updating a slot in the browser surgically patches only that slot's Virtual DOM subtree; sibling Client Components in the layout, page, or other slots keep 100% of their local React state (`useState`, inputs, counters).
243
+
244
+ ---
245
+
246
+ ### 5.3. Dimension 3: Temporal Segmentation — Partial Prerendering (PPR)
247
+
248
+ **Partial Prerendering (PPR)** is Dinou's **Temporal Segmentation** axis: it splits a single route across *time*, delivering the pre-rendered **Static Shell (`shell.html`)** at $t = 0\text{ ms}$ (build/revalidation time) while streaming personalized or live **`<Suspense>` Dynamic Holes** concurrently at request time over the same HTTP connection.
249
+
250
+ Enable PPR globally in `dinou.config.mjs` (`ppr: true`) or per-route/layout in `page_functions.ts` / `layout_functions.ts` (`export const ppr = true`).
251
+
252
+ #### How `<Suspense>` Boundaries, Dynamic PPR Holes & `noDynamic()` Work:
253
+ 1. **`<Suspense>` Is the Single Boundary (`ppr = true` vs. `ppr = false`):**
254
+ - **Outside `<Suspense>`** (top-level `async` Page/Layout, `getProps`, or unwrapped child `async` Server Components): Awaited at build/revalidation time and baked directly into the **Static Shell (`shell.html`)**. *(Accessing `req.cookies`, `req.headers`, `req.query`, or `<DinouCacheSlot revalidate={0}>` outside `<Suspense>` triggers a Full-Page Dynamic Bailout).*
255
+ - **Inside `<Suspense fallback={...}>` (Default = Dynamic PPR Hole):** On `ppr = true` routes, **any `async` Server Component** (postponed immediately at its first `await` with zero build latency), any component reading `getContext()` (`req.cookies`, `req.headers`, `req.query`) / `useSearchParams()`, or `<DinouCacheSlot revalidate={0}>` automatically becomes a **Dynamic PPR Hole** (`data-ppr-hole`). Its `<Suspense>` fallback is baked into `shell.html` (`0ms` TTFB) and the resolved content streams live over the same HTTP response at request time. *(On `ppr = false` routes, `async` components inside `<Suspense>` resolve at build time into `index.html`).*
256
+ 2. **Static `<Suspense>` Opt-Out via `noDynamic()` (`"dinou"` or `"dinou/server"`):**
257
+ - If an `async` Server Component inside `<Suspense>` on a `ppr = true` route should instead resolve at build time into the **Static Shell (`shell.html`)** (e.g., static Markdown/syntax highlighting), call **`noDynamic()`** synchronously at the top of the component **before its first `await`**.
258
+ - At runtime, leaf static `<Suspense>` boundaries opted out via `noDynamic()` automatically short-circuit (`0ms`, zero re-execution) when sibling dynamic holes stream. *(If `req.cookies`, `req.headers`, or `req.query` is read inside a `noDynamic()` subtree, dynamic bailout always wins).*
259
+ 3. **Single-Request Streaming:** On incoming HTTP requests, Dinou flushes the cached `shell.html` immediately and concurrently streams all Dynamic PPR Holes over the same HTTP response stream. If a `ppr = true` route has zero dynamic holes (`holes: []`), Dinou serves `shell.html` directly with zero runtime component execution.
260
+
261
+ ---
262
+
263
+ ### 5.4. The Triple Synergy (Horizontal + Vertical + Temporal / PPR)
264
+
265
+ All three dimensions compose simultaneously in the same route tree:
266
+ - **Layout Level:** Can be Static (HS), Dynamic (HS), or PPR (`layout_functions.ts` with `ppr = true`), and can contain `<DinouCacheSlot>` components both in the **Layout Static Shell** and inside **Layout Dynamic `<Suspense>` Holes**.
267
+ - **Page Level:** Can be Static (HS), Dynamic (HS), or PPR (`page_functions.ts` with `ppr = true`), and can contain `<DinouCacheSlot>` components both in the **Page Static Shell** and inside **Page Dynamic `<Suspense>` Holes**:
268
+ - **`<DinouCacheSlot>` Outside `<Suspense>` (or Wrapping an Inner `<Suspense>`)**: Resolves at build time into the **Static Shell (`shell.html` + `slot.json`)**, preserving any inner `<Suspense>` node in `slot.json` and using non-blocking background SWR upon TTL expiration.
269
+ - **`<Suspense>` Wrapping `<DinouCacheSlot>` (`<Suspense><DinouCacheSlot>...</DinouCacheSlot></Suspense>`)**: Acts as a **Cached Dynamic PPR Hole** by default on `ppr = true` routes (unless opted out via `noDynamic()`), baking the `<Suspense>` fallback into `shell.html` and caching `slot.json` across runtime hole streams.
270
+ - **Synergy Invalidation Invariants:**
271
+ 1. Invalidating a `<DinouCacheSlot>` inside a **PPR Dynamic Hole** (`revalidateTag("hole-slot")`) updates only that slot on the next request without regenerating `shell.html` or sibling slots.
272
+ 2. Invalidating a `<DinouCacheSlot>` inside a **PPR Static Shell** (`revalidateTag("shell-slot")`) purges the slot and automatically enqueues background regeneration of the host `shell.html` (and `layout.rsc` if the slot lives in the layout shell), while leaving sibling cached slots untouched.
273
+ 3. Calling `refreshSlot(idOrTag, { fresh: true })` (or `refreshSlot("*", { fresh: true })`) from the browser updates slots live in the DOM across the Layout Shell, Layout Holes, Page Shell, and Page Holes simultaneously, **and** enqueues background regeneration of any affected static shells so a subsequent F5 hard reload serves the exact updated slot tokens with **zero hydration mismatch**.
274
+
275
+ ---
276
+
277
+ ## 6. Client Navigation, Router Cache & Hooks
278
+
279
+ Import navigation primitives from `"dinou"`:
280
+
281
+ ```tsx
282
+ "use client";
283
+ import {
284
+ Link,
285
+ ClientRedirect,
286
+ redirect,
287
+ useRouter,
288
+ usePathname,
289
+ useSearchParams,
290
+ useNavigationLoading,
291
+ refreshSlot,
292
+ } from "dinou";
293
+ ```
294
+
295
+ | Primitive | Scope | Signature / Props | Key Behavior |
296
+ | :--- | :--- | :--- | :--- |
297
+ | `<Link>` | Universal | `href` (or `to`), `prefetch?: boolean` (`true`), `fresh?: boolean` (`false`) | Performs soft SPA navigation. Prefetches RSC payload on hover when `prefetch={true}`. Pass `fresh` to bypass the client-side router cache (`pageCache`). Supports relative paths (`"sub"`, `"../other"`). |
298
+ | `useRouter()` | Client | `{ push, replace, back, forward, refresh, refreshSlot }` | `push(href, { fresh? })`, `replace(href, { fresh? })`, `refresh({ layout?: boolean })` (re-fetches current page RSC payload; pass `{ layout: true }` to also re-fetch layouts), `refreshSlot(idOrTag, { fresh? })`. |
299
+ | `usePathname()` | Universal | `() => string` | Returns current URL pathname (e.g. `"/blog/hello"`). Works in both Server Components and Client Components. |
300
+ | `useSearchParams()` | Universal | `() => URLSearchParams` | Returns read-only `URLSearchParams`. Works in both Server Components (triggers dynamic/PPR bailout) and Client Components. |
301
+ | `useNavigationLoading()` | Client | `() => boolean` | Returns `true` while a client-side route transition is in flight. |
302
+ | `redirect(url)` | Universal | `(destination: string) => ReactNode` | In `getProps` or Server Functions/Components before headers flush: sends real HTTP `307 Temporary Redirect` (or `X-Dinou-Redirect` in RPC). If streaming has already started or on client: renders `<ClientRedirect to={destination} />`. |
303
+ | `<ClientRedirect>` | Client | `<ClientRedirect to="/login" />` | Triggers immediate client-side `replace` navigation upon mount. |
304
+ | `refreshSlot()` | Client | `(slotIdOrTag: string, opts?: { fresh?: boolean }) => void` | Standalone helper (identical to `useRouter().refreshSlot`) to refresh one or all (`"*"`) `<DinouCacheSlot>` instances live in the browser. |
305
+
306
+ ---
307
+
308
+ ## 7. Server Functions (`"use server"`), Context & The Dinou Pattern
309
+
310
+ ### Server Functions & Actions (`"use server"`)
311
+ Any file or async function marked with `"use server"` runs exclusively on the server and can be imported directly into Client Components (`"use client"`):
312
+ - Supports standard React 19 form actions (`<form action={myAction}>`, `useActionState`, `useFormStatus`, `useOptimistic`) and direct RPC calls (`await myAction(arg1, arg2)`), including `FormData` uploads.
313
+ - **Security:** Bundlers automatically strip the implementation from the client bundle and replace it with a Flight RPC proxy (`/____server_function____`).
314
+
315
+ ### Reading & Mutating Request Context (`getContext()`)
316
+ Call `getContext()` (from `"dinou"` or `"dinou/server"`) synchronously inside any Server Component, `getProps`, `validateParams`, or `"use server"` function:
317
+ ```ts
318
+ import { getContext } from "dinou";
319
+
320
+ export async function updateThemeAction(theme: string) {
321
+ "use server";
322
+ const ctx = getContext();
323
+ if (!ctx) return; // undefined during static build time if no request is active
324
+
325
+ const currentCookie = ctx.req.cookies["theme"];
326
+ const userAgent = ctx.req.headers["user-agent"];
327
+
328
+ ctx.res.cookie("theme", theme, { path: "/", httpOnly: true, maxAge: 86400 });
329
+ ctx.res.setHeader("X-Custom-Header", "updated");
330
+ }
331
+ ```
332
+ - `ctx.req`: `{ query, cookies, headers, path, method, env, ctx }`
333
+ - `ctx.res`: `{ cookie(name, val, opts?), clearCookie(name, opts?), setHeader(name, val), status(code), redirect(statusOrUrl, url?) }`
334
+ - `ctx.env` / `ctx.ctx`: Platform bindings (e.g., Cloudflare Workers `env.DB`, `env.KV`, `ctx.waitUntil`).
335
+
336
+ ### The Dinou Pattern (Streaming Server Components from Server Functions)
337
+ In Dinou, a `"use server"` function can return **rendered JSX (including async Server Components and `<Suspense>` trees)** directly to a Client Component over React Flight RPC:
338
+ ```tsx
339
+ // src/actions.tsx
340
+ "use server";
341
+ export async function searchProductsView(query: string) {
342
+ const items = await db.products.search(query);
343
+ return (
344
+ <ul>
345
+ {items.map((item) => <li key={item.id}>{item.name}</li>)}
346
+ </ul>
347
+ );
348
+ }
349
+ ```
350
+ ```tsx
351
+ // src/search-client.tsx
352
+ "use client";
353
+ import { useState, Suspense } from "react";
354
+ import { searchProductsView } from "./actions";
355
+
356
+ export function SearchBox() {
357
+ const [viewPromise, setViewPromise] = useState<Promise<React.ReactNode> | null>(null);
358
+ return (
359
+ <div>
360
+ <button onClick={() => setViewPromise(searchProductsView("shoes"))}>Search</button>
361
+ <Suspense fallback={<p>Loading...</p>}>{viewPromise}</Suspense>
362
+ </div>
363
+ );
364
+ }
365
+ ```
366
+
367
+ ### On-Demand Server Cache Invalidation (`"dinou/server"`)
368
+ ```ts
369
+ import {
370
+ revalidateTag,
371
+ revalidatePath,
372
+ revalidatePage,
373
+ revalidateLayout,
374
+ } from "dinou/server";
375
+
376
+ await revalidateTag("products"); // Purges all pages, layouts & DinouCacheSlots with tag "products"
377
+ await revalidatePath("/blog/hello"); // Purges both layout (if any) and page at "/blog/hello"
378
+ await revalidatePage("/dashboard/stats"); // Purges only page.rsc + index.html (preserves cached layout.rsc)
379
+ await revalidateLayout("/dashboard"); // Purges only layout.rsc (preserves child page.rsc payloads; lazily re-composes index.html)
380
+ ```
381
+
382
+ ---
383
+
384
+ ## 8. Configuration (`dinou.config.mjs`), Middleware (`onRequest`) & Storage Adapters
385
+
386
+ Create `dinou.config.mjs` (or `.js` / `.ts`) at the project root using `defineConfig` from `"dinou"` (or `"dinou/config"`):
387
+
388
+ ```js
389
+ import { defineConfig } from "dinou";
390
+ import { RedisStorage } from "dinou/server";
391
+
392
+ export default defineConfig({
393
+ reactStrictMode: true, // Default: true
394
+ ppr: false, // Global PPR default (can be overridden per route/layout)
395
+ setupFiles: ["./dinou.setup.ts"],
396
+ // storage: new RedisStorage(redisClient, "dinou:"),
397
+ plugins: [
398
+ {
399
+ name: "auth-and-webhooks",
400
+ // 1. Universal Web Standards HTTP Middleware & Webhook Handler
401
+ async onRequest(request, context) {
402
+ const url = new URL(request.url);
403
+
404
+ // Short-circuit webhooks or API endpoints (<2ms, bypasses React)
405
+ if (url.pathname === "/api/health") {
406
+ return Response.json({ ok: true });
407
+ }
408
+
409
+ // Mutate context for downstream Server Components & Server Functions
410
+ context.user = { id: request.headers.get("x-user-id") ?? "guest" };
411
+ },
412
+
413
+ // 2. Optional Node.js HTTP Server Hook (WebSockets, raw Node middleware)
414
+ configureServer({ server, isDev, use }) {
415
+ use((req, res, next) => {
416
+ res.setHeader("X-Powered-By", "Dinou");
417
+ next();
418
+ });
419
+ },
420
+ },
421
+ ],
422
+ });
423
+ ```
424
+
425
+ ### Pluggable ISR Storage Adapters (`"dinou/server"`)
426
+ - `FileSystemStorage(baseDir?)`: Default on Node.js & Bun (persists to `.dinou/cache`).
427
+ - `CloudflareKVStorage(kvNamespace)`: Default on Cloudflare Workers when `env.DINOU_CACHE` KV binding is present.
428
+ - `DenoKVStorage(kvInstance?)`: Default on Deno / Deno Deploy.
429
+ - `MemoryStorage()`: In-memory fallback when no persistent store is configured.
430
+ - `RedisStorage(redisClient, prefix?)`: Distributed cluster cache for multi-instance deployments.
431
+ - Custom adapter: extend `StorageAdapter` (`get(key)`, `set(key, content, metadata?)`, `has(key)`, `delete(key)`) or call `setStorageAdapter(adapter)`.
432
+
433
+ ---
434
+
435
+ ## 9. Styling, Assets, Environment Variables & Aliases
436
+
437
+ - **Global CSS & Tailwind CSS v4:** Import `./styles.css` in `src/layout.tsx` (compiled automatically via PostCSS + `@tailwindcss/postcss` + `autoprefixer` into `/styles.css`) and link it in `<head>`:
438
+ ```tsx
439
+ import "./styles.css";
440
+ // Inside RootLayout <head>:
441
+ <link rel="stylesheet" href="/styles.css" precedence="default" />
442
+ ```
443
+ - **CSS Modules:** Any `*.module.css` file returns scoped class names (`import styles from "./card.module.css"`).
444
+ - **Media & Asset Imports:** Import 21+ formats (`.png`, `.jpg`, `.jpeg`, `.gif`, `.svg`, `.webp`, `.avif`, `.ico`, `.mp4`, `.webm`, `.ogg`, `.mp3`, `.wav`, `.flac`, `.aac`, `.woff`, `.woff2`, `.eot`, `.ttf`, `.otf`, `.pdf`) directly in Server or Client Components to receive their hashed public URL string. Add `/// <reference types="dinou/env" />` in `src/env.d.ts` for TypeScript support.
445
+ - **Public Directory (`public/`):** Files in `public/` are copied verbatim to `.dinou/dist3/` and served at the root URL (`/favicon.ico`, `/robots.txt`).
446
+ - **Path Aliases (`tsconfig.json`):** Configure `compilerOptions.paths` (e.g. `"@/*": ["./src/*"]`) in `tsconfig.json`. Dinou automatically resolves aliases across TypeScript/JSX, CSS `@import`, and asset imports in all three bundlers (esbuild, Rollup, Webpack).
447
+ - **Environment Variables:** `.env` files are loaded on the server via `dotenv`. For security, `process.env` secrets are **server-only** and never bundled into client code; pass public values explicitly as props from Server Components to Client Components.
448
+
449
+ ---
450
+
451
+ ## 10. Bundlers, Deployment Targets, Dual-Mode Vendoring & Eject
452
+
453
+ ### Multi-Bundler Parity
454
+ Dinou provides 100% feature parity across three bundlers:
455
+ - **esbuild** (Default): Fastest builds and HMR.
456
+ - **Rollup** (`:rollup`): Clean ES module output.
457
+ - **Webpack** (`:webpack`): Includes `babel-plugin-react-compiler` automatic memoization in production builds.
458
+
459
+ ### Deployment Targets
460
+ - **Node.js:** `npm run build && npm start` (entry: `dinou/adapters/node`).
461
+ - **Cloudflare Workers:** `npm run build:cloudflare && npx wrangler deploy` (generates `.dinou/cloudflare/worker.js`).
462
+ - **Bun:** `npm run build:bun && npm run start:bun` (or `npm run build:bun:compile` for standalone binary).
463
+ - **Deno:** `npm run build:deno && npm run start:deno` (or `npm run build:deno:compile` for standalone binary).
464
+ - **Netlify:** Uses `dinou/adapters/netlify` serverless entry.
465
+ - **Static Export:** `npm run export-static` outputs a self-contained static site into `dist/`.
466
+
467
+ ### Dual-Mode Vendoring (`--unvendorized` / `-u`)
468
+ By default, Dinou runs in **Vendorized Mode**, resolving Babel, PostCSS, Tailwind, Rollup/Webpack plugins, `ws`, `chokidar`, etc. from pre-compiled zero-install bundles in `dinou/compiled/` via `package.json` `#imports`.
469
+ Pass `-u` / `--unvendorized` (e.g. `npx dinou dev -u` or `DINOU_UNVENDORIZED=true`) to resolve those packages from standard `node_modules` via Node's `--conditions=unvendorized`.
470
+
471
+ ### Ejecting (`npx dinou eject`)
472
+ Running `npx dinou eject` copies the complete Dinou framework into `./dinou` at your project root and rewrites `package.json` scripts and imports to use `./dinou/index.js`, `./dinou/server.js`, and `./dinou/cli.js`, giving you 100% ownership of the compiler and runtime.
473
+
474
+ ---
475
+
476
+ ## 11. Complete Public Exports Cheat-Sheet
477
+
478
+ ### Package `"dinou"`
479
+ | Export | Kind | Description |
480
+ | :--- | :--- | :--- |
481
+ | `Link` | Component | Client SPA navigation `<Link href="..." prefetch? fresh? />` |
482
+ | `ClientRedirect` | Component | Client mount redirect `<ClientRedirect to="..." />` |
483
+ | `redirect` | Function | Universal redirect `redirect("/path")` (HTTP 307 or SPA redirect) |
484
+ | `useRouter` | Hook (Client) | `{ push, replace, back, forward, refresh, refreshSlot }` |
485
+ | `usePathname` | Hook (Universal) | Current URL pathname string |
486
+ | `useSearchParams` | Hook (Universal) | Current `URLSearchParams` |
487
+ | `useNavigationLoading` | Hook (Client) | Boolean pending navigation state |
488
+ | `refreshSlot` | Function (Client) | `refreshSlot(slotIdOrTag, { fresh?: boolean })` (supports `"*"` wildcard) |
489
+ | `getContext` | Function (Server) | Returns `{ req, res, env, ctx, ...custom }` from `AsyncLocalStorage` |
490
+ | `noDynamic` | Function (Server) | Opts enclosing `<Suspense>` out of becoming a Dynamic PPR Hole on `ppr = true` routes |
491
+ | `defineConfig` | Function | Type-safe helper for `dinou.config.mjs` |
492
+ | `PageProps<T>`, `LayoutProps<T>`, `ErrorProps<T>`, `PageFunctions<T, P>`, `LayoutFunctions<T, P>`, `RouteSegmentConfig`, `PPRConfig`, `StaticPathItem`, `StaticPathsResult`, `RouteParams<T>`, `DinouRoute`, `DinouRoutePattern`, `DinouRouter`, `CleanRoutePath`, `ExtractRouteParams`, `ExtractSegmentParam`, `LinkProps`, `ClientRedirectProps`, `NavigationOptions`, `RequestContextStore`, `ResponseProxy`, `CookieOptions`, `Query`, `Cookies`, `Headers`, `DinouConfig`, `DinouPlugin`, `ServerHookContext`, `NodeMiddleware` | TypeScript Types | Complete compile-time routing, component prop, context, and plugin types |
493
+
494
+ ### Package `"dinou/server"`
495
+ | Export | Kind | Description |
496
+ | :--- | :--- | :--- |
497
+ | `DinouCacheSlot` | Server Component | `<DinouCacheSlot id? tag? tags? revalidate?>{children}</DinouCacheSlot>` |
498
+ | `getContext` | Function (Server) | Returns `{ req, res, env, ctx, ...custom }` from `AsyncLocalStorage` (also in `"dinou"`) |
499
+ | `noDynamic` | Function (Server) | Opts enclosing `<Suspense>` out of becoming a Dynamic PPR Hole (also in `"dinou"`) |
500
+ | `revalidateTag` | Function (Server) | `await revalidateTag(tag)` — invalidates tagged pages, layouts & slots |
501
+ | `revalidatePath` | Function (Server) | `await revalidatePath(path)` — invalidates route layout + page |
502
+ | `revalidatePage` | Function (Server) | `await revalidatePage(path)` — invalidates only `page.rsc` + `index.html` |
503
+ | `revalidateLayout` | Function (Server) | `await revalidateLayout(path)` — invalidates only `layout.rsc` (lazy HTML re-composition) |
504
+ | `StorageAdapter`, `FileSystemStorage`, `CloudflareKVStorage`, `DenoKVStorage`, `MemoryStorage`, `RedisStorage`, `getStorageAdapter`, `setStorageAdapter` | Storage API | Pluggable cache storage engines for SSG / ISR / PPR / `DinouCacheSlot` |
505
+ | `DinouCacheSlotProps`, `StorageItem`, plus all server/route/page/layout/context/plugin types (`PageProps<T>`, `LayoutProps<T>`, `ErrorProps<T>`, `PageFunctions<T, P>`, `LayoutFunctions<T, P>`, `RouteSegmentConfig`, `PPRConfig`, `StaticPathItem`, `StaticPathsResult`, `RouteParams<T>`, `DinouRoute`, `DinouRoutePattern`, `DinouRouter`, `CleanRoutePath`, `ExtractRouteParams`, `ExtractSegmentParam`, `RequestContextStore`, `ResponseProxy`, `CookieOptions`, `Query`, `Cookies`, `Headers`, `DinouConfig`, `DinouPlugin`, `ServerHookContext`, `NodeMiddleware`) | TypeScript Types | Server-side & routing TypeScript definitions re-exported from `"dinou/server"` |
506
+
507
+ ### Package `"dinou/config"` & Additional Subpaths
508
+ | Subpath | Export / Purpose | Description |
509
+ | :--- | :--- | :--- |
510
+ | `"dinou/config"` | `defineConfig` (+ types from `index.d.ts`) | Dedicated config-only entry point (`dinou/core/config.js`) for `dinou.config.{mjs,js,ts}` |
511
+ | `"dinou/env"` | Ambient TypeScript definitions | `/// <reference types="dinou/env" />` — declares module types for 21+ static asset & media extensions |
512
+ | `"dinou/adapters/{node,bun,deno,cloudflare,netlify}"` | Platform runtime adapters | Server entry points for each deployment runtime |
513
+
514
+ > **Import Safety Rule:** `import { ... } from "dinou"` (and `import type`) is 100% safe in both Server Components/Functions and Client Components (`"use client"`). Runtime value imports `import { ... } from "dinou/server"` are **Server-Only** (pulling `node:*` modules), whereas `import type { ... } from "dinou/server"` is erased at compile time and safe anywhere.
515
+
516
+ ---
517
+
518
+ ## License
519
+
520
+ [MIT](./LICENSE.md)