@fierst/c7t 0.0.0-stage → 1.0.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/CHANGELOG.md +38 -0
- package/LICENSE +21 -0
- package/README.md +62 -2
- package/bin/c7t.d.mts +1 -0
- package/bin/c7t.mjs +107 -0
- package/bin/create.d.mts +9 -0
- package/bin/create.mjs +344 -0
- package/dist/adapters/bun.d.mts +40 -0
- package/dist/adapters/bun.mjs +114 -0
- package/dist/adapters/cloudflare.d.mts +29 -0
- package/dist/adapters/cloudflare.mjs +28 -0
- package/dist/adapters/node.d.mts +31 -0
- package/dist/adapters/node.mjs +139 -0
- package/dist/adapters/static.d.mts +34 -0
- package/dist/adapters/static.mjs +53 -0
- package/dist/adapters/vercel.d.mts +40 -0
- package/dist/adapters/vercel.mjs +79 -0
- package/dist/client.d.mts +78 -0
- package/dist/client.mjs +181 -0
- package/dist/head-CUiNFY7Q.mjs +142 -0
- package/dist/index.d.mts +77 -0
- package/dist/index.mjs +25 -0
- package/dist/multipart-CwqTb3AQ.mjs +72 -0
- package/dist/protocol-B6QOAMGj.d.mts +115 -0
- package/dist/protocol-CZANZJ5x.mjs +126 -0
- package/dist/router-19ZZ3woS.d.mts +148 -0
- package/dist/router-B50LekA_.mjs +680 -0
- package/dist/router.d.mts +2 -0
- package/dist/router.mjs +1 -0
- package/dist/search-params-C03mU47i.mjs +79 -0
- package/dist/server.d.mts +146 -0
- package/dist/server.mjs +850 -0
- package/dist/ssg-DFBgqaob.d.mts +40 -0
- package/dist/ssg.d.mts +2 -0
- package/dist/ssg.mjs +179 -0
- package/dist/vite.d.mts +95 -0
- package/dist/vite.mjs +920 -0
- package/docs/README.md +26 -0
- package/docs/guides/01-getting-started.md +164 -0
- package/docs/guides/02-data-fetching-and-mutations.md +258 -0
- package/docs/guides/03-streaming-and-workflows.md +198 -0
- package/docs/guides/04-routing-layouts-and-state.md +236 -0
- package/docs/guides/05-auth-sessions-and-security.md +179 -0
- package/docs/guides/06-ssg-and-deployment.md +247 -0
- package/docs/guides/07-databases-and-drizzle.md +200 -0
- package/docs/reference.md +112 -0
- package/llms.txt +1627 -0
- package/package.json +121 -4
- package/template/gitignore +11 -0
- package/template/package.json +22 -0
- package/template/src/routes/404.tsx +16 -0
- package/template/src/routes/about.tsx +22 -0
- package/template/src/routes/index.tsx +41 -0
- package/template/src/routes/layout.tsx +14 -0
- package/template/src/styles.css +39 -0
- package/template/tsconfig.json +18 -0
- package/template/vite.config.ts +16 -0
package/llms.txt
ADDED
|
@@ -0,0 +1,1627 @@
|
|
|
1
|
+
# c7t (Construct — @fierst/c7t) 1.0.0
|
|
2
|
+
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
CRITICAL RULES FOR AI CODING ASSISTANTS: Never write React hooks (`useState`, `useEffect`, `useMemo`), `<Show>`/`<For>` control-flow components, `<Link>` wrappers, or separate route `loader` conventions. `c7t` is built on `@fierst/blokd` generator components (`function*`), Hono, and Vite+ (`vp`). Use plain `let` inside `function*` + `return () => (<JSX />)` (or `for (props of ctx) { yield <JSX />; }`), `yield* serverFn()` during component setup for 0-tick State Receipt SSR/revival, `await serverFn()` inside event handlers for live RPCs, `for await (const chunk of streamFn())` for NDJSON server streams, and standard `<a href>` links for nested layout routing.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
This handbook contains all seven `c7t` guides followed by the complete API reference.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
# 01. Getting Started with c7t ("Construct")
|
|
14
|
+
|
|
15
|
+
`@fierst/c7t` turns a single directory of `.tsx` files into a streaming SSR + SSG full-stack application with zero client bootstrap boilerplate, zero hydration waterfall, and end-to-end TypeScript safety.
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## 1. Scaffold a New Project
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npx @fierst/c7t my-app
|
|
23
|
+
cd my-app
|
|
24
|
+
npm install
|
|
25
|
+
npm run dev
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Open `http://localhost:5173`. Edit `src/routes/index.tsx`—Blokd's in-place HMR updates generator components without losing local `let` state, while `@fierst/c7t/vite` hot-reloads `server()` handlers on the fly.
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## 2. Project Anatomy
|
|
33
|
+
|
|
34
|
+
A minimal `c7t` project requires **no `index.html`**, **no client `main.tsx`**, and **no custom `server.ts`** unless you want custom Hono middleware:
|
|
35
|
+
|
|
36
|
+
```text
|
|
37
|
+
my-app/
|
|
38
|
+
├── src/
|
|
39
|
+
│ ├── styles.css # Automatically linked in <head> (zero FOUC!)
|
|
40
|
+
│ └── routes/
|
|
41
|
+
│ ├── layout.tsx # Persistent root shell (<nav>, theme, footer)
|
|
42
|
+
│ ├── index.tsx # "/" — Full-stack page + colocated server() RPCs
|
|
43
|
+
│ ├── about.tsx # "/about" — Static SSG page (export const prerender = true)
|
|
44
|
+
│ └── 404.tsx # Custom HTTP 404 page rendered inside layout.tsx
|
|
45
|
+
├── vite.config.ts # Single plugin: c7t()
|
|
46
|
+
├── tsconfig.json # jsxImportSource: "@fierst/blokd"
|
|
47
|
+
└── package.json
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### `vite.config.ts`
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { defineConfig } from "vite-plus";
|
|
54
|
+
import c7t from "@fierst/c7t/vite";
|
|
55
|
+
|
|
56
|
+
export default defineConfig({
|
|
57
|
+
plugins: [c7t()],
|
|
58
|
+
lint: {
|
|
59
|
+
ignorePatterns: ["node_modules/**", "dist/**", ".vercel/**"],
|
|
60
|
+
rules: {
|
|
61
|
+
"require-yield": "off",
|
|
62
|
+
},
|
|
63
|
+
options: {
|
|
64
|
+
typeAware: true,
|
|
65
|
+
typeCheck: true,
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
## 3. Your First Full-Stack Route
|
|
74
|
+
|
|
75
|
+
Create `src/routes/index.tsx`. Notice how server queries, mutations, `<head>` metadata, local `let` state, and reactive JSX live cohesively in one file:
|
|
76
|
+
|
|
77
|
+
```tsx
|
|
78
|
+
import { head, server } from "@fierst/c7t";
|
|
79
|
+
|
|
80
|
+
interface Todo {
|
|
81
|
+
id: string;
|
|
82
|
+
title: string;
|
|
83
|
+
done: boolean;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// In-memory store for illustration — swap for SQLite, Postgres, Drizzle, or Cloudflare D1!
|
|
87
|
+
const todos: Todo[] = [{ id: "1", title: "Ship Construct v1.0", done: false }];
|
|
88
|
+
|
|
89
|
+
export const listTodos = server(async () => [...todos]);
|
|
90
|
+
|
|
91
|
+
export const addTodo = server(async (title: string) => {
|
|
92
|
+
const item: Todo = { id: crypto.randomUUID(), title: title.trim(), done: false };
|
|
93
|
+
todos.unshift(item);
|
|
94
|
+
return item;
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
export default function* HomePage() {
|
|
98
|
+
// 1. Runs directly on the server during SSR; replays in 0 ticks on client revival!
|
|
99
|
+
let items = yield* listTodos();
|
|
100
|
+
let draft = "";
|
|
101
|
+
let saving = false;
|
|
102
|
+
|
|
103
|
+
head({
|
|
104
|
+
title: "Tasks — Construct",
|
|
105
|
+
description: "Zero-VDOM full-stack task tracker",
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
// 2. Live reactive view closure — plain `let` mutations automatically patch compiled DOM slots!
|
|
109
|
+
return () => (
|
|
110
|
+
<main>
|
|
111
|
+
<h1>Tasks ({items.filter((t) => !t.done).length} remaining)</h1>
|
|
112
|
+
|
|
113
|
+
<form
|
|
114
|
+
onSubmit={async (e) => {
|
|
115
|
+
e.preventDefault();
|
|
116
|
+
if (!draft.trim() || saving) return;
|
|
117
|
+
saving = true;
|
|
118
|
+
try {
|
|
119
|
+
const created = await addTodo(draft);
|
|
120
|
+
items = [created, ...items];
|
|
121
|
+
draft = "";
|
|
122
|
+
} finally {
|
|
123
|
+
saving = false;
|
|
124
|
+
}
|
|
125
|
+
}}
|
|
126
|
+
>
|
|
127
|
+
<input bind:value={draft} placeholder="Add a task…" />
|
|
128
|
+
<button type="submit" disabled={saving || !draft.trim()}>
|
|
129
|
+
{saving ? "Saving…" : "Add"}
|
|
130
|
+
</button>
|
|
131
|
+
</form>
|
|
132
|
+
|
|
133
|
+
<ul>
|
|
134
|
+
{items.map((item) => (
|
|
135
|
+
<li key={item.id}>
|
|
136
|
+
<label>
|
|
137
|
+
<input type="checkbox" bind:checked={item.done} />
|
|
138
|
+
<span>{item.title}</span>
|
|
139
|
+
</label>
|
|
140
|
+
</li>
|
|
141
|
+
))}
|
|
142
|
+
</ul>
|
|
143
|
+
</main>
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### What Happened Under the Hood?
|
|
149
|
+
|
|
150
|
+
1. **Zero Client Secret Leakage:** During the browser build, `@fierst/c7t/vite` parses `src/routes/index.tsx` with Rust Oxc, replaces `server(...)` bodies with lightweight `createRpcStub("c7t_<sha256>")` stubs, and strips any imports referenced only inside `server(...)` (such as database drivers, `node:fs`, or schema libraries).
|
|
151
|
+
2. **Zero Hydration Waterfall:** On `GET /`, Hono streams the HTML with `<link rel="stylesheet">` already in `<head>` and embeds a deduplicated **State Receipt** (`<script id="__C7T_RECEIPTS__">`). Zero framework JavaScript executes on page load until the user actually focuses or clicks inside `<HomePage />`.
|
|
152
|
+
3. **0-Tick Lazy Revival:** On first interaction, Blokd loads the component chunk, replays `yield* listTodos()` synchronously from the State Receipt (**0 network requests**), claims the existing DOM nodes in-place without losing typed input, and replays the event.
|
|
153
|
+
|
|
154
|
+
---
|
|
155
|
+
|
|
156
|
+
## 4. Development, Checking, and Production Builds
|
|
157
|
+
|
|
158
|
+
```bash
|
|
159
|
+
# Start Vite+ dev server with SSR + HMR
|
|
160
|
+
npm run dev
|
|
161
|
+
|
|
162
|
+
# Run formatting, Oxlint, and TypeScript type-checking
|
|
163
|
+
npm run check
|
|
164
|
+
|
|
165
|
+
# Run the 3-stage production pipeline (Client -> SSR Bundle -> SSG Prerender + Adapter)
|
|
166
|
+
npm run build
|
|
167
|
+
|
|
168
|
+
# Boot the standalone Node production server on http://localhost:3000
|
|
169
|
+
npm start
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
What `c7t build` produces in `dist/`:
|
|
173
|
+
|
|
174
|
+
- `dist/client/` — Content-hashed JS islands, extracted CSS stylesheets, `c7t-manifest.json`, and any prerendered SSG `.html` + `__c7t.json` sidecar files.
|
|
175
|
+
- `dist/server/entry.mjs` — Self-contained Hono SSR + RPC server bundle with inline asset & stylesheet manifests (runs with zero filesystem reads on edge or serverless runtimes).
|
|
176
|
+
- `dist/server/start.mjs` — Ready-to-run Node HTTP server serving `dist/client` with `Cache-Control: immutable` on `/assets/*` and streaming SSR/RPCs for dynamic routes.
|
|
177
|
+
|
|
178
|
+
---
|
|
179
|
+
|
|
180
|
+
# 02. Data Fetching, Validation, Optimistic UI, and File Uploads
|
|
181
|
+
|
|
182
|
+
In `c7t`, you never maintain separate REST controllers, route `loader` conventions, `useEffect` fetch hooks, or query-cache providers. Everything flows through one primitive: **`server()`**.
|
|
183
|
+
|
|
184
|
+
---
|
|
185
|
+
|
|
186
|
+
## 1. Dual-Protocol `server()` Callables (`yield*` + `await`)
|
|
187
|
+
|
|
188
|
+
Every function wrapped in `server(...)` returns a `ServerCall<T>` implementing **both** JavaScript's `Generator` protocol (`[Symbol.iterator]`) and `PromiseLike<T>` (`then()`):
|
|
189
|
+
|
|
190
|
+
| Calling Style | Where to Use It | Behavior |
|
|
191
|
+
| ------------------------------------------ | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
192
|
+
| `const data = yield* getProject(id)` | Inside synchronous `function*` setup | **SSR:** Calls the server function directly in-process and records a State Receipt.<br>**Client Revival:** Replays the recorded value synchronously in **0 microtasks** (0 network requests).<br>**Client SPA Navigation:** Suspends cleanly while fetching `/_c7t/rpc/:id` (or reads `__c7t.json` on SSG routes). |
|
|
193
|
+
| `const saved = await updateProject(patch)` | Inside DOM event handlers (`onClick`, `onSubmit`) or `async function*` | Sends `POST /_c7t/rpc/:id` with automatic CSRF verification, schema validation, and typed error/redirect propagation. |
|
|
194
|
+
|
|
195
|
+
---
|
|
196
|
+
|
|
197
|
+
## 2. Colocated `server()` vs Dedicated `*.server.ts` Files
|
|
198
|
+
|
|
199
|
+
Both styles compile to identical RPC endpoints and client stubs—pick whichever fits your module organization:
|
|
200
|
+
|
|
201
|
+
### Style A: Colocated Inside a `.tsx` Route
|
|
202
|
+
|
|
203
|
+
Ideal when queries/mutations belong to one route. Oxc automatically prunes server-only imports (`db`, `valibot`, `node:crypto`) from the client bundle:
|
|
204
|
+
|
|
205
|
+
```tsx
|
|
206
|
+
import { server } from "@fierst/c7t";
|
|
207
|
+
import { db } from "../lib/db"; // Automatically stripped from client bundle!
|
|
208
|
+
|
|
209
|
+
const getStats = server(async () => {
|
|
210
|
+
return db.query("SELECT count(*) AS users FROM accounts");
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
export default function* Dashboard() {
|
|
214
|
+
const stats = yield* getStats();
|
|
215
|
+
return () => <p>Total users: {stats.users}</p>;
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
### Style B: Dedicated `*.server.ts` Module Boundary
|
|
220
|
+
|
|
221
|
+
Ideal when multiple routes share domain logic. Every exported `async function`, arrow function, `async function*`, or `server(...)` declaration in a `*.server.ts` file is automatically registered as an RPC, and the entire module compiles to lightweight stubs on the client:
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
// src/lib/invoices.server.ts
|
|
225
|
+
import { server, notFound } from "@fierst/c7t";
|
|
226
|
+
import * as v from "valibot";
|
|
227
|
+
import { db } from "./db";
|
|
228
|
+
|
|
229
|
+
// Plain exported async function — automatically becomes a Dual-Protocol ServerCall!
|
|
230
|
+
export async function getInvoice(id: string) {
|
|
231
|
+
const row = await db.invoices.findUnique({ where: { id } });
|
|
232
|
+
if (!row) throw notFound(`Invoice #${id} does not exist`);
|
|
233
|
+
return row;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Schema-validated mutation
|
|
237
|
+
export const markInvoicePaid = server(
|
|
238
|
+
v.object({ invoiceId: v.pipe(v.string(), v.nonEmpty()) }),
|
|
239
|
+
async ({ invoiceId }) => {
|
|
240
|
+
return db.invoices.update({ where: { id: invoiceId }, data: { status: "paid" } });
|
|
241
|
+
},
|
|
242
|
+
);
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
---
|
|
246
|
+
|
|
247
|
+
## 3. Parallel Queries with `all()` & Request Deduplication
|
|
248
|
+
|
|
249
|
+
Avoid sequential waterfalls when loading multiple independent queries by combining them with **`all([...])`**:
|
|
250
|
+
|
|
251
|
+
```tsx
|
|
252
|
+
import { all, type RouteProps } from "@fierst/c7t";
|
|
253
|
+
import { getProject, getProjectMembers, getRecentActivity } from "./projects.server";
|
|
254
|
+
|
|
255
|
+
export default function* ProjectOverview(props: RouteProps<"/projects/[id]">) {
|
|
256
|
+
// Executes all 3 queries concurrently via Promise.all on SSR & SPA navigation,
|
|
257
|
+
// and replays all 3 synchronously in 0 ticks on client revival!
|
|
258
|
+
const [project, members, activity] = yield* all([
|
|
259
|
+
getProject(props.params.id),
|
|
260
|
+
getProjectMembers(props.params.id),
|
|
261
|
+
getRecentActivity(props.params.id),
|
|
262
|
+
]);
|
|
263
|
+
|
|
264
|
+
return () => (
|
|
265
|
+
<section>
|
|
266
|
+
<h1>{project.name}</h1>
|
|
267
|
+
<p>
|
|
268
|
+
{members.length} members · {activity.length} recent events
|
|
269
|
+
</p>
|
|
270
|
+
</section>
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
### Automatic Per-Request Memoization & `$ref` Deduplication
|
|
276
|
+
|
|
277
|
+
- **Request Memoization:** If both `layout.tsx` and `index.tsx` call `yield* getCurrentUser()` during the same SSR request with identical arguments, `c7t` executes `getCurrentUser()` **once** and shares the result.
|
|
278
|
+
- **`$ref` Receipt Pool:** Repeated objects across islands are stored once in `window.__C7T_R.p` and referenced via `{"$ref": 0}`, preserving object identity (`a === b`) after revival while shrinking HTML payload size. `Date` and `URLSearchParams` values serialize losslessly.
|
|
279
|
+
|
|
280
|
+
---
|
|
281
|
+
|
|
282
|
+
## 4. Standard Schema Input Validation & `err.fields`
|
|
283
|
+
|
|
284
|
+
Pass any **[Standard Schema v1](https://standardschema.dev)** validator (**Valibot**, **Zod 3.24+**, or **ArkType**) as the first argument to `server(Schema, fn)`. Invalid payloads are rejected at the HTTP boundary with **status `400`** before your handler executes, and reconstruct on the client as a typed `ValidationError` with a lazy **`err.fields`** map:
|
|
285
|
+
|
|
286
|
+
```tsx
|
|
287
|
+
import { server, ValidationError } from "@fierst/c7t";
|
|
288
|
+
import * as v from "valibot";
|
|
289
|
+
|
|
290
|
+
const InviteSchema = v.object({
|
|
291
|
+
email: v.pipe(v.string(), v.email("Enter a valid work email")),
|
|
292
|
+
role: v.picklist(["member", "admin"], "Choose member or admin"),
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
export const sendInvite = server(InviteSchema, async (input) => {
|
|
296
|
+
// `input` is inferred as `{ email: string; role: "member" | "admin" }`
|
|
297
|
+
return { id: crypto.randomUUID(), ...input };
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
export default function* InviteForm() {
|
|
301
|
+
let email = "";
|
|
302
|
+
let role: "member" | "admin" = "member";
|
|
303
|
+
let fieldErrors: Record<string, string> = {};
|
|
304
|
+
let sentTo: string | null = null;
|
|
305
|
+
|
|
306
|
+
return () => (
|
|
307
|
+
<form
|
|
308
|
+
onSubmit={async (e) => {
|
|
309
|
+
e.preventDefault();
|
|
310
|
+
fieldErrors = {};
|
|
311
|
+
try {
|
|
312
|
+
const res = await sendInvite({ email, role });
|
|
313
|
+
sentTo = res.email;
|
|
314
|
+
email = "";
|
|
315
|
+
} catch (err) {
|
|
316
|
+
if (err instanceof ValidationError) {
|
|
317
|
+
// Instant dot-path lookup: { email: "Enter a valid work email" }
|
|
318
|
+
fieldErrors = err.fields;
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
throw err;
|
|
322
|
+
}
|
|
323
|
+
}}
|
|
324
|
+
>
|
|
325
|
+
<label>
|
|
326
|
+
Work Email
|
|
327
|
+
<input bind:value={email} type="email" aria-invalid={Boolean(fieldErrors.email)} />
|
|
328
|
+
</label>
|
|
329
|
+
{fieldErrors.email && <p class="error">{fieldErrors.email}</p>}
|
|
330
|
+
|
|
331
|
+
<select bind:value={role}>
|
|
332
|
+
<option value="member">Member</option>
|
|
333
|
+
<option value="admin">Admin</option>
|
|
334
|
+
</select>
|
|
335
|
+
|
|
336
|
+
<button type="submit">Send Invite</button>
|
|
337
|
+
{sentTo && <p>Invitation sent to {sentTo}!</p>}
|
|
338
|
+
</form>
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
---
|
|
344
|
+
|
|
345
|
+
## 5. Zero-Framework Optimistic UI + Automatic Rollback
|
|
346
|
+
|
|
347
|
+
Because local state in Blokd is ordinary JavaScript `let`, optimistic updates and error rollbacks require zero `useOptimistic` hooks—just save a snapshot, mutate `let` before `await`, and restore inside `catch` + `ctx.refresh()`:
|
|
348
|
+
|
|
349
|
+
```tsx
|
|
350
|
+
import type { Ctx } from "@fierst/blokd";
|
|
351
|
+
import { toggleTaskDone, type Task } from "./tasks.server";
|
|
352
|
+
|
|
353
|
+
export function* TaskItem(props: { task: Task }, ctx: Ctx<{ task: Task }>) {
|
|
354
|
+
let done = props.task.done;
|
|
355
|
+
let errorMsg = "";
|
|
356
|
+
|
|
357
|
+
return () => (
|
|
358
|
+
<li>
|
|
359
|
+
<label>
|
|
360
|
+
<input
|
|
361
|
+
type="checkbox"
|
|
362
|
+
checked={done}
|
|
363
|
+
onChange={async () => {
|
|
364
|
+
const previous = done;
|
|
365
|
+
done = !done; // 1. Instant optimistic UI update!
|
|
366
|
+
errorMsg = "";
|
|
367
|
+
try {
|
|
368
|
+
const updated = await toggleTaskDone(props.task.id, done);
|
|
369
|
+
done = updated.done;
|
|
370
|
+
} catch (err) {
|
|
371
|
+
done = previous; // 2. Exact rollback on network/server failure
|
|
372
|
+
errorMsg = (err as Error).message;
|
|
373
|
+
} finally {
|
|
374
|
+
ctx.refresh(); // 3. Patch DOM slots after async settlement
|
|
375
|
+
}
|
|
376
|
+
}}
|
|
377
|
+
/>
|
|
378
|
+
<span>{props.task.title}</span>
|
|
379
|
+
</label>
|
|
380
|
+
{errorMsg && <small role="alert">{errorMsg}</small>}
|
|
381
|
+
</li>
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
---
|
|
387
|
+
|
|
388
|
+
## 6. Binary `File`, `Blob`, and `FormData` Uploads
|
|
389
|
+
|
|
390
|
+
Pass `File`, `Blob`, or `FormData` objects directly to any `server()` function—even nested inside plain objects or arrays! `c7t` automatically detects binary payloads, switches the wire transport from JSON to `multipart/form-data`, and reconstructs native `File` instances on the server:
|
|
391
|
+
|
|
392
|
+
```tsx
|
|
393
|
+
import { server, httpError } from "@fierst/c7t";
|
|
394
|
+
import { writeFile } from "node:fs/promises";
|
|
395
|
+
|
|
396
|
+
export const uploadAvatar = server(async (input: { displayName: string; avatar: File }) => {
|
|
397
|
+
if (input.avatar.size > 5 * 1024 * 1024) {
|
|
398
|
+
throw httpError(413, "Avatar must be smaller than 5 MB");
|
|
399
|
+
}
|
|
400
|
+
const bytes = new Uint8Array(await input.avatar.arrayBuffer());
|
|
401
|
+
await writeFile(`./uploads/${crypto.randomUUID()}-${input.avatar.name}`, bytes);
|
|
402
|
+
return { name: input.avatar.name, bytes: input.avatar.size };
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
export default function* AvatarUploader() {
|
|
406
|
+
let displayName = "";
|
|
407
|
+
let selectedFile: File | null = null;
|
|
408
|
+
let uploadedInfo: { name: string; bytes: number } | null = null;
|
|
409
|
+
|
|
410
|
+
return () => (
|
|
411
|
+
<form
|
|
412
|
+
onSubmit={async (e) => {
|
|
413
|
+
e.preventDefault();
|
|
414
|
+
if (!selectedFile) return;
|
|
415
|
+
uploadedInfo = await uploadAvatar({ displayName, avatar: selectedFile });
|
|
416
|
+
}}
|
|
417
|
+
>
|
|
418
|
+
<input bind:value={displayName} placeholder="Display name" />
|
|
419
|
+
<input
|
|
420
|
+
type="file"
|
|
421
|
+
accept="image/*"
|
|
422
|
+
onChange={(e) => {
|
|
423
|
+
selectedFile = e.currentTarget.files?.[0] ?? null;
|
|
424
|
+
}}
|
|
425
|
+
/>
|
|
426
|
+
<button type="submit" disabled={!selectedFile}>
|
|
427
|
+
Upload
|
|
428
|
+
</button>
|
|
429
|
+
{uploadedInfo && (
|
|
430
|
+
<p>
|
|
431
|
+
Uploaded {uploadedInfo.name} ({uploadedInfo.bytes} bytes)
|
|
432
|
+
</p>
|
|
433
|
+
)}
|
|
434
|
+
</form>
|
|
435
|
+
);
|
|
436
|
+
}
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
---
|
|
440
|
+
|
|
441
|
+
# 03. Streaming SSR, NDJSON Server Streams, and `yield*` Workflows
|
|
442
|
+
|
|
443
|
+
JavaScript generators give `c7t` a superpower that non-generator frameworks have to bolt on with custom protocols: **one unified language construct (`yield`, `yield*`, `for await`) governs UI state, streaming HTML, real-time server streams, and multi-step user workflows.**
|
|
444
|
+
|
|
445
|
+
---
|
|
446
|
+
|
|
447
|
+
## 1. Out-of-Order Streaming SSR (`async function*`)
|
|
448
|
+
|
|
449
|
+
By default, `createServer()` runs in `ssrMode: "stream"`. Any `async function*` component can `yield` an immediate loading skeleton before awaiting slow data:
|
|
450
|
+
|
|
451
|
+
1. `c7t` flushes `<head>` (with `<title>`, meta tags, and `<link rel="stylesheet">`) plus the initial shell + skeleton HTML immediately for sub-10ms TTFB.
|
|
452
|
+
2. As each `async function*` resolves on the server—in whatever order it finishes—Blokd streams a self-cleaning `<template>` + `<script>` swap chunk and its State Receipt entry.
|
|
453
|
+
|
|
454
|
+
```tsx
|
|
455
|
+
import { server } from "@fierst/c7t";
|
|
456
|
+
|
|
457
|
+
const fetchSlowAnalytics = server(async (orgId: string) => {
|
|
458
|
+
await new Promise((r) => setTimeout(r, 400));
|
|
459
|
+
return { revenue: "$48,200", conversion: "4.8%" };
|
|
460
|
+
});
|
|
461
|
+
|
|
462
|
+
export async function* AnalyticsWidget(props: { orgId: string }) {
|
|
463
|
+
// Flushed immediately in the first HTTP chunk!
|
|
464
|
+
yield <div class="card skeleton">Loading revenue metrics…</div>;
|
|
465
|
+
|
|
466
|
+
const metrics = await fetchSlowAnalytics(props.orgId);
|
|
467
|
+
|
|
468
|
+
// Streamed out-of-order and swapped in-place as soon as ready
|
|
469
|
+
return () => (
|
|
470
|
+
<div class="card">
|
|
471
|
+
<strong>{metrics.revenue}</strong> ({metrics.conversion} conversion)
|
|
472
|
+
</div>
|
|
473
|
+
);
|
|
474
|
+
}
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
---
|
|
478
|
+
|
|
479
|
+
## 2. Bidirectional NDJSON Server Streams (`server(async function* ...)`)
|
|
480
|
+
|
|
481
|
+
Need to stream LLM tokens, CSV import progress, build logs, or live ticker updates from your server? Pass an **`async function*`** to `server(...)` (or export `async function*` from `*.server.ts`):
|
|
482
|
+
|
|
483
|
+
- **Wire Protocol:** Streams `application/x-ndjson` frames over standard HTTP `fetch()` (works through every CDN, corporate proxy, Cloudflare Worker, and Vercel Function without WebSockets).
|
|
484
|
+
- **Zero Manual `ctx.refresh()`:** Each `yield` frame received by `for await` on the client automatically schedules a compiled DOM slot patch on the calling component!
|
|
485
|
+
- **End-to-End Cancellation Teardown:** If the user clicks a "Cancel" button (`break`), navigates away, or closes the browser tab, `c7t` aborts the `fetch()` request, Hono aborts `req.signal`, and `c7t` invokes `gen.return()` on the backend generator—running your server's `finally` block immediately to release database cursors or upstream AI streams!
|
|
486
|
+
|
|
487
|
+
### Real-World Example: Cancellable AI Assistant Stream
|
|
488
|
+
|
|
489
|
+
```tsx
|
|
490
|
+
import { server } from "@fierst/c7t";
|
|
491
|
+
import { req } from "@fierst/c7t/server";
|
|
492
|
+
|
|
493
|
+
export const streamCompletion = server(async function* (prompt: string) {
|
|
494
|
+
const upstream = await fetch("https://api.example.com/v1/chat/completions", {
|
|
495
|
+
method: "POST",
|
|
496
|
+
headers: {
|
|
497
|
+
Authorization: `Bearer ${process.env.AI_API_KEY}`,
|
|
498
|
+
"Content-Type": "application/json",
|
|
499
|
+
},
|
|
500
|
+
body: JSON.stringify({ prompt, stream: true }),
|
|
501
|
+
// Automatically aborts upstream LLM request when client breaks or unmounts!
|
|
502
|
+
signal: req.signal,
|
|
503
|
+
});
|
|
504
|
+
|
|
505
|
+
try {
|
|
506
|
+
// Simulated token chunks for illustration
|
|
507
|
+
const tokens = ["Generators ", "make ", "streaming ", "effortless."];
|
|
508
|
+
for (const token of tokens) {
|
|
509
|
+
await new Promise((r) => setTimeout(r, 80));
|
|
510
|
+
yield { token };
|
|
511
|
+
}
|
|
512
|
+
return { finishReason: "stop" as const };
|
|
513
|
+
} finally {
|
|
514
|
+
// Guaranteed to run on completion, error, OR client disconnect / `break`!
|
|
515
|
+
console.log("Cleaned up AI stream resources");
|
|
516
|
+
}
|
|
517
|
+
});
|
|
518
|
+
|
|
519
|
+
export default function* AiPlayground() {
|
|
520
|
+
let prompt = "Why generators?";
|
|
521
|
+
let answer = "";
|
|
522
|
+
let streaming = false;
|
|
523
|
+
let stopRequested = false;
|
|
524
|
+
|
|
525
|
+
return () => (
|
|
526
|
+
<section>
|
|
527
|
+
<form
|
|
528
|
+
onSubmit={async (e) => {
|
|
529
|
+
e.preventDefault();
|
|
530
|
+
if (streaming) return;
|
|
531
|
+
answer = "";
|
|
532
|
+
streaming = true;
|
|
533
|
+
stopRequested = false;
|
|
534
|
+
|
|
535
|
+
try {
|
|
536
|
+
for await (const chunk of streamCompletion(prompt)) {
|
|
537
|
+
answer += chunk.token; // Automatically updates DOM on every yielded token!
|
|
538
|
+
if (stopRequested) {
|
|
539
|
+
break; // Immediately aborts HTTP stream & triggers server `finally`!
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
} finally {
|
|
543
|
+
streaming = false;
|
|
544
|
+
}
|
|
545
|
+
}}
|
|
546
|
+
>
|
|
547
|
+
<input bind:value={prompt} disabled={streaming} />
|
|
548
|
+
{!streaming ? (
|
|
549
|
+
<button type="submit">Ask</button>
|
|
550
|
+
) : (
|
|
551
|
+
<button type="button" onClick={() => (stopRequested = true)}>
|
|
552
|
+
Stop Generating
|
|
553
|
+
</button>
|
|
554
|
+
)}
|
|
555
|
+
</form>
|
|
556
|
+
|
|
557
|
+
<output>{answer}</output>
|
|
558
|
+
</section>
|
|
559
|
+
);
|
|
560
|
+
}
|
|
561
|
+
```
|
|
562
|
+
|
|
563
|
+
---
|
|
564
|
+
|
|
565
|
+
## 3. Composable Multi-Step UI Workflows (`yield*`)
|
|
566
|
+
|
|
567
|
+
Combine Blokd's `yield*` UI sub-generators with `c7t` `server()` mutations to write complex multi-step user flows—confirmations, step-up 2FA prompts, or onboarding wizards—as linear, strongly typed functions with zero boolean-flag soup:
|
|
568
|
+
|
|
569
|
+
```tsx
|
|
570
|
+
import type { Ctx } from "@fierst/blokd";
|
|
571
|
+
import { server } from "@fierst/c7t";
|
|
572
|
+
|
|
573
|
+
const deleteWorkspace = server(async (workspaceId: string, totpCode: string) => {
|
|
574
|
+
// Verify TOTP & delete workspace on server
|
|
575
|
+
return { deletedId: workspaceId, verifiedWith: totpCode.length };
|
|
576
|
+
});
|
|
577
|
+
|
|
578
|
+
function* promptTotpCode(workspaceName: string): Generator<any, string | null, any> {
|
|
579
|
+
let code = "";
|
|
580
|
+
let decision: "confirm" | "cancel" | null = null;
|
|
581
|
+
|
|
582
|
+
while (decision === null) {
|
|
583
|
+
yield (
|
|
584
|
+
<div class="danger-modal" role="alertdialog">
|
|
585
|
+
<h3>Delete {workspaceName}?</h3>
|
|
586
|
+
<p>Enter your 6-digit authenticator code to confirm permanent deletion.</p>
|
|
587
|
+
<input bind:value={code} maxLength={6} placeholder="000000" />
|
|
588
|
+
<div class="actions">
|
|
589
|
+
<button type="button" onClick={() => (decision = "cancel")}>
|
|
590
|
+
Cancel
|
|
591
|
+
</button>
|
|
592
|
+
<button
|
|
593
|
+
type="button"
|
|
594
|
+
disabled={code.length !== 6}
|
|
595
|
+
onClick={() => (decision = "confirm")}
|
|
596
|
+
>
|
|
597
|
+
Permanently Delete
|
|
598
|
+
</button>
|
|
599
|
+
</div>
|
|
600
|
+
</div>
|
|
601
|
+
);
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
return decision === "confirm" ? code : null;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
export function* DangerZone(
|
|
608
|
+
props: { id: string; name: string },
|
|
609
|
+
ctx: Ctx<{ id: string; name: string }>,
|
|
610
|
+
) {
|
|
611
|
+
let confirming = false;
|
|
612
|
+
let deleted = false;
|
|
613
|
+
|
|
614
|
+
for (props of ctx) {
|
|
615
|
+
if (deleted) {
|
|
616
|
+
yield <p>Workspace deleted.</p>;
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
if (confirming) {
|
|
621
|
+
// Delegates rendering to `promptTotpCode` and resumes here with `string | null`!
|
|
622
|
+
const totp = yield* promptTotpCode(props.name);
|
|
623
|
+
confirming = false;
|
|
624
|
+
if (totp) {
|
|
625
|
+
await deleteWorkspace(props.id, totp);
|
|
626
|
+
deleted = true;
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
yield (
|
|
632
|
+
<button class="danger" onClick={() => (confirming = true)}>
|
|
633
|
+
Delete Workspace…
|
|
634
|
+
</button>
|
|
635
|
+
);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
```
|
|
639
|
+
|
|
640
|
+
---
|
|
641
|
+
|
|
642
|
+
# 04. Routing, Nested Layouts, URL State, and Webhooks
|
|
643
|
+
|
|
644
|
+
`c7t` discovers routes automatically from `src/routes/**` (configurable via `c7t({ routesDir })`). Standard HTML `<a href="/...">` tags drive client-side navigation with View Transitions—no `<Link>` wrapper component needed.
|
|
645
|
+
|
|
646
|
+
---
|
|
647
|
+
|
|
648
|
+
## 1. File-System Route Mapping
|
|
649
|
+
|
|
650
|
+
| File in `src/routes/` | Matched URL Pattern | Notes |
|
|
651
|
+
| --------------------------- | ------------------------------------------- | ------------------------------------------------------------ |
|
|
652
|
+
| `index.tsx` | `/` | Root home page |
|
|
653
|
+
| `pricing.tsx` | `/pricing` | Static segment (score `100` per segment) |
|
|
654
|
+
| `projects/index.tsx` | `/projects` | Directory index |
|
|
655
|
+
| `projects/[id].tsx` | `/projects/:id` | Dynamic parameter (`props.params.id`, score `10`) |
|
|
656
|
+
| `docs/[...slug].tsx` | `/docs/*` | Catch-all parameter (`props.params.slug`, score `1`) |
|
|
657
|
+
| `layout.tsx` | Wraps `/` and all descendants | Persistent root layout (`props.children`) |
|
|
658
|
+
| `(marketing)/layout.tsx` | Pathless layout group | Wraps `(marketing)/*` without adding `/marketing` to the URL |
|
|
659
|
+
| `(app)/dashboard/index.tsx` | `/dashboard` | Inherits both root `layout.tsx` and `(app)/layout.tsx` |
|
|
660
|
+
| `404.tsx` | Any unmatched route (or `throw notFound()`) | Rendered with HTTP `404` inside root `layout.tsx` |
|
|
661
|
+
| `error.tsx` | Root `<ErrorBoundary>` fallback | Catches uncaught SSR & client errors (`{ error, reset }`) |
|
|
662
|
+
| `api/stripe.ts` | `/api/stripe` | Server-only HTTP verb endpoint (`POST`, `GET`, etc.) |
|
|
663
|
+
|
|
664
|
+
> **Duplicate Route Protection:** If `(marketing)/about.tsx` and `(app)/about.tsx` both resolve to `/about`, `buildRoutes()` throws a clear build-time collision error naming both files.
|
|
665
|
+
|
|
666
|
+
---
|
|
667
|
+
|
|
668
|
+
## 2. Zero-Codegen Typed Route Params (`RouteProps<Path>`)
|
|
669
|
+
|
|
670
|
+
Use `RouteProps<"/projects/[id]/tasks/[taskId]">` to infer `props.params` purely at the TypeScript type level with zero generated `.d.ts` files:
|
|
671
|
+
|
|
672
|
+
```tsx
|
|
673
|
+
import { useRoute, type RouteProps } from "@fierst/c7t";
|
|
674
|
+
|
|
675
|
+
export default function* TaskDetailPage(props: RouteProps<"/projects/[id]/tasks/[taskId]">) {
|
|
676
|
+
// TypeScript infers: props.params = { id: string; taskId: string }
|
|
677
|
+
return () => (
|
|
678
|
+
<article>
|
|
679
|
+
<h1>
|
|
680
|
+
Project {props.params.id} — Task #{props.params.taskId}
|
|
681
|
+
</h1>
|
|
682
|
+
<p>Pathname: {props.pathname}</p>
|
|
683
|
+
</article>
|
|
684
|
+
);
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
// Deep child components can also read route state via `useRoute()`
|
|
688
|
+
export function Breadcrumb() {
|
|
689
|
+
const route = useRoute();
|
|
690
|
+
return <nav aria-label="Breadcrumb">Current path: {route.pathname}</nav>;
|
|
691
|
+
}
|
|
692
|
+
```
|
|
693
|
+
|
|
694
|
+
---
|
|
695
|
+
|
|
696
|
+
## 3. Persistent Nested & Pathless Group Layouts
|
|
697
|
+
|
|
698
|
+
Layouts render `{props.children}` inside a `<c7t-outlet>` boundary. When navigating from `/projects/alpha` to `/projects/beta`:
|
|
699
|
+
|
|
700
|
+
- **Shared ancestor layouts (`layout.tsx`, `projects/layout.tsx`) stay mounted**, preserving local `let` variables (e.g. sidebar filter text, scroll position, audio player state) and `provide()` context!
|
|
701
|
+
- **Outgoing child page generators dispose cleanly** (`ctx.signal` aborts in-flight requests and `finally` blocks run) before the incoming page mounts.
|
|
702
|
+
- **Cascading `prerender` & `csr` Subtree Defaults:** Any `layout.tsx` (including pathless `(marketing)/layout.tsx` groups!) can export `prerender = true | false` and `csr = "auto" | "islands" | true | false` to set defaults for every route in its folder without repeating exports per page.
|
|
703
|
+
|
|
704
|
+
```tsx
|
|
705
|
+
// src/routes/(app)/layout.tsx
|
|
706
|
+
import type { RouteProps } from "@fierst/c7t";
|
|
707
|
+
|
|
708
|
+
export default function* AppShellLayout(props: RouteProps) {
|
|
709
|
+
let sidebarCollapsed = false;
|
|
710
|
+
|
|
711
|
+
return () => (
|
|
712
|
+
<div class="workspace-grid" class:collapsed={sidebarCollapsed}>
|
|
713
|
+
<aside>
|
|
714
|
+
<button onClick={() => (sidebarCollapsed = !sidebarCollapsed)}>
|
|
715
|
+
{sidebarCollapsed ? "Expand" : "Collapse"}
|
|
716
|
+
</button>
|
|
717
|
+
<nav>
|
|
718
|
+
<a href="/dashboard">Dashboard</a>
|
|
719
|
+
<a href="/settings">Settings</a>
|
|
720
|
+
</nav>
|
|
721
|
+
</aside>
|
|
722
|
+
<div class="workspace-content">{props.children}</div>
|
|
723
|
+
</div>
|
|
724
|
+
);
|
|
725
|
+
}
|
|
726
|
+
```
|
|
727
|
+
|
|
728
|
+
---
|
|
729
|
+
|
|
730
|
+
## 4. Custom `404.tsx` and `error.tsx` Boundaries
|
|
731
|
+
|
|
732
|
+
Create `src/routes/404.tsx` and `src/routes/error.tsx` to handle missing routes and unexpected runtime exceptions automatically:
|
|
733
|
+
|
|
734
|
+
```tsx
|
|
735
|
+
// src/routes/404.tsx
|
|
736
|
+
import { head } from "@fierst/c7t";
|
|
737
|
+
|
|
738
|
+
export default function NotFoundPage(props: { pathname: string }) {
|
|
739
|
+
head({ title: "404 — Page Not Found" });
|
|
740
|
+
return (
|
|
741
|
+
<section>
|
|
742
|
+
<h1>Page not found</h1>
|
|
743
|
+
<p>
|
|
744
|
+
We couldn't find <code>{props.pathname}</code>.
|
|
745
|
+
</p>
|
|
746
|
+
<a href="/">Back to Dashboard</a>
|
|
747
|
+
</section>
|
|
748
|
+
);
|
|
749
|
+
}
|
|
750
|
+
```
|
|
751
|
+
|
|
752
|
+
```tsx
|
|
753
|
+
// src/routes/error.tsx
|
|
754
|
+
export default function GlobalErrorFallback(props: { error: unknown; reset: () => void }) {
|
|
755
|
+
const message = props.error instanceof Error ? props.error.message : "Unexpected error";
|
|
756
|
+
|
|
757
|
+
return (
|
|
758
|
+
<section role="alert" class="error-panel">
|
|
759
|
+
<h2>Something went wrong</h2>
|
|
760
|
+
<p>{message}</p>
|
|
761
|
+
<button onClick={props.reset}>Try Again</button>
|
|
762
|
+
</section>
|
|
763
|
+
);
|
|
764
|
+
}
|
|
765
|
+
```
|
|
766
|
+
|
|
767
|
+
---
|
|
768
|
+
|
|
769
|
+
## 5. Isomorphic Document Metadata (`head()`)
|
|
770
|
+
|
|
771
|
+
Call `head(...)` inline inside layouts and pages. During SSR, metadata merges outer-to-inner (child pages override parent layouts by `name` or `property`) and flushes inside `<head>` before `<body>` streams; during client navigation, `head()` updates `document.title` and `<meta>` / `<link rel="canonical">` tags in-place:
|
|
772
|
+
|
|
773
|
+
```tsx
|
|
774
|
+
import { head } from "@fierst/c7t";
|
|
775
|
+
|
|
776
|
+
export default function* BlogPostPage() {
|
|
777
|
+
const post = yield* getPost();
|
|
778
|
+
|
|
779
|
+
head({
|
|
780
|
+
title: `${post.title} — Fierst Engineering`,
|
|
781
|
+
description: post.summary,
|
|
782
|
+
canonical: `https://example.com/blog/${post.slug}`,
|
|
783
|
+
meta: [
|
|
784
|
+
{ property: "og:title", content: post.title },
|
|
785
|
+
{ property: "og:type", content: "article" },
|
|
786
|
+
{ name: "twitter:card", content: "summary_large_image" },
|
|
787
|
+
],
|
|
788
|
+
});
|
|
789
|
+
|
|
790
|
+
return () => (
|
|
791
|
+
<article>
|
|
792
|
+
<h1>{post.title}</h1>
|
|
793
|
+
</article>
|
|
794
|
+
);
|
|
795
|
+
}
|
|
796
|
+
```
|
|
797
|
+
|
|
798
|
+
---
|
|
799
|
+
|
|
800
|
+
## 6. Bindable URL Search Params (`searchParam()`)
|
|
801
|
+
|
|
802
|
+
`searchParam(key, defaultValue, opts?)` returns a reactive Blokd `Signal<T>` (`string`, `number`, or `boolean`) backed directly by the URL query string on both SSR and the client—so it plugs straight into `bind:value` and `bind:checked`!
|
|
803
|
+
|
|
804
|
+
- Writing its default value automatically **removes** the query key to keep URLs clean (`?q=` disappears when cleared!).
|
|
805
|
+
- Defaults to `replace: true` so typing into a search box doesn't spam browser Back history; pass `{ replace: false }` for discrete pagination steps.
|
|
806
|
+
|
|
807
|
+
```tsx
|
|
808
|
+
import { searchParam } from "@fierst/c7t";
|
|
809
|
+
|
|
810
|
+
export default function* DirectoryFilter() {
|
|
811
|
+
const q = searchParam("q", "");
|
|
812
|
+
const page = searchParam("page", 1, { replace: false });
|
|
813
|
+
const activeOnly = searchParam("active", false);
|
|
814
|
+
|
|
815
|
+
return () => (
|
|
816
|
+
<section>
|
|
817
|
+
{/* Two-way bound straight to `?q=...` and `?active=true`! */}
|
|
818
|
+
<input bind:value={q} placeholder="Filter members…" />
|
|
819
|
+
<label>
|
|
820
|
+
<input type="checkbox" bind:checked={activeOnly} />
|
|
821
|
+
Active only
|
|
822
|
+
</label>
|
|
823
|
+
|
|
824
|
+
<p>
|
|
825
|
+
Showing query "{q()}" (page {page()})
|
|
826
|
+
</p>
|
|
827
|
+
<button onClick={() => page.update((n) => n + 1)}>Next Page</button>
|
|
828
|
+
</section>
|
|
829
|
+
);
|
|
830
|
+
}
|
|
831
|
+
```
|
|
832
|
+
|
|
833
|
+
---
|
|
834
|
+
|
|
835
|
+
## 7. Hover / Focus Preloading & Escape Attributes
|
|
836
|
+
|
|
837
|
+
Out of the box, hovering (`pointerenter`) or tabbing (`focusin`) onto any internal `<a href="/...">` link preloads the destination route's JS module—and if the target route is SSG-prerendered, preloads its `/__c7t.json` receipt sidecar too—making click navigation instantaneous.
|
|
838
|
+
|
|
839
|
+
Control link behavior with two HTML attributes:
|
|
840
|
+
|
|
841
|
+
- `data-c7t-preload="off"` — Disable hover/focus preloading on a specific `<a href>` (e.g. a sign-out link).
|
|
842
|
+
- `data-c7t-reload` — Bypass the client router and perform a full browser document load.
|
|
843
|
+
|
|
844
|
+
Programmatic navigation is also available via `import { navigate } from "@fierst/c7t"`:
|
|
845
|
+
|
|
846
|
+
```ts
|
|
847
|
+
await navigate("/projects/alpha", { replace: false, transition: true });
|
|
848
|
+
```
|
|
849
|
+
|
|
850
|
+
---
|
|
851
|
+
|
|
852
|
+
## 8. File-System HTTP API & Webhook Endpoints
|
|
853
|
+
|
|
854
|
+
Export named HTTP verb functions (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`) from any file in `src/routes/**` to create raw Hono endpoints for Stripe/GitHub webhooks, OAuth callbacks, health checks, or RSS/XML feeds.
|
|
855
|
+
|
|
856
|
+
Files without a `default` UI component export are **100% excluded from the client browser bundle**:
|
|
857
|
+
|
|
858
|
+
```ts
|
|
859
|
+
// src/routes/api/webhooks/stripe.ts
|
|
860
|
+
import type { Context } from "hono";
|
|
861
|
+
import { cookies } from "@fierst/c7t/server";
|
|
862
|
+
|
|
863
|
+
export async function POST(c: Context) {
|
|
864
|
+
const signature = c.req.header("stripe-signature");
|
|
865
|
+
if (!signature) {
|
|
866
|
+
return c.json({ error: "Missing signature" }, 400);
|
|
867
|
+
}
|
|
868
|
+
const rawBody = await c.req.text();
|
|
869
|
+
// Verify webhook signature & process event...
|
|
870
|
+
return c.json({ received: true, bytes: rawBody.length });
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
export function GET(c: Context) {
|
|
874
|
+
const sid = cookies.get("sid") ?? null;
|
|
875
|
+
return c.json({ status: "healthy", authenticated: Boolean(sid) });
|
|
876
|
+
}
|
|
877
|
+
```
|
|
878
|
+
|
|
879
|
+
---
|
|
880
|
+
|
|
881
|
+
# 05. Authentication, Sessions, Environment Variables, and Security
|
|
882
|
+
|
|
883
|
+
`c7t` treats security as a zero-config baseline: signed `httpOnly` Web-Crypto sessions, ambient request context across SSR and RPCs, build-time secret stripping, CSRF verification, and production error masking all ship built-in with zero third-party auth dependencies.
|
|
884
|
+
|
|
885
|
+
---
|
|
886
|
+
|
|
887
|
+
## 1. Ambient `req` & `cookies` (`AsyncLocalStorage`)
|
|
888
|
+
|
|
889
|
+
Import `req` and `cookies` from `@fierst/c7t/server` inside any `server()` function, `*.server.ts` module, Hono middleware, or file-system API handler—without prop-drilling `(req, res)` through helper functions:
|
|
890
|
+
|
|
891
|
+
```ts
|
|
892
|
+
import { server } from "@fierst/c7t";
|
|
893
|
+
import { cookies, req } from "@fierst/c7t/server";
|
|
894
|
+
|
|
895
|
+
export const getClientDiagnostics = server(async () => {
|
|
896
|
+
const userAgent = req.headers.get("user-agent") ?? "unknown";
|
|
897
|
+
const theme = cookies.get("theme") ?? "system";
|
|
898
|
+
return { url: req.url, method: req.method, userAgent, theme };
|
|
899
|
+
});
|
|
900
|
+
|
|
901
|
+
export const setThemePreference = server(async (theme: "light" | "dark") => {
|
|
902
|
+
cookies.set("theme", theme, {
|
|
903
|
+
httpOnly: false,
|
|
904
|
+
sameSite: "Lax",
|
|
905
|
+
maxAge: 60 * 60 * 24 * 365,
|
|
906
|
+
});
|
|
907
|
+
return { theme };
|
|
908
|
+
});
|
|
909
|
+
```
|
|
910
|
+
|
|
911
|
+
---
|
|
912
|
+
|
|
913
|
+
## 2. Web-Crypto Signed Cookie Sessions (`createSession()`)
|
|
914
|
+
|
|
915
|
+
`createSession<T>()` uses the Web Standard `crypto.subtle` (`HMAC-SHA256`) API—running identically on Node.js, Cloudflare Workers, Vercel, and Bun with **zero npm dependencies**.
|
|
916
|
+
|
|
917
|
+
- Sets `httpOnly: true`, `sameSite: "Lax"`, and `secure: true` (automatically on `https://`) by default.
|
|
918
|
+
- Rejects tampered payloads or forged signatures in constant time via `crypto.subtle.verify()`.
|
|
919
|
+
- Supports **zero-downtime secret key rotation** by passing `secret: [currentSecret, previousSecret]`: new cookies sign with `currentSecret`, while existing user sessions signed with `previousSecret` continue verifying seamlessly until refreshed!
|
|
920
|
+
|
|
921
|
+
```ts
|
|
922
|
+
// src/lib/auth.server.ts
|
|
923
|
+
import { redirect, server, unauthorized } from "@fierst/c7t";
|
|
924
|
+
import { createSession } from "@fierst/c7t/server";
|
|
925
|
+
import * as v from "valibot";
|
|
926
|
+
|
|
927
|
+
export interface SessionData {
|
|
928
|
+
userId: string;
|
|
929
|
+
email: string;
|
|
930
|
+
role: "admin" | "member";
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
export const authSession = createSession<SessionData>({
|
|
934
|
+
name: "app_session",
|
|
935
|
+
// Rotate secrets without logging anyone out: [newKey, oldKey]
|
|
936
|
+
secret: [process.env.SESSION_SECRET ?? "dev-only-secret-at-least-32-chars-long!"],
|
|
937
|
+
maxAge: 60 * 60 * 24 * 7, // 7 days
|
|
938
|
+
});
|
|
939
|
+
|
|
940
|
+
export const getCurrentUser = server(async () => {
|
|
941
|
+
return authSession.get(); // SessionData | null
|
|
942
|
+
});
|
|
943
|
+
|
|
944
|
+
export const login = server(
|
|
945
|
+
v.object({
|
|
946
|
+
email: v.pipe(v.string(), v.email()),
|
|
947
|
+
password: v.pipe(v.string(), v.minLength(8)),
|
|
948
|
+
}),
|
|
949
|
+
async ({ email, password }) => {
|
|
950
|
+
// Replace with real password hash check (e.g. Scrypt / Argon2 / WebCrypto PBKDF2)
|
|
951
|
+
if (password !== "correct-horse-battery") {
|
|
952
|
+
throw unauthorized("Invalid email or password");
|
|
953
|
+
}
|
|
954
|
+
await authSession.set({
|
|
955
|
+
userId: "usr_01",
|
|
956
|
+
email,
|
|
957
|
+
role: "admin",
|
|
958
|
+
});
|
|
959
|
+
return { email };
|
|
960
|
+
},
|
|
961
|
+
);
|
|
962
|
+
|
|
963
|
+
export const logout = server(async () => {
|
|
964
|
+
authSession.clear();
|
|
965
|
+
throw redirect("/login", 303);
|
|
966
|
+
});
|
|
967
|
+
```
|
|
968
|
+
|
|
969
|
+
---
|
|
970
|
+
|
|
971
|
+
## 3. Inline Auth Gates vs `redirect()`
|
|
972
|
+
|
|
973
|
+
With `c7t`, you can protect routes in two complementary ways:
|
|
974
|
+
|
|
975
|
+
### Pattern A: HTTP Redirect (`throw redirect("/login")`)
|
|
976
|
+
|
|
977
|
+
When thrown before the first yield in a route component (or inside a `yield*` `server()` query), `createServer()` intercepts `RedirectSignal` and returns a genuine **HTTP `302` redirect** on SSR—or navigates via the client router when triggered from an RPC:
|
|
978
|
+
|
|
979
|
+
```tsx
|
|
980
|
+
import { redirect } from "@fierst/c7t";
|
|
981
|
+
import { getCurrentUser } from "../lib/auth.server";
|
|
982
|
+
|
|
983
|
+
export default function* BillingPage() {
|
|
984
|
+
const user = yield* getCurrentUser();
|
|
985
|
+
if (!user) throw redirect("/login");
|
|
986
|
+
|
|
987
|
+
return () => <h1>Billing for {user.email}</h1>;
|
|
988
|
+
}
|
|
989
|
+
```
|
|
990
|
+
|
|
991
|
+
### Pattern B: Zero-Redirect Inline Auth Gate
|
|
992
|
+
|
|
993
|
+
Render `<LoginScreen />` directly at the protected URL (`return () => user ? <Dashboard /> : <LoginForm onSuccess={(u) => (user = u)} />`) so signing in transitions immediately to the dashboard without a round-trip redirect!
|
|
994
|
+
|
|
995
|
+
---
|
|
996
|
+
|
|
997
|
+
## 4. Custom Hono Middleware & `RequestContext` Augmentation
|
|
998
|
+
|
|
999
|
+
When you want global middleware (request logging, rate limiting, CORS, or populating `req.user` across **both** SSR page loads and `/_c7t/rpc/*` calls), add `src/server.ts`. `@fierst/c7t/vite` automatically wires your discovered `src/routes/**` into `createServer()`:
|
|
1000
|
+
|
|
1001
|
+
```ts
|
|
1002
|
+
// src/server.ts
|
|
1003
|
+
import { createServer, req } from "@fierst/c7t/server";
|
|
1004
|
+
import { authSession, type SessionData } from "./lib/auth.server";
|
|
1005
|
+
|
|
1006
|
+
// Augment `RequestContext` once — `req.user` is now typed everywhere!
|
|
1007
|
+
declare module "@fierst/c7t/server" {
|
|
1008
|
+
interface RequestContext {
|
|
1009
|
+
user: SessionData | null;
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
export default createServer({
|
|
1014
|
+
middleware: [
|
|
1015
|
+
async (c, next) => {
|
|
1016
|
+
req.user = await authSession.get();
|
|
1017
|
+
await next();
|
|
1018
|
+
},
|
|
1019
|
+
],
|
|
1020
|
+
configure(app) {
|
|
1021
|
+
// Optional raw Hono escape hatch (custom sub-apps, OpenAPI docs, metrics)
|
|
1022
|
+
app.get("/healthz", (c) => c.json({ ok: true }));
|
|
1023
|
+
},
|
|
1024
|
+
});
|
|
1025
|
+
```
|
|
1026
|
+
|
|
1027
|
+
---
|
|
1028
|
+
|
|
1029
|
+
## 5. Isomorphic Environment Validation (`defineEnv()`)
|
|
1030
|
+
|
|
1031
|
+
`defineEnv()` validates `server` and `public` schemas using Standard Schema v1 across **Cloudflare Workers per-request `req.env`**, **Node/Bun `process.env`**, and **Vite `import.meta.env`**—and throws immediately if client code ever touches a server secret:
|
|
1032
|
+
|
|
1033
|
+
```ts
|
|
1034
|
+
// src/env.ts
|
|
1035
|
+
import { defineEnv } from "@fierst/c7t";
|
|
1036
|
+
import * as v from "valibot";
|
|
1037
|
+
|
|
1038
|
+
export const env = defineEnv({
|
|
1039
|
+
server: {
|
|
1040
|
+
DATABASE_URL: v.pipe(v.string(), v.url()),
|
|
1041
|
+
STRIPE_SECRET_KEY: v.pipe(v.string(), v.startsWith("sk_")),
|
|
1042
|
+
},
|
|
1043
|
+
public: {
|
|
1044
|
+
PUBLIC_APP_NAME: v.optional(v.string(), "Construct"),
|
|
1045
|
+
},
|
|
1046
|
+
});
|
|
1047
|
+
|
|
1048
|
+
// Safe anywhere (SSR & Browser): env.PUBLIC_APP_NAME
|
|
1049
|
+
// Safe on Server; throws "[c7t] Attempted to access server-only environment variable..." in Browser: env.STRIPE_SECRET_KEY
|
|
1050
|
+
```
|
|
1051
|
+
|
|
1052
|
+
---
|
|
1053
|
+
|
|
1054
|
+
## 6. Built-In Security Protections
|
|
1055
|
+
|
|
1056
|
+
1. **Cross-Site Request Forgery (CSRF) Guard:** Every `POST /_c7t/rpc/:id` call checks `Sec-Fetch-Site` (blocking `cross-site`) and verifies `Origin` against the request's origin (blocking mismatched or `"null"` origins with HTTP `403`).
|
|
1057
|
+
2. **SHA-256 Production RPC Hashing:** During `c7t build`, internal file paths and function names are hashed (`/_c7t/rpc/c7t_a1b2c3d4e5f6`) so production bundles never expose your source directory layout.
|
|
1058
|
+
3. **Production `500` Error Sanitization:** When `NODE_ENV === "production"`, unexpected exceptions thrown inside RPC or NDJSON streaming handlers are logged on the server (`[c7t RPC error]`) and masked on the wire as `"Internal Server Error"` (`500`), while intentional `ValidationError` (`400`), `HttpStatusError` (`unauthorized()`, `forbidden()`, `notFound()`, `httpError()`), and `RedirectSignal` messages pass through intact.
|
|
1059
|
+
4. **Compiler Server-Import Guard:** Importing runtime bindings from `@fierst/c7t/server` (`req`, `cookies`, `createSession`) outside a `server(...)` block in a client-bundled `.tsx` file fails the build immediately with an explicit error naming the leaked identifier.
|
|
1060
|
+
|
|
1061
|
+
---
|
|
1062
|
+
|
|
1063
|
+
# 06. Static Site Generation (SSG) and Deployment Adapters
|
|
1064
|
+
|
|
1065
|
+
`c7t` unifies dynamic SSR, hybrid per-route prerendering, 0-KB JS static content pages, and 100% serverless static sites under one architecture—with zero code rewrites when moving between hosting providers.
|
|
1066
|
+
|
|
1067
|
+
---
|
|
1068
|
+
|
|
1069
|
+
## 1. Hybrid Per-Route Prerendering (`export const prerender`)
|
|
1070
|
+
|
|
1071
|
+
In any dynamic SSR application (`node`, `cloudflare`, `vercel`, `bun`), mark marketing pages, documentation, or blog posts with `export const prerender` to render them once during `c7t build`:
|
|
1072
|
+
|
|
1073
|
+
### Static Route (`prerender = true`)
|
|
1074
|
+
|
|
1075
|
+
```tsx
|
|
1076
|
+
// src/routes/pricing.tsx
|
|
1077
|
+
import { head, server } from "@fierst/c7t";
|
|
1078
|
+
|
|
1079
|
+
export const prerender = true;
|
|
1080
|
+
|
|
1081
|
+
const loadPricingTiers = server(async () => [
|
|
1082
|
+
{ name: "Starter", price: "\$0" },
|
|
1083
|
+
{ name: "Pro", price: "\$29" },
|
|
1084
|
+
]);
|
|
1085
|
+
|
|
1086
|
+
export default function* PricingPage() {
|
|
1087
|
+
const tiers = yield* loadPricingTiers();
|
|
1088
|
+
head({ title: "Pricing" });
|
|
1089
|
+
|
|
1090
|
+
return () => (
|
|
1091
|
+
<section>
|
|
1092
|
+
<h1>Pricing</h1>
|
|
1093
|
+
<ul>
|
|
1094
|
+
{tiers.map((t) => (
|
|
1095
|
+
<li key={t.name}>
|
|
1096
|
+
{t.name}: {t.price}
|
|
1097
|
+
</li>
|
|
1098
|
+
))}
|
|
1099
|
+
</ul>
|
|
1100
|
+
</section>
|
|
1101
|
+
);
|
|
1102
|
+
}
|
|
1103
|
+
```
|
|
1104
|
+
|
|
1105
|
+
### Dynamic Parameterized Route (`prerender = async () => [...]`)
|
|
1106
|
+
|
|
1107
|
+
Export an async `prerender` function returning parameter records (or full URL strings). `@fierst/c7t/vite` runs `prerender()` at build time and strips its body + server imports (`node:fs`, CMS SDKs) from the browser bundle automatically!
|
|
1108
|
+
|
|
1109
|
+
```tsx
|
|
1110
|
+
// src/routes/blog/[slug].tsx
|
|
1111
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
1112
|
+
import { head, server, type RouteProps } from "@fierst/c7t";
|
|
1113
|
+
|
|
1114
|
+
export async function prerender() {
|
|
1115
|
+
const files = await readdir("./content/blog");
|
|
1116
|
+
return files.filter((f) => f.endsWith(".md")).map((f) => ({ slug: f.replace(/\.md$/, "") }));
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
const getPost = server(async (slug: string) => {
|
|
1120
|
+
const body = await readFile(`./content/blog/${slug}.md`, "utf-8");
|
|
1121
|
+
return { slug, body };
|
|
1122
|
+
});
|
|
1123
|
+
|
|
1124
|
+
export default function* BlogPost(props: RouteProps<"/blog/[slug]">) {
|
|
1125
|
+
const post = yield* getPost(props.params.slug);
|
|
1126
|
+
head({ title: post.slug });
|
|
1127
|
+
return () => <article>{post.body}</article>;
|
|
1128
|
+
}
|
|
1129
|
+
```
|
|
1130
|
+
|
|
1131
|
+
### How `__c7t.json` Static Receipt Sidecars Work
|
|
1132
|
+
|
|
1133
|
+
For every prerendered route (e.g. `/blog/hello`), `c7t build` writes **two** static files into `dist/client/`:
|
|
1134
|
+
|
|
1135
|
+
1. `dist/client/blog/hello/index.html` — Served directly from CDN/disk on initial page visits with embedded State Receipts.
|
|
1136
|
+
2. `dist/client/blog/hello/__c7t.json` — A tiny JSON State Receipt sidecar. When a user navigates from `/` to `/blog/hello` via `<a href="/blog/hello">`, the client router fetches `/blog/hello/__c7t.json` from the static CDN and resolves `yield* getPost("hello")` synchronously in **0 server RPCs**!
|
|
1137
|
+
|
|
1138
|
+
---
|
|
1139
|
+
|
|
1140
|
+
## 2. Automatic Zero-JS Pages (`csr: "auto"`) & Cascading Route Defaults
|
|
1141
|
+
|
|
1142
|
+
Out of the box, `c7t` defaults to **`csr: "auto"`** across every route—meaning **you almost never need to write `export const csr = false`!**
|
|
1143
|
+
|
|
1144
|
+
### How `csr` Modes Work
|
|
1145
|
+
|
|
1146
|
+
| `csr` Value | Behavior |
|
|
1147
|
+
| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1148
|
+
| **`"auto"`** _(Universal Default)_ | Inspects what actually rendered on SSR: if **0 `<blokd-island>`s** rendered (plain stateless `function` layout + page), `c7t` automatically emits **0 `<script>` tags (0.00 kB JS)**. If **1+ `<blokd-island>`s** rendered (`function*`, `onClick`, `bind:*`), `c7t` automatically attaches the lazy-revival + nested router bootstrap. |
|
|
1149
|
+
| **`"islands"`** _(Astro-style MPA Mode)_ | Emits **0.00 kB JS** when 0 islands render, and loads **only** the ~1.3 kB island + State Receipt loader (no SPA router bundle) when 1+ islands render—using native browser MPA navigation on `<a href>`. |
|
|
1150
|
+
| **`true`** | Always include the client SPA router + lazy revival bootstrap, even on purely stateless pages. |
|
|
1151
|
+
| **`false`** | Strict 0-JS lock — omit all island markers and `<script>` tags even if a stateful component rendered. |
|
|
1152
|
+
|
|
1153
|
+
### Cascading `prerender` & `csr` Inheritance (`vite.config.ts` -> `layout.tsx` -> `route.tsx`)
|
|
1154
|
+
|
|
1155
|
+
Both `prerender` and `csr` cascade cleanly from **project config -> ancestor `layout.tsx` -> leaf `route.tsx`**, so you never repeat flags across dozens of files:
|
|
1156
|
+
|
|
1157
|
+
1. **Pure Static Marketing / Docs Site (`staticAdapter()`):**
|
|
1158
|
+
- `staticAdapter()` automatically sets the site-wide default to `prerender: true`, while `csr: "auto"` emits **0 KB JS** on every static page and wakes `function*` islands automatically—**zero flags needed in any route file!**
|
|
1159
|
+
2. **Marketing-Heavy Hybrid Site (`c7t({ prerender: true, csr: "islands" })`):**
|
|
1160
|
+
- Every static route prerenders with 0-JS-by-default MPA islands, and your 1–2 live dynamic routes simply opt out with one line:
|
|
1161
|
+
```tsx
|
|
1162
|
+
// src/routes/portal.tsx — stays live SSR while the rest of the site prerenders!
|
|
1163
|
+
export const prerender = false;
|
|
1164
|
+
export const csr = true;
|
|
1165
|
+
```
|
|
1166
|
+
3. **Mixed SaaS + Marketing Monolith via Pathless Group Layouts:**
|
|
1167
|
+
- Set `export const prerender = true; export const csr = "islands";` once inside `src/routes/(marketing)/layout.tsx`, and every page inside `(marketing)/` becomes static + 0-JS-unless-interactive, while `src/routes/(app)/layout.tsx` stays live dynamic SSR + SPA!
|
|
1168
|
+
|
|
1169
|
+
```tsx
|
|
1170
|
+
// src/routes/terms.tsx — 0 flags needed!
|
|
1171
|
+
// Plain `function` + stateless layout => 0 <blokd-island>s => 0 <script> tags emitted automatically!
|
|
1172
|
+
export default function TermsOfService() {
|
|
1173
|
+
return (
|
|
1174
|
+
<main>
|
|
1175
|
+
<h1>Terms of Service</h1>
|
|
1176
|
+
<p>100% pure HTML & CSS — zero script tags emitted automatically.</p>
|
|
1177
|
+
</main>
|
|
1178
|
+
);
|
|
1179
|
+
}
|
|
1180
|
+
```
|
|
1181
|
+
|
|
1182
|
+
---
|
|
1183
|
+
|
|
1184
|
+
## 3. Prerendering `sitemap.xml`, `rss.xml`, & Broken-Link Detection
|
|
1185
|
+
|
|
1186
|
+
- **Static Non-HTML Endpoints:** Add `export const prerender = true` to any file-system `GET` route (such as `src/routes/sitemap.xml.ts` or `src/routes/rss.xml.ts`) to emit raw static `.xml` / `.txt` / `.json` files into `dist/client/` during `c7t build`!
|
|
1187
|
+
- **Automatic `<a href>` Crawler:** `prerenderApp()` crawls internal `<a href="/...">` links in rendered HTML automatically and fails the build (`onBrokenLink: "error"` by default) if an internal link points to a broken `404` URL.
|
|
1188
|
+
- **Build-Time Cookie Guardrail:** Calling `cookies.get()`, `cookies.set()`, or `session.get()` while prerendering a static route throws an immediate, descriptive build-time error so per-user data can never be accidentally baked into shared static HTML.
|
|
1189
|
+
|
|
1190
|
+
---
|
|
1191
|
+
|
|
1192
|
+
## 4. Official Deployment Adapters
|
|
1193
|
+
|
|
1194
|
+
Configure your target adapter in `vite.config.ts` (or override on the CLI via `c7t build --adapter=<name>`):
|
|
1195
|
+
|
|
1196
|
+
### A. Node.js (`@fierst/c7t/node` — Default)
|
|
1197
|
+
|
|
1198
|
+
Builds a standalone, zero-dependency Node HTTP server (`dist/server/start.mjs`) that serves `dist/client` with `Cache-Control: public, max-age=31536000, immutable` on `/assets/*` and streams SSR + NDJSON RPCs:
|
|
1199
|
+
|
|
1200
|
+
```ts
|
|
1201
|
+
// vite.config.ts
|
|
1202
|
+
import { defineConfig } from "vite-plus";
|
|
1203
|
+
import c7t from "@fierst/c7t/vite";
|
|
1204
|
+
import { nodeAdapter } from "@fierst/c7t/node";
|
|
1205
|
+
|
|
1206
|
+
export default defineConfig({
|
|
1207
|
+
plugins: [c7t({ adapter: nodeAdapter({ port: 3000 }) })],
|
|
1208
|
+
});
|
|
1209
|
+
```
|
|
1210
|
+
|
|
1211
|
+
Run in production (even in a minimal Docker image without `node_modules`—`dist/` is self-contained!):
|
|
1212
|
+
|
|
1213
|
+
```bash
|
|
1214
|
+
c7t build
|
|
1215
|
+
PORT=8080 node dist/server/start.mjs
|
|
1216
|
+
```
|
|
1217
|
+
|
|
1218
|
+
### B. Cloudflare Workers (`@fierst/c7t/cloudflare`)
|
|
1219
|
+
|
|
1220
|
+
Emits `dist/worker.mjs` + `dist/client` static assets wired through Cloudflare Workers Static Assets (`env.ASSETS`) before falling through to edge SSR and streaming RPCs:
|
|
1221
|
+
|
|
1222
|
+
```ts
|
|
1223
|
+
// vite.config.ts
|
|
1224
|
+
import { defineConfig } from "vite-plus";
|
|
1225
|
+
import c7t from "@fierst/c7t/vite";
|
|
1226
|
+
import { cloudflarePreset } from "@fierst/c7t/cloudflare";
|
|
1227
|
+
|
|
1228
|
+
export default defineConfig({
|
|
1229
|
+
plugins: [c7t({ adapter: cloudflarePreset({ assetsBinding: "ASSETS" }) })],
|
|
1230
|
+
});
|
|
1231
|
+
```
|
|
1232
|
+
|
|
1233
|
+
Minimal `wrangler.jsonc`:
|
|
1234
|
+
|
|
1235
|
+
```jsonc
|
|
1236
|
+
{
|
|
1237
|
+
"name": "my-c7t-app",
|
|
1238
|
+
"main": "dist/worker.mjs",
|
|
1239
|
+
"compatibility_date": "2026-01-01",
|
|
1240
|
+
"compatibility_flags": ["nodejs_als"],
|
|
1241
|
+
"assets": {
|
|
1242
|
+
"directory": "dist/client",
|
|
1243
|
+
"binding": "ASSETS",
|
|
1244
|
+
},
|
|
1245
|
+
}
|
|
1246
|
+
```
|
|
1247
|
+
|
|
1248
|
+
### C. Vercel (`@fierst/c7t/vercel` — Build Output API v3)
|
|
1249
|
+
|
|
1250
|
+
Emits a ready-to-deploy `.vercel/output` directory (`config.json` v3 + `static/` CDN assets/SSG sidecars + `functions/index.func` Web `fetch` handler):
|
|
1251
|
+
|
|
1252
|
+
```ts
|
|
1253
|
+
// vite.config.ts
|
|
1254
|
+
import { defineConfig } from "vite-plus";
|
|
1255
|
+
import c7t from "@fierst/c7t/vite";
|
|
1256
|
+
import { vercelAdapter } from "@fierst/c7t/vercel";
|
|
1257
|
+
|
|
1258
|
+
export default defineConfig({
|
|
1259
|
+
plugins: [
|
|
1260
|
+
c7t({
|
|
1261
|
+
adapter: vercelAdapter({
|
|
1262
|
+
runtime: "nodejs22.x",
|
|
1263
|
+
regions: ["iad1"],
|
|
1264
|
+
}),
|
|
1265
|
+
}),
|
|
1266
|
+
],
|
|
1267
|
+
});
|
|
1268
|
+
```
|
|
1269
|
+
|
|
1270
|
+
Deploy with `c7t build && vercel deploy --prebuilt`.
|
|
1271
|
+
|
|
1272
|
+
### D. Bun (`@fierst/c7t/bun`)
|
|
1273
|
+
|
|
1274
|
+
Emits `dist/server/start.bun.mjs` powered by `Bun.serve()` and zero-copy `Bun.file()` static/SSG serving:
|
|
1275
|
+
|
|
1276
|
+
```ts
|
|
1277
|
+
// vite.config.ts
|
|
1278
|
+
import { defineConfig } from "vite-plus";
|
|
1279
|
+
import c7t from "@fierst/c7t/vite";
|
|
1280
|
+
import { bunAdapter } from "@fierst/c7t/bun";
|
|
1281
|
+
|
|
1282
|
+
export default defineConfig({
|
|
1283
|
+
plugins: [c7t({ adapter: bunAdapter({ port: 3000 }) })],
|
|
1284
|
+
});
|
|
1285
|
+
```
|
|
1286
|
+
|
|
1287
|
+
Run with `c7t build && bun dist/server/start.bun.mjs`.
|
|
1288
|
+
|
|
1289
|
+
### E. Pure Static Site Hosting (`@fierst/c7t/static`)
|
|
1290
|
+
|
|
1291
|
+
Prerenders every route (`mode: "all"`), crawls internal links, writes `__c7t.json` SPA sidecars, generates `dist/client/404.html` from `src/routes/404.tsx`, and removes `dist/server`—ready for GitHub Pages, Cloudflare Pages, Netlify, or S3:
|
|
1292
|
+
|
|
1293
|
+
```ts
|
|
1294
|
+
// vite.config.ts
|
|
1295
|
+
import { defineConfig } from "vite-plus";
|
|
1296
|
+
import c7t from "@fierst/c7t/vite";
|
|
1297
|
+
import { staticAdapter } from "@fierst/c7t/static";
|
|
1298
|
+
|
|
1299
|
+
export default defineConfig({
|
|
1300
|
+
plugins: [
|
|
1301
|
+
c7t({
|
|
1302
|
+
adapter: staticAdapter({
|
|
1303
|
+
fallback: "404.html",
|
|
1304
|
+
onBrokenLink: "error",
|
|
1305
|
+
}),
|
|
1306
|
+
}),
|
|
1307
|
+
],
|
|
1308
|
+
});
|
|
1309
|
+
```
|
|
1310
|
+
|
|
1311
|
+
---
|
|
1312
|
+
|
|
1313
|
+
# 07. Databases, `defineDb()`, and Drizzle ORM
|
|
1314
|
+
|
|
1315
|
+
`@fierst/c7t` keeps its core runtime 100% database-agnostic while providing a first-class paved road for SQL databases through two pieces:
|
|
1316
|
+
|
|
1317
|
+
1. **`defineDb()` (`@fierst/c7t/server`):** A zero-dependency, lazy database proxy that seamlessly bridges Node/Bun connection pools (`process.env.DATABASE_URL`) and Cloudflare Workers per-request bindings (`req.env.DB` D1 / Hyperdrive) without passing `db` arguments through every function.
|
|
1318
|
+
2. **`c7t create --db=sqlite|postgres|d1`:** Opt-in project scaffolding powered by **[Drizzle ORM](https://orm.drizzle.team)** + **`drizzle-valibot`**, turning a single SQL table definition into your database schema, TypeScript row types, and `server(Schema, fn)` Standard Schema v1 validator!
|
|
1319
|
+
|
|
1320
|
+
---
|
|
1321
|
+
|
|
1322
|
+
## 1. Scaffold a Project with Drizzle (`--db`)
|
|
1323
|
+
|
|
1324
|
+
Choose your database target when scaffolding a project (omit `--db` if you don't need a database):
|
|
1325
|
+
|
|
1326
|
+
```bash
|
|
1327
|
+
# Local SQLite / Turso / LibSQL (zero native C++ compile — works everywhere)
|
|
1328
|
+
npx @fierst/c7t my-app --db=sqlite
|
|
1329
|
+
|
|
1330
|
+
# PostgreSQL / Neon / Supabase
|
|
1331
|
+
npx @fierst/c7t my-app --db=postgres
|
|
1332
|
+
|
|
1333
|
+
# Cloudflare Workers D1 (auto-configures cloudflarePreset() + wrangler.jsonc)
|
|
1334
|
+
npx @fierst/c7t my-app --db=d1
|
|
1335
|
+
```
|
|
1336
|
+
|
|
1337
|
+
Push your initial schema and launch the dev server + visual database studio:
|
|
1338
|
+
|
|
1339
|
+
```bash
|
|
1340
|
+
cd my-app
|
|
1341
|
+
npm install
|
|
1342
|
+
npm run db:push # Push src/db/schema.ts directly to your database
|
|
1343
|
+
npm run dev # Start Construct at http://localhost:5173
|
|
1344
|
+
npm run db:studio # Optional: inspect tables in Drizzle Studio
|
|
1345
|
+
```
|
|
1346
|
+
|
|
1347
|
+
---
|
|
1348
|
+
|
|
1349
|
+
## 2. How `defineDb()` Solves Singleton Pools & Edge Bindings
|
|
1350
|
+
|
|
1351
|
+
In traditional frameworks, switching from Node/Bun (where you want **one module-level connection pool** reused across requests) to Cloudflare Workers (where D1 and Hyperdrive bindings are injected **per request** on `env.DB` inside `fetch(req, env)`) forces you to refactor every helper function to accept `(db, ...)` as an argument.
|
|
1352
|
+
|
|
1353
|
+
`defineDb(factory, options?)` eliminates that split using `c7t`'s `AsyncLocalStorage` request store:
|
|
1354
|
+
|
|
1355
|
+
- **Lazy Initialization:** Importing `db` at module top-level opens **zero connections** until a query actually runs—keeping build-time route discovery and edge cold starts instantaneous.
|
|
1356
|
+
- **Smart `scope: "auto"` Caching (Default):**
|
|
1357
|
+
- When running on Node.js, Bun, or Vercel against `process.env`, `defineDb()` initializes your pool once and reuses the singleton across requests.
|
|
1358
|
+
- When running on Cloudflare Workers with request bindings (`req.env.DB`), `defineDb()` caches the Drizzle wrapper in a `WeakMap` keyed by `req.env`—isolating bindings cleanly with zero per-query allocation overhead.
|
|
1359
|
+
- **Private-Field Safe:** Method accesses bind the underlying client (`Reflect.get` + `.bind()`), so native classes using ES `#private` fields (such as Node's built-in `node:sqlite` `DatabaseSync`) work out of the box.
|
|
1360
|
+
|
|
1361
|
+
### Example A: SQLite / LibSQL / Turso (`--db=sqlite`)
|
|
1362
|
+
|
|
1363
|
+
```ts
|
|
1364
|
+
// src/db/index.ts
|
|
1365
|
+
import { createClient } from "@libsql/client";
|
|
1366
|
+
import { drizzle } from "drizzle-orm/libsql";
|
|
1367
|
+
import { defineDb } from "@fierst/c7t/server";
|
|
1368
|
+
import * as schema from "./schema";
|
|
1369
|
+
|
|
1370
|
+
export const db = defineDb((env) => {
|
|
1371
|
+
const client = createClient({
|
|
1372
|
+
url: env.DATABASE_URL ?? "file:local.db",
|
|
1373
|
+
authToken: env.DATABASE_AUTH_TOKEN,
|
|
1374
|
+
});
|
|
1375
|
+
return drizzle(client, { schema });
|
|
1376
|
+
});
|
|
1377
|
+
|
|
1378
|
+
export * from "./schema";
|
|
1379
|
+
```
|
|
1380
|
+
|
|
1381
|
+
### Example B: Cloudflare Workers D1 (`--db=d1`)
|
|
1382
|
+
|
|
1383
|
+
```ts
|
|
1384
|
+
// src/db/index.ts
|
|
1385
|
+
import { drizzle } from "drizzle-orm/d1";
|
|
1386
|
+
import { defineDb } from "@fierst/c7t/server";
|
|
1387
|
+
import * as schema from "./schema";
|
|
1388
|
+
|
|
1389
|
+
export const db = defineDb((env) => {
|
|
1390
|
+
if (!env.DB) throw new Error('Missing Cloudflare D1 binding "DB"');
|
|
1391
|
+
return drizzle(env.DB, { schema });
|
|
1392
|
+
});
|
|
1393
|
+
|
|
1394
|
+
export * from "./schema";
|
|
1395
|
+
```
|
|
1396
|
+
|
|
1397
|
+
---
|
|
1398
|
+
|
|
1399
|
+
## 3. Single Source of Truth: SQL Table -> Standard Schema -> `server()`
|
|
1400
|
+
|
|
1401
|
+
Because `drizzle-valibot` (and `drizzle-zod`) implement **Standard Schema v1**, `createInsertSchema(table)` passes directly into `server(Schema, fn)`—giving you SQL constraints, runtime HTTP `400` validation, TypeScript inference, and `err.fields` form errors from **one** schema definition:
|
|
1402
|
+
|
|
1403
|
+
```ts
|
|
1404
|
+
// src/db/schema.ts
|
|
1405
|
+
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
|
1406
|
+
import { createInsertSchema } from "drizzle-valibot";
|
|
1407
|
+
import * as v from "valibot";
|
|
1408
|
+
|
|
1409
|
+
export const projects = sqliteTable("projects", {
|
|
1410
|
+
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
1411
|
+
name: text("name").notNull(),
|
|
1412
|
+
slug: text("slug").notNull().unique(),
|
|
1413
|
+
createdAt: integer("created_at", { mode: "timestamp" })
|
|
1414
|
+
.notNull()
|
|
1415
|
+
.$defaultFn(() => new Date()),
|
|
1416
|
+
});
|
|
1417
|
+
|
|
1418
|
+
export const InsertProjectSchema = createInsertSchema(projects, {
|
|
1419
|
+
name: v.pipe(v.string(), v.trim(), v.minLength(2, "Name must be at least 2 characters")),
|
|
1420
|
+
slug: v.pipe(v.string(), v.regex(/^[a-z0-9-]+$/, "Use lowercase letters, numbers, and hyphens")),
|
|
1421
|
+
});
|
|
1422
|
+
```
|
|
1423
|
+
|
|
1424
|
+
Use it directly inside a colocated route (Oxc strips `drizzle-orm` and `../db` from the browser bundle automatically):
|
|
1425
|
+
|
|
1426
|
+
```tsx
|
|
1427
|
+
// src/routes/projects/index.tsx
|
|
1428
|
+
import { desc } from "drizzle-orm";
|
|
1429
|
+
import { head, server, ValidationError } from "@fierst/c7t";
|
|
1430
|
+
import { db, InsertProjectSchema, projects } from "../../db";
|
|
1431
|
+
|
|
1432
|
+
export const listProjects = server(async () => {
|
|
1433
|
+
return db.select().from(projects).orderBy(desc(projects.createdAt));
|
|
1434
|
+
});
|
|
1435
|
+
|
|
1436
|
+
export const createProject = server(InsertProjectSchema, async (input) => {
|
|
1437
|
+
const [created] = await db
|
|
1438
|
+
.insert(projects)
|
|
1439
|
+
.values({ name: input.name, slug: input.slug })
|
|
1440
|
+
.returning();
|
|
1441
|
+
return created;
|
|
1442
|
+
});
|
|
1443
|
+
|
|
1444
|
+
export default function* ProjectsPage() {
|
|
1445
|
+
let rows = yield* listProjects();
|
|
1446
|
+
let name = "";
|
|
1447
|
+
let slug = "";
|
|
1448
|
+
let errors: Record<string, string> = {};
|
|
1449
|
+
|
|
1450
|
+
head({ title: "Projects" });
|
|
1451
|
+
|
|
1452
|
+
return () => (
|
|
1453
|
+
<main>
|
|
1454
|
+
<h1>Projects ({rows.length})</h1>
|
|
1455
|
+
|
|
1456
|
+
<form
|
|
1457
|
+
onSubmit={async (e) => {
|
|
1458
|
+
e.preventDefault();
|
|
1459
|
+
errors = {};
|
|
1460
|
+
try {
|
|
1461
|
+
const created = await createProject({ name, slug });
|
|
1462
|
+
rows = [created, ...rows];
|
|
1463
|
+
name = "";
|
|
1464
|
+
slug = "";
|
|
1465
|
+
} catch (err) {
|
|
1466
|
+
if (err instanceof ValidationError) {
|
|
1467
|
+
errors = err.fields;
|
|
1468
|
+
return;
|
|
1469
|
+
}
|
|
1470
|
+
throw err;
|
|
1471
|
+
}
|
|
1472
|
+
}}
|
|
1473
|
+
>
|
|
1474
|
+
<input bind:value={name} placeholder="Project name" />
|
|
1475
|
+
{errors.name && <span class="error">{errors.name}</span>}
|
|
1476
|
+
|
|
1477
|
+
<input bind:value={slug} placeholder="project-slug" />
|
|
1478
|
+
{errors.slug && <span class="error">{errors.slug}</span>}
|
|
1479
|
+
|
|
1480
|
+
<button type="submit">Create Project</button>
|
|
1481
|
+
</form>
|
|
1482
|
+
|
|
1483
|
+
<ul>
|
|
1484
|
+
{rows.map((p) => (
|
|
1485
|
+
<li key={p.id}>
|
|
1486
|
+
<a href={`/projects/${p.slug}`}>{p.name}</a>
|
|
1487
|
+
</li>
|
|
1488
|
+
))}
|
|
1489
|
+
</ul>
|
|
1490
|
+
</main>
|
|
1491
|
+
);
|
|
1492
|
+
}
|
|
1493
|
+
```
|
|
1494
|
+
|
|
1495
|
+
---
|
|
1496
|
+
|
|
1497
|
+
## 4. Using Built-In `node:sqlite`, `Bun.sql`, or Kysely
|
|
1498
|
+
|
|
1499
|
+
`defineDb()` is completely ORM-agnostic. For zero-dependency local tools on Node.js 22.5+, you can even wrap Node's built-in `node:sqlite` directly:
|
|
1500
|
+
|
|
1501
|
+
```ts
|
|
1502
|
+
import { DatabaseSync } from "node:sqlite";
|
|
1503
|
+
import { defineDb } from "@fierst/c7t/server";
|
|
1504
|
+
|
|
1505
|
+
export const sqlite = defineDb((env) => {
|
|
1506
|
+
const conn = new DatabaseSync(env.SQLITE_PATH ?? "./app.db");
|
|
1507
|
+
conn.exec("PRAGMA journal_mode = WAL;");
|
|
1508
|
+
return conn;
|
|
1509
|
+
});
|
|
1510
|
+
```
|
|
1511
|
+
|
|
1512
|
+
Need the raw unwrapped instance for `instanceof` checks or driver plugins? Access **`db.$client`**.
|
|
1513
|
+
|
|
1514
|
+
---
|
|
1515
|
+
|
|
1516
|
+
# `@fierst/c7t` API Reference
|
|
1517
|
+
|
|
1518
|
+
`@fierst/c7t` is an ESM-first TypeScript package requiring **Node.js >= 20.19.0** (or Bun / Cloudflare `workerd` with `nodejs_als`) and `@fierst/blokd >= 1.3.0`.
|
|
1519
|
+
|
|
1520
|
+
---
|
|
1521
|
+
|
|
1522
|
+
## 1. Isomorphic Core (`@fierst/c7t`)
|
|
1523
|
+
|
|
1524
|
+
Safe to import in any `.tsx` or `.ts` module (SSR, SSG, and Browser):
|
|
1525
|
+
|
|
1526
|
+
| Export | Signature & Behavior |
|
|
1527
|
+
| -------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1528
|
+
| `server(fn)` / `server(Schema, fn)` | Wrap an `async (...args) => T` function into a dual-protocol `ServerCall<T>` (`yield*` + `await`), or wrap an `async function* (...args)` into an NDJSON streaming generator (`for await`). Optional first argument validates `args[0]` via Standard Schema v1 (Valibot, Zod, ArkType). |
|
|
1529
|
+
| `all([...calls])` | Execute a tuple or array of `ServerCall` / `STEP` generators concurrently (`Promise.all` on SSR/client mount, 0-tick replay on revival) and return their typed tuple `[A, B, ...]`. |
|
|
1530
|
+
| `head(config)` | `{ title?, description?, canonical?, meta?: HeadMetaTag[] }`. Merges outer-to-inner into `<head>` on SSR and updates `document` head tags in-place on client navigation. |
|
|
1531
|
+
| `searchParam(key, defaultValue, opts?)` | Returns a Blokd `Signal<T>` (`string \| number \| boolean`) synced with URL query parameter `key`. Works directly with `bind:value` and `bind:checked`. Options: `{ replace?: boolean }` (default `true`). |
|
|
1532
|
+
| `defineEnv({ server, public, runtimeEnv? })` | Validate environment variables via Standard Schema v1 across Cloudflare `req.env`, `process.env`, and `import.meta.env`. Accessing a `server` key in the browser throws immediately. |
|
|
1533
|
+
| `redirect(location, status?)` | Construct a `RedirectSignal` (`301 \| 302 \| 303 \| 307 \| 308`, default `302`). Throw inside SSR routes or `server()` handlers (`throw redirect("/login")`). |
|
|
1534
|
+
| `notFound(msg?)`, `unauthorized(msg?)`, `forbidden(msg?)`, `httpError(status, msg?, data?)` | Construct an `HttpStatusError` (`404`, `401`, `403`, or custom HTTP status). `throw notFound()` on SSR renders `src/routes/404.tsx` with HTTP `404`. |
|
|
1535
|
+
| `ValidationError` | Thrown when Standard Schema validation fails (`status = 400`, `issues`, and lazy `err.fields: Record<string, string>` dot-path map). |
|
|
1536
|
+
| `RouteProps<Path>` | `{ params: ExtractRouteParams<Path>, search: URLSearchParams, pathname: string, children?: View }`. Infers `[id]` and `[...slug]` params from template-literal route paths. |
|
|
1537
|
+
| `useRoute()`, `navigate(to, opts?)` | Read `{ pathname, search, params }` in any descendant component, or trigger client-side navigation programmatically (`{ replace?, transition? }`). |
|
|
1538
|
+
| `buildRoutes(entries)`, `buildApiRoutes(entries)`, `extractSpecialRoutes(entries)`, `Outlet` | Low-level route compilation helpers used by `virtual:c7t/routes` and custom programmatic servers. |
|
|
1539
|
+
|
|
1540
|
+
---
|
|
1541
|
+
|
|
1542
|
+
## 2. Server Runtime (`@fierst/c7t/server`)
|
|
1543
|
+
|
|
1544
|
+
Server-only module (importing runtime bindings outside `server(...)` in client code is blocked at build time):
|
|
1545
|
+
|
|
1546
|
+
| Export | Signature & Behavior |
|
|
1547
|
+
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1548
|
+
| `createServer(options?)` | Returns a `Hono` app configured with `AsyncLocalStorage` request scoping, user `middleware`, `POST /_c7t/rpc/:fnId` (CSRF + validation + NDJSON stream cancellation), file-system API routes, zero-FOUC CSS `<link>` injection, `404.tsx` / `error.tsx`, and streaming SSR (`ssrMode: "stream" \| "string"`). |
|
|
1549
|
+
| `req` | Ambient `C7tRequest` proxy (`req.url`, `req.method`, `req.headers`, `req.raw`, `req.env`, `req.signal`, `req.c`, plus augmented `RequestContext` fields). |
|
|
1550
|
+
| `cookies` | `{ get(name), set(name, value, options?), delete(name, options?) }`. Throws a build-time guardrail error if accessed while prerendering a static SSG route. |
|
|
1551
|
+
| `createSession<T>(config)` | Web-Crypto (`HMAC-SHA256`) signed `httpOnly` cookie session manager: `{ get(), set(data), clear() }`. Supports secret rotation via `secret: [currentKey, oldKey]`. |
|
|
1552
|
+
| `defineDb(factory, options?)` | Lazy, ORM-agnostic database proxy (`scope?: "auto" \| "singleton" \| "request"`). Reuses singletons on Node/Bun (`process.env`) and isolates per-request bindings on Cloudflare Workers (`req.env.DB`). Exposes `db.$client` for raw instance access. |
|
|
1553
|
+
| `runWithRequestContext(c, fn, signal?)` | Run arbitrary async work inside `c7t`'s Hono `AsyncLocalStorage` context. |
|
|
1554
|
+
| `registerServerFn(id, schemaOrFn, maybeFn?)` | Low-level RPC registration helper emitted by `@fierst/c7t/vite`. |
|
|
1555
|
+
|
|
1556
|
+
### `CreateServerOptions`
|
|
1557
|
+
|
|
1558
|
+
- `routes?: readonly RouteModuleEntry[] | readonly CompiledRoute[]` — Defaults to auto-discovered `src/routes/**` when built with `@fierst/c7t/vite`.
|
|
1559
|
+
- `middleware?: MiddlewareHandler | readonly MiddlewareHandler[]` — Runs identically on SSR page loads, file-system API routes, and `/_c7t/rpc/*`.
|
|
1560
|
+
- `configure?: (app: Hono) => void` — Escape hatch to mount custom Hono routes or sub-apps.
|
|
1561
|
+
- `notFoundComponent?: ComponentFn<{ pathname: string }>` — Overrides `src/routes/404.tsx`.
|
|
1562
|
+
- `errorComponent?: ComponentFn<{ error: unknown; reset: () => void }>` — Overrides `src/routes/error.tsx`.
|
|
1563
|
+
- `styles?: readonly string[]` — Additional stylesheet hrefs injected into `<head>`.
|
|
1564
|
+
- `ssrMode?: "stream" | "string"` — Defaults to `"stream"`.
|
|
1565
|
+
- `rpcBase?: string` — Defaults to `"/_c7t/rpc"`.
|
|
1566
|
+
- `document?: Omit<DocumentOptions, "receipts"> & { clientEntryUrl?: string }` — Customize `lang`, `title`, `head`, `nonce` (CSP), `importmap`, or `revive` (`true | false | "auto"`).
|
|
1567
|
+
- `manifest?: RevivalManifest` — Explicit production asset manifest override.
|
|
1568
|
+
|
|
1569
|
+
---
|
|
1570
|
+
|
|
1571
|
+
## 3. Client Runtime (`@fierst/c7t/client`)
|
|
1572
|
+
|
|
1573
|
+
| Export | Signature & Behavior |
|
|
1574
|
+
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1575
|
+
| `installC7t(options?)` | Installs the `$ref` State Receipt decoder, Blokd lazy island revival, and persistent nested `<c7t-outlet>` client router. Called automatically by `virtual:c7t/client-entry`. |
|
|
1576
|
+
| `configureClient(config)` | Configure `{ rpcBase?, fetch? }` on the client. |
|
|
1577
|
+
| `createRpcStub(fnId)` | Low-level dual-protocol RPC stub factory emitted by `@fierst/c7t/vite`. Automatically switches to `multipart/form-data` when arguments contain `File`, `Blob`, or `FormData`. |
|
|
1578
|
+
| `createStreamStub(fnId)` | Low-level NDJSON `AsyncGenerator` stub factory with owner auto-refresh and `AbortController` teardown. |
|
|
1579
|
+
|
|
1580
|
+
---
|
|
1581
|
+
|
|
1582
|
+
## 4. Vite+ Compiler, Build Pipeline, & CLI (`@fierst/c7t/vite` & `c7t`)
|
|
1583
|
+
|
|
1584
|
+
| Export / Command | Description |
|
|
1585
|
+
| ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1586
|
+
| `c7t(options?)` | Default & named Vite+ plugin (`routesDir`, `serverEntry`, `hashIds`, `adapter`, `prerender?: boolean \| "marked" \| "all"`, `csr?: "auto" \| "islands" \| boolean`, `blokd`). |
|
|
1587
|
+
| `buildApp(options?)` | Programmatic 3-stage production builder (`{ root?, adapter?, prerender?, logLevel? }`) returning `BuildAppResult`. |
|
|
1588
|
+
| `compileC7tModule(code, opts)` | Low-level Oxc AST transform for `*.server.ts` and colocated `server()` / `prerender` stripping. |
|
|
1589
|
+
| `c7t <dir> [--db=sqlite\|postgres\|d1]` / `c7t create <dir>` | Scaffold a new `c7t` starter project (with optional Drizzle + `drizzle-valibot` database setup). |
|
|
1590
|
+
| `c7t build [--adapter=<t>] [--prerender=all\|marked\|false]` | Run Client -> SSR -> SSG + Adapter build pipeline. |
|
|
1591
|
+
| `c7t start [--port=3000]` | Boot `dist/server/start.mjs` in production mode. |
|
|
1592
|
+
|
|
1593
|
+
---
|
|
1594
|
+
|
|
1595
|
+
## 5. Static Site Generation & Deployment Adapters
|
|
1596
|
+
|
|
1597
|
+
| Subpath | Exports |
|
|
1598
|
+
| ------------------------ | ------------------------------------------------------------------------------------------------------------------- |
|
|
1599
|
+
| `@fierst/c7t/ssg` | `prerenderApp(options)` (`mode: "marked" \| "all"`, `crawl`, `entries`, `onBrokenLink`), `getSidecarPathname(path)` |
|
|
1600
|
+
| `@fierst/c7t/node` | `serveNode(app, opts?)`, `createNodeHandler(app, opts?)`, `nodeAdapter(opts?)` |
|
|
1601
|
+
| `@fierst/c7t/cloudflare` | `cloudflareAdapter(app, opts?)`, `cloudflarePreset(opts?)` |
|
|
1602
|
+
| `@fierst/c7t/vercel` | `buildVercelOutput(opts?)`, `vercelAdapter(opts?)` (Vercel Build Output API v3) |
|
|
1603
|
+
| `@fierst/c7t/bun` | `serveBun(app, opts?)`, `createBunFetchHandler(app, opts?)`, `bunAdapter(opts?)` |
|
|
1604
|
+
| `@fierst/c7t/static` | `buildStaticSite(opts)`, `staticAdapter(opts?)` |
|
|
1605
|
+
|
|
1606
|
+
---
|
|
1607
|
+
|
|
1608
|
+
## 6. Route Module Exports Reference (`src/routes/**`)
|
|
1609
|
+
|
|
1610
|
+
| Export in Route File | Purpose |
|
|
1611
|
+
| ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1612
|
+
| `export default function* Page(props)` | UI page or layout component (`function`, `function*`, or `async function*`). |
|
|
1613
|
+
| `export const prerender = true \| false \| (() => [...])` | Prerender route (or layout subtree) to static HTML + `__c7t.json` sidecar, or pass `false` to opt a route out of global `prerender: true`. |
|
|
1614
|
+
| `export const csr = "auto" \| "islands" \| true \| false` | Client JS mode (cascades from `c7t()` config -> `layout.tsx` -> page; defaults to `"auto"`, emitting 0 `<script>` tags when 0 islands render). |
|
|
1615
|
+
| `export async function GET(c)` (`POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`) | Raw Hono HTTP endpoint handler at the route's URL pattern. |
|
|
1616
|
+
|
|
1617
|
+
---
|
|
1618
|
+
|
|
1619
|
+
## 7. Troubleshooting & Diagnostics
|
|
1620
|
+
|
|
1621
|
+
| Symptom | Cause & Resolution |
|
|
1622
|
+
| ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1623
|
+
| `[c7t] "..." references server-only import(s) (cookies) from "@fierst/c7t/server" in client code` | `cookies` or `req` was referenced in JSX or component setup outside a `server(...)` block. Move the access inside `server(async () => { ... })` and call `yield* fn()`. |
|
|
1624
|
+
| `[c7t SSG] Cannot call cookies.get while prerendering static route` | A route marked `prerender = true` (or crawled under `prerender: "all"`) read request cookies/sessions at build time. Remove `prerender` from personalized routes or move user state to a client RPC after interaction. |
|
|
1625
|
+
| `[Blokd] Receipt step mismatch` warning in dev console | Conditional logic (`typeof window`, `Math.random()`) changed the order of `yield*` `server()` calls between SSR and client revival. Keep `yield*` calls deterministic across server and client. |
|
|
1626
|
+
| Cross-origin `POST /_c7t/rpc/*` returns `403 Forbidden` | `c7t`'s CSRF guard blocks cross-site RPCs when `Origin` mismatches. For third-party webhooks or public CORS APIs, export a file-system `POST(c)` handler (`src/routes/api/webhook.ts`) instead of an internal RPC. |
|
|
1627
|
+
| Unexpected server error shows `"Internal Server Error"` in prod | `NODE_ENV="production"` masks unhandled `500` errors on the wire for security. Inspect server logs (`[c7t RPC error]`) or throw `httpError(422, "Safe user-facing message")` when the message is intended for the UI. |
|