@fierst/c7t 0.0.0-stage → 1.0.0-beta.1
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 +337 -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 +122 -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/docs/README.md
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# c7t ("Construct") Documentation
|
|
2
|
+
|
|
3
|
+
**`@fierst/c7t`** (_Construct_) is Fierst LLC's full-stack generator meta-framework built on **[`@fierst/blokd`](https://blokd.dev)**, **[Hono](https://hono.dev)**, and **[Vite+ (`vp`)](https://viteplus.dev)**.
|
|
4
|
+
|
|
5
|
+
It pairs Blokd's zero-VDOM generator components (`function*`), slot-compiled templates, and event-delegated lazy revival with:
|
|
6
|
+
|
|
7
|
+
- **Dual-Protocol `server()` Callables:** Use `yield* getTasks()` during component setup (runs directly on the server during SSR, emits a `$ref`-deduplicated State Receipt, and revives synchronously in **0 microtasks** with **0 client refetches**) and `await createTask(input)` inside event handlers (calls `POST /_c7t/rpc/:id` with automatic SHA-256 ID hashing in production).
|
|
8
|
+
- **Bidirectional NDJSON Streaming (`server(async function* ...)`):** Stream real-time progress or AI tokens with `for await (const chunk of runJob())`. Breaking out of the loop or unmounting aborts the HTTP stream and runs the server generator's `finally` block immediately.
|
|
9
|
+
- **Persistent Nested & Pathless Group Layouts:** File-system routing (`src/routes/**`) with `<c7t-outlet>` boundaries that preserve parent layout `let` & `signal()` state across navigations, plus `404.tsx`, `error.tsx`, `head()`, and bindable `searchParam()`.
|
|
10
|
+
- **First-Class Hybrid & Full Static Site Generation (SSG):** Automatic `csr: "auto"` (0 `<script>` tags when 0 islands render; automatic lazy revival when 1+ islands render), cascading `prerender` & `csr` inheritance (`c7t()` config -> `layout.tsx` -> route), `<a href>` link crawling, `__c7t.json` static receipt sidecars for serverless SPA navigation, and static `sitemap.xml` / `rss.xml` endpoints.
|
|
11
|
+
- **Deploy Everywhere:** Official zero-bloat adapters for **Node.js**, **Cloudflare Workers**, **Vercel (Build Output v3)**, **Bun**, and **Static CDNs**.
|
|
12
|
+
|
|
13
|
+
## Guides
|
|
14
|
+
|
|
15
|
+
1. [Getting Started](./guides/01-getting-started.md) — Scaffolding with `c7t`, project structure, zero-boilerplate single-file apps, `vp dev`, `c7t build`, and `c7t start`.
|
|
16
|
+
2. [Data Fetching, Validation, and File Uploads](./guides/02-data-fetching-and-mutations.md) — Dual-protocol `server()`, `*.server.ts` vs colocated RPCs, `all()`, State Receipts, Standard Schema validation (`err.fields`), optimistic UI, and `File`/`Blob` multipart uploads.
|
|
17
|
+
3. [Streaming SSR, NDJSON Server Streams, and `yield*` Workflows](./guides/03-streaming-and-workflows.md) — Out-of-order streaming SSR skeletons, `server(async function* ...)` live streams, cancellation teardown, and multi-step UI wizards.
|
|
18
|
+
4. [Routing, Nested Layouts, URL State, and Webhooks](./guides/04-routing-layouts-and-state.md) — `layout.tsx`, `(group)/layout.tsx`, `[param]` & `[...catchall]`, `RouteProps<Path>`, `404.tsx` & `error.tsx`, `head()`, `searchParam()`, hover preloading, and HTTP API routes.
|
|
19
|
+
5. [Authentication, Sessions, Environment Variables, and Security](./guides/05-auth-sessions-and-security.md) — `req` & `cookies` (`AsyncLocalStorage`), Hono middleware, `createSession()` (HMAC-SHA256 + key rotation), `defineEnv()`, CSRF guards, and production error masking.
|
|
20
|
+
6. [Static Site Generation (SSG) and Deployment Adapters](./guides/06-ssg-and-deployment.md) — Hybrid prerendering, pure SSG (`mode: 'all'`), `__c7t.json` sidecars, `csr = false`, and deploying to Node, Cloudflare Workers, Vercel, Bun, and Static hosts.
|
|
21
|
+
7. [Databases, `defineDb()`, and Drizzle ORM](./guides/07-databases-and-drizzle.md) — Scaffolding with `--db=sqlite|postgres|d1`, bridging Node pools and Cloudflare D1 bindings via `defineDb()`, and single-source-of-truth validation with `drizzle-valibot`.
|
|
22
|
+
|
|
23
|
+
## Reference
|
|
24
|
+
|
|
25
|
+
- [API Reference](./reference.md) — Complete signatures across `@fierst/c7t`, `/server`, `/client`, `/router`, `/ssg`, `/vite`, `/node`, `/cloudflare`, `/vercel`, `/bun`, and `/static`, plus CLI flags and troubleshooting.
|
|
26
|
+
- [Single-File LLM Handbook](../llms.txt) — Concatenated guides and API reference optimized for AI coding assistants.
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
# 01. Getting Started with c7t ("Construct")
|
|
2
|
+
|
|
3
|
+
`@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.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Scaffold a New Project
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npx @fierst/c7t my-app
|
|
11
|
+
cd my-app
|
|
12
|
+
npm install
|
|
13
|
+
npm run dev
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
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.
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## 2. Project Anatomy
|
|
21
|
+
|
|
22
|
+
A minimal `c7t` project requires **no `index.html`**, **no client `main.tsx`**, and **no custom `server.ts`** unless you want custom Hono middleware:
|
|
23
|
+
|
|
24
|
+
```text
|
|
25
|
+
my-app/
|
|
26
|
+
├── src/
|
|
27
|
+
│ ├── styles.css # Automatically linked in <head> (zero FOUC!)
|
|
28
|
+
│ └── routes/
|
|
29
|
+
│ ├── layout.tsx # Persistent root shell (<nav>, theme, footer)
|
|
30
|
+
│ ├── index.tsx # "/" — Full-stack page + colocated server() RPCs
|
|
31
|
+
│ ├── about.tsx # "/about" — Static SSG page (export const prerender = true)
|
|
32
|
+
│ └── 404.tsx # Custom HTTP 404 page rendered inside layout.tsx
|
|
33
|
+
├── vite.config.ts # Single plugin: c7t()
|
|
34
|
+
├── tsconfig.json # jsxImportSource: "@fierst/blokd"
|
|
35
|
+
└── package.json
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### `vite.config.ts`
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
import { defineConfig } from "vite-plus";
|
|
42
|
+
import c7t from "@fierst/c7t/vite";
|
|
43
|
+
|
|
44
|
+
export default defineConfig({
|
|
45
|
+
plugins: [c7t()],
|
|
46
|
+
lint: {
|
|
47
|
+
ignorePatterns: ["node_modules/**", "dist/**", ".vercel/**"],
|
|
48
|
+
rules: {
|
|
49
|
+
"require-yield": "off",
|
|
50
|
+
},
|
|
51
|
+
options: {
|
|
52
|
+
typeAware: true,
|
|
53
|
+
typeCheck: true,
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
## 3. Your First Full-Stack Route
|
|
62
|
+
|
|
63
|
+
Create `src/routes/index.tsx`. Notice how server queries, mutations, `<head>` metadata, local `let` state, and reactive JSX live cohesively in one file:
|
|
64
|
+
|
|
65
|
+
```tsx
|
|
66
|
+
import { head, server } from "@fierst/c7t";
|
|
67
|
+
|
|
68
|
+
interface Todo {
|
|
69
|
+
id: string;
|
|
70
|
+
title: string;
|
|
71
|
+
done: boolean;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// In-memory store for illustration — swap for SQLite, Postgres, Drizzle, or Cloudflare D1!
|
|
75
|
+
const todos: Todo[] = [{ id: "1", title: "Ship Construct v1.0", done: false }];
|
|
76
|
+
|
|
77
|
+
export const listTodos = server(async () => [...todos]);
|
|
78
|
+
|
|
79
|
+
export const addTodo = server(async (title: string) => {
|
|
80
|
+
const item: Todo = { id: crypto.randomUUID(), title: title.trim(), done: false };
|
|
81
|
+
todos.unshift(item);
|
|
82
|
+
return item;
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
export default function* HomePage() {
|
|
86
|
+
// 1. Runs directly on the server during SSR; replays in 0 ticks on client revival!
|
|
87
|
+
let items = yield* listTodos();
|
|
88
|
+
let draft = "";
|
|
89
|
+
let saving = false;
|
|
90
|
+
|
|
91
|
+
head({
|
|
92
|
+
title: "Tasks — Construct",
|
|
93
|
+
description: "Zero-VDOM full-stack task tracker",
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
// 2. Live reactive view closure — plain `let` mutations automatically patch compiled DOM slots!
|
|
97
|
+
return () => (
|
|
98
|
+
<main>
|
|
99
|
+
<h1>Tasks ({items.filter((t) => !t.done).length} remaining)</h1>
|
|
100
|
+
|
|
101
|
+
<form
|
|
102
|
+
onSubmit={async (e) => {
|
|
103
|
+
e.preventDefault();
|
|
104
|
+
if (!draft.trim() || saving) return;
|
|
105
|
+
saving = true;
|
|
106
|
+
try {
|
|
107
|
+
const created = await addTodo(draft);
|
|
108
|
+
items = [created, ...items];
|
|
109
|
+
draft = "";
|
|
110
|
+
} finally {
|
|
111
|
+
saving = false;
|
|
112
|
+
}
|
|
113
|
+
}}
|
|
114
|
+
>
|
|
115
|
+
<input bind:value={draft} placeholder="Add a task…" />
|
|
116
|
+
<button type="submit" disabled={saving || !draft.trim()}>
|
|
117
|
+
{saving ? "Saving…" : "Add"}
|
|
118
|
+
</button>
|
|
119
|
+
</form>
|
|
120
|
+
|
|
121
|
+
<ul>
|
|
122
|
+
{items.map((item) => (
|
|
123
|
+
<li key={item.id}>
|
|
124
|
+
<label>
|
|
125
|
+
<input type="checkbox" bind:checked={item.done} />
|
|
126
|
+
<span>{item.title}</span>
|
|
127
|
+
</label>
|
|
128
|
+
</li>
|
|
129
|
+
))}
|
|
130
|
+
</ul>
|
|
131
|
+
</main>
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### What Happened Under the Hood?
|
|
137
|
+
|
|
138
|
+
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).
|
|
139
|
+
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 />`.
|
|
140
|
+
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.
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
## 4. Development, Checking, and Production Builds
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
# Start Vite+ dev server with SSR + HMR
|
|
148
|
+
npm run dev
|
|
149
|
+
|
|
150
|
+
# Run formatting, Oxlint, and TypeScript type-checking
|
|
151
|
+
npm run check
|
|
152
|
+
|
|
153
|
+
# Run the 3-stage production pipeline (Client -> SSR Bundle -> SSG Prerender + Adapter)
|
|
154
|
+
npm run build
|
|
155
|
+
|
|
156
|
+
# Boot the standalone Node production server on http://localhost:3000
|
|
157
|
+
npm start
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
What `c7t build` produces in `dist/`:
|
|
161
|
+
|
|
162
|
+
- `dist/client/` — Content-hashed JS islands, extracted CSS stylesheets, `c7t-manifest.json`, and any prerendered SSG `.html` + `__c7t.json` sidecar files.
|
|
163
|
+
- `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).
|
|
164
|
+
- `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.
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
# 02. Data Fetching, Validation, Optimistic UI, and File Uploads
|
|
2
|
+
|
|
3
|
+
In `c7t`, you never maintain separate REST controllers, route `loader` conventions, `useEffect` fetch hooks, or query-cache providers. Everything flows through one primitive: **`server()`**.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Dual-Protocol `server()` Callables (`yield*` + `await`)
|
|
8
|
+
|
|
9
|
+
Every function wrapped in `server(...)` returns a `ServerCall<T>` implementing **both** JavaScript's `Generator` protocol (`[Symbol.iterator]`) and `PromiseLike<T>` (`then()`):
|
|
10
|
+
|
|
11
|
+
| Calling Style | Where to Use It | Behavior |
|
|
12
|
+
| ------------------------------------------ | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
13
|
+
| `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). |
|
|
14
|
+
| `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. |
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## 2. Colocated `server()` vs Dedicated `*.server.ts` Files
|
|
19
|
+
|
|
20
|
+
Both styles compile to identical RPC endpoints and client stubs—pick whichever fits your module organization:
|
|
21
|
+
|
|
22
|
+
### Style A: Colocated Inside a `.tsx` Route
|
|
23
|
+
|
|
24
|
+
Ideal when queries/mutations belong to one route. Oxc automatically prunes server-only imports (`db`, `valibot`, `node:crypto`) from the client bundle:
|
|
25
|
+
|
|
26
|
+
```tsx
|
|
27
|
+
import { server } from "@fierst/c7t";
|
|
28
|
+
import { db } from "../lib/db"; // Automatically stripped from client bundle!
|
|
29
|
+
|
|
30
|
+
const getStats = server(async () => {
|
|
31
|
+
return db.query("SELECT count(*) AS users FROM accounts");
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
export default function* Dashboard() {
|
|
35
|
+
const stats = yield* getStats();
|
|
36
|
+
return () => <p>Total users: {stats.users}</p>;
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
### Style B: Dedicated `*.server.ts` Module Boundary
|
|
41
|
+
|
|
42
|
+
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:
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
// src/lib/invoices.server.ts
|
|
46
|
+
import { server, notFound } from "@fierst/c7t";
|
|
47
|
+
import * as v from "valibot";
|
|
48
|
+
import { db } from "./db";
|
|
49
|
+
|
|
50
|
+
// Plain exported async function — automatically becomes a Dual-Protocol ServerCall!
|
|
51
|
+
export async function getInvoice(id: string) {
|
|
52
|
+
const row = await db.invoices.findUnique({ where: { id } });
|
|
53
|
+
if (!row) throw notFound(`Invoice #${id} does not exist`);
|
|
54
|
+
return row;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Schema-validated mutation
|
|
58
|
+
export const markInvoicePaid = server(
|
|
59
|
+
v.object({ invoiceId: v.pipe(v.string(), v.nonEmpty()) }),
|
|
60
|
+
async ({ invoiceId }) => {
|
|
61
|
+
return db.invoices.update({ where: { id: invoiceId }, data: { status: "paid" } });
|
|
62
|
+
},
|
|
63
|
+
);
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## 3. Parallel Queries with `all()` & Request Deduplication
|
|
69
|
+
|
|
70
|
+
Avoid sequential waterfalls when loading multiple independent queries by combining them with **`all([...])`**:
|
|
71
|
+
|
|
72
|
+
```tsx
|
|
73
|
+
import { all, type RouteProps } from "@fierst/c7t";
|
|
74
|
+
import { getProject, getProjectMembers, getRecentActivity } from "./projects.server";
|
|
75
|
+
|
|
76
|
+
export default function* ProjectOverview(props: RouteProps<"/projects/[id]">) {
|
|
77
|
+
// Executes all 3 queries concurrently via Promise.all on SSR & SPA navigation,
|
|
78
|
+
// and replays all 3 synchronously in 0 ticks on client revival!
|
|
79
|
+
const [project, members, activity] = yield* all([
|
|
80
|
+
getProject(props.params.id),
|
|
81
|
+
getProjectMembers(props.params.id),
|
|
82
|
+
getRecentActivity(props.params.id),
|
|
83
|
+
]);
|
|
84
|
+
|
|
85
|
+
return () => (
|
|
86
|
+
<section>
|
|
87
|
+
<h1>{project.name}</h1>
|
|
88
|
+
<p>
|
|
89
|
+
{members.length} members · {activity.length} recent events
|
|
90
|
+
</p>
|
|
91
|
+
</section>
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### Automatic Per-Request Memoization & `$ref` Deduplication
|
|
97
|
+
|
|
98
|
+
- **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.
|
|
99
|
+
- **`$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.
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## 4. Standard Schema Input Validation & `err.fields`
|
|
104
|
+
|
|
105
|
+
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:
|
|
106
|
+
|
|
107
|
+
```tsx
|
|
108
|
+
import { server, ValidationError } from "@fierst/c7t";
|
|
109
|
+
import * as v from "valibot";
|
|
110
|
+
|
|
111
|
+
const InviteSchema = v.object({
|
|
112
|
+
email: v.pipe(v.string(), v.email("Enter a valid work email")),
|
|
113
|
+
role: v.picklist(["member", "admin"], "Choose member or admin"),
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
export const sendInvite = server(InviteSchema, async (input) => {
|
|
117
|
+
// `input` is inferred as `{ email: string; role: "member" | "admin" }`
|
|
118
|
+
return { id: crypto.randomUUID(), ...input };
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
export default function* InviteForm() {
|
|
122
|
+
let email = "";
|
|
123
|
+
let role: "member" | "admin" = "member";
|
|
124
|
+
let fieldErrors: Record<string, string> = {};
|
|
125
|
+
let sentTo: string | null = null;
|
|
126
|
+
|
|
127
|
+
return () => (
|
|
128
|
+
<form
|
|
129
|
+
onSubmit={async (e) => {
|
|
130
|
+
e.preventDefault();
|
|
131
|
+
fieldErrors = {};
|
|
132
|
+
try {
|
|
133
|
+
const res = await sendInvite({ email, role });
|
|
134
|
+
sentTo = res.email;
|
|
135
|
+
email = "";
|
|
136
|
+
} catch (err) {
|
|
137
|
+
if (err instanceof ValidationError) {
|
|
138
|
+
// Instant dot-path lookup: { email: "Enter a valid work email" }
|
|
139
|
+
fieldErrors = err.fields;
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
throw err;
|
|
143
|
+
}
|
|
144
|
+
}}
|
|
145
|
+
>
|
|
146
|
+
<label>
|
|
147
|
+
Work Email
|
|
148
|
+
<input bind:value={email} type="email" aria-invalid={Boolean(fieldErrors.email)} />
|
|
149
|
+
</label>
|
|
150
|
+
{fieldErrors.email && <p class="error">{fieldErrors.email}</p>}
|
|
151
|
+
|
|
152
|
+
<select bind:value={role}>
|
|
153
|
+
<option value="member">Member</option>
|
|
154
|
+
<option value="admin">Admin</option>
|
|
155
|
+
</select>
|
|
156
|
+
|
|
157
|
+
<button type="submit">Send Invite</button>
|
|
158
|
+
{sentTo && <p>Invitation sent to {sentTo}!</p>}
|
|
159
|
+
</form>
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
---
|
|
165
|
+
|
|
166
|
+
## 5. Zero-Framework Optimistic UI + Automatic Rollback
|
|
167
|
+
|
|
168
|
+
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()`:
|
|
169
|
+
|
|
170
|
+
```tsx
|
|
171
|
+
import type { Ctx } from "@fierst/blokd";
|
|
172
|
+
import { toggleTaskDone, type Task } from "./tasks.server";
|
|
173
|
+
|
|
174
|
+
export function* TaskItem(props: { task: Task }, ctx: Ctx<{ task: Task }>) {
|
|
175
|
+
let done = props.task.done;
|
|
176
|
+
let errorMsg = "";
|
|
177
|
+
|
|
178
|
+
return () => (
|
|
179
|
+
<li>
|
|
180
|
+
<label>
|
|
181
|
+
<input
|
|
182
|
+
type="checkbox"
|
|
183
|
+
checked={done}
|
|
184
|
+
onChange={async () => {
|
|
185
|
+
const previous = done;
|
|
186
|
+
done = !done; // 1. Instant optimistic UI update!
|
|
187
|
+
errorMsg = "";
|
|
188
|
+
try {
|
|
189
|
+
const updated = await toggleTaskDone(props.task.id, done);
|
|
190
|
+
done = updated.done;
|
|
191
|
+
} catch (err) {
|
|
192
|
+
done = previous; // 2. Exact rollback on network/server failure
|
|
193
|
+
errorMsg = (err as Error).message;
|
|
194
|
+
} finally {
|
|
195
|
+
ctx.refresh(); // 3. Patch DOM slots after async settlement
|
|
196
|
+
}
|
|
197
|
+
}}
|
|
198
|
+
/>
|
|
199
|
+
<span>{props.task.title}</span>
|
|
200
|
+
</label>
|
|
201
|
+
{errorMsg && <small role="alert">{errorMsg}</small>}
|
|
202
|
+
</li>
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
---
|
|
208
|
+
|
|
209
|
+
## 6. Binary `File`, `Blob`, and `FormData` Uploads
|
|
210
|
+
|
|
211
|
+
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:
|
|
212
|
+
|
|
213
|
+
```tsx
|
|
214
|
+
import { server, httpError } from "@fierst/c7t";
|
|
215
|
+
import { writeFile } from "node:fs/promises";
|
|
216
|
+
|
|
217
|
+
export const uploadAvatar = server(async (input: { displayName: string; avatar: File }) => {
|
|
218
|
+
if (input.avatar.size > 5 * 1024 * 1024) {
|
|
219
|
+
throw httpError(413, "Avatar must be smaller than 5 MB");
|
|
220
|
+
}
|
|
221
|
+
const bytes = new Uint8Array(await input.avatar.arrayBuffer());
|
|
222
|
+
await writeFile(`./uploads/${crypto.randomUUID()}-${input.avatar.name}`, bytes);
|
|
223
|
+
return { name: input.avatar.name, bytes: input.avatar.size };
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
export default function* AvatarUploader() {
|
|
227
|
+
let displayName = "";
|
|
228
|
+
let selectedFile: File | null = null;
|
|
229
|
+
let uploadedInfo: { name: string; bytes: number } | null = null;
|
|
230
|
+
|
|
231
|
+
return () => (
|
|
232
|
+
<form
|
|
233
|
+
onSubmit={async (e) => {
|
|
234
|
+
e.preventDefault();
|
|
235
|
+
if (!selectedFile) return;
|
|
236
|
+
uploadedInfo = await uploadAvatar({ displayName, avatar: selectedFile });
|
|
237
|
+
}}
|
|
238
|
+
>
|
|
239
|
+
<input bind:value={displayName} placeholder="Display name" />
|
|
240
|
+
<input
|
|
241
|
+
type="file"
|
|
242
|
+
accept="image/*"
|
|
243
|
+
onChange={(e) => {
|
|
244
|
+
selectedFile = e.currentTarget.files?.[0] ?? null;
|
|
245
|
+
}}
|
|
246
|
+
/>
|
|
247
|
+
<button type="submit" disabled={!selectedFile}>
|
|
248
|
+
Upload
|
|
249
|
+
</button>
|
|
250
|
+
{uploadedInfo && (
|
|
251
|
+
<p>
|
|
252
|
+
Uploaded {uploadedInfo.name} ({uploadedInfo.bytes} bytes)
|
|
253
|
+
</p>
|
|
254
|
+
)}
|
|
255
|
+
</form>
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
```
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
# 03. Streaming SSR, NDJSON Server Streams, and `yield*` Workflows
|
|
2
|
+
|
|
3
|
+
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.**
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Out-of-Order Streaming SSR (`async function*`)
|
|
8
|
+
|
|
9
|
+
By default, `createServer()` runs in `ssrMode: "stream"`. Any `async function*` component can `yield` an immediate loading skeleton before awaiting slow data:
|
|
10
|
+
|
|
11
|
+
1. `c7t` flushes `<head>` (with `<title>`, meta tags, and `<link rel="stylesheet">`) plus the initial shell + skeleton HTML immediately for sub-10ms TTFB.
|
|
12
|
+
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.
|
|
13
|
+
|
|
14
|
+
```tsx
|
|
15
|
+
import { server } from "@fierst/c7t";
|
|
16
|
+
|
|
17
|
+
const fetchSlowAnalytics = server(async (orgId: string) => {
|
|
18
|
+
await new Promise((r) => setTimeout(r, 400));
|
|
19
|
+
return { revenue: "$48,200", conversion: "4.8%" };
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
export async function* AnalyticsWidget(props: { orgId: string }) {
|
|
23
|
+
// Flushed immediately in the first HTTP chunk!
|
|
24
|
+
yield <div class="card skeleton">Loading revenue metrics…</div>;
|
|
25
|
+
|
|
26
|
+
const metrics = await fetchSlowAnalytics(props.orgId);
|
|
27
|
+
|
|
28
|
+
// Streamed out-of-order and swapped in-place as soon as ready
|
|
29
|
+
return () => (
|
|
30
|
+
<div class="card">
|
|
31
|
+
<strong>{metrics.revenue}</strong> ({metrics.conversion} conversion)
|
|
32
|
+
</div>
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## 2. Bidirectional NDJSON Server Streams (`server(async function* ...)`)
|
|
40
|
+
|
|
41
|
+
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`):
|
|
42
|
+
|
|
43
|
+
- **Wire Protocol:** Streams `application/x-ndjson` frames over standard HTTP `fetch()` (works through every CDN, corporate proxy, Cloudflare Worker, and Vercel Function without WebSockets).
|
|
44
|
+
- **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!
|
|
45
|
+
- **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!
|
|
46
|
+
|
|
47
|
+
### Real-World Example: Cancellable AI Assistant Stream
|
|
48
|
+
|
|
49
|
+
```tsx
|
|
50
|
+
import { server } from "@fierst/c7t";
|
|
51
|
+
import { req } from "@fierst/c7t/server";
|
|
52
|
+
|
|
53
|
+
export const streamCompletion = server(async function* (prompt: string) {
|
|
54
|
+
const upstream = await fetch("https://api.example.com/v1/chat/completions", {
|
|
55
|
+
method: "POST",
|
|
56
|
+
headers: {
|
|
57
|
+
Authorization: `Bearer ${process.env.AI_API_KEY}`,
|
|
58
|
+
"Content-Type": "application/json",
|
|
59
|
+
},
|
|
60
|
+
body: JSON.stringify({ prompt, stream: true }),
|
|
61
|
+
// Automatically aborts upstream LLM request when client breaks or unmounts!
|
|
62
|
+
signal: req.signal,
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
try {
|
|
66
|
+
// Simulated token chunks for illustration
|
|
67
|
+
const tokens = ["Generators ", "make ", "streaming ", "effortless."];
|
|
68
|
+
for (const token of tokens) {
|
|
69
|
+
await new Promise((r) => setTimeout(r, 80));
|
|
70
|
+
yield { token };
|
|
71
|
+
}
|
|
72
|
+
return { finishReason: "stop" as const };
|
|
73
|
+
} finally {
|
|
74
|
+
// Guaranteed to run on completion, error, OR client disconnect / `break`!
|
|
75
|
+
console.log("Cleaned up AI stream resources");
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
export default function* AiPlayground() {
|
|
80
|
+
let prompt = "Why generators?";
|
|
81
|
+
let answer = "";
|
|
82
|
+
let streaming = false;
|
|
83
|
+
let stopRequested = false;
|
|
84
|
+
|
|
85
|
+
return () => (
|
|
86
|
+
<section>
|
|
87
|
+
<form
|
|
88
|
+
onSubmit={async (e) => {
|
|
89
|
+
e.preventDefault();
|
|
90
|
+
if (streaming) return;
|
|
91
|
+
answer = "";
|
|
92
|
+
streaming = true;
|
|
93
|
+
stopRequested = false;
|
|
94
|
+
|
|
95
|
+
try {
|
|
96
|
+
for await (const chunk of streamCompletion(prompt)) {
|
|
97
|
+
answer += chunk.token; // Automatically updates DOM on every yielded token!
|
|
98
|
+
if (stopRequested) {
|
|
99
|
+
break; // Immediately aborts HTTP stream & triggers server `finally`!
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
} finally {
|
|
103
|
+
streaming = false;
|
|
104
|
+
}
|
|
105
|
+
}}
|
|
106
|
+
>
|
|
107
|
+
<input bind:value={prompt} disabled={streaming} />
|
|
108
|
+
{!streaming ? (
|
|
109
|
+
<button type="submit">Ask</button>
|
|
110
|
+
) : (
|
|
111
|
+
<button type="button" onClick={() => (stopRequested = true)}>
|
|
112
|
+
Stop Generating
|
|
113
|
+
</button>
|
|
114
|
+
)}
|
|
115
|
+
</form>
|
|
116
|
+
|
|
117
|
+
<output>{answer}</output>
|
|
118
|
+
</section>
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
## 3. Composable Multi-Step UI Workflows (`yield*`)
|
|
126
|
+
|
|
127
|
+
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:
|
|
128
|
+
|
|
129
|
+
```tsx
|
|
130
|
+
import type { Ctx } from "@fierst/blokd";
|
|
131
|
+
import { server } from "@fierst/c7t";
|
|
132
|
+
|
|
133
|
+
const deleteWorkspace = server(async (workspaceId: string, totpCode: string) => {
|
|
134
|
+
// Verify TOTP & delete workspace on server
|
|
135
|
+
return { deletedId: workspaceId, verifiedWith: totpCode.length };
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
function* promptTotpCode(workspaceName: string): Generator<any, string | null, any> {
|
|
139
|
+
let code = "";
|
|
140
|
+
let decision: "confirm" | "cancel" | null = null;
|
|
141
|
+
|
|
142
|
+
while (decision === null) {
|
|
143
|
+
yield (
|
|
144
|
+
<div class="danger-modal" role="alertdialog">
|
|
145
|
+
<h3>Delete {workspaceName}?</h3>
|
|
146
|
+
<p>Enter your 6-digit authenticator code to confirm permanent deletion.</p>
|
|
147
|
+
<input bind:value={code} maxLength={6} placeholder="000000" />
|
|
148
|
+
<div class="actions">
|
|
149
|
+
<button type="button" onClick={() => (decision = "cancel")}>
|
|
150
|
+
Cancel
|
|
151
|
+
</button>
|
|
152
|
+
<button
|
|
153
|
+
type="button"
|
|
154
|
+
disabled={code.length !== 6}
|
|
155
|
+
onClick={() => (decision = "confirm")}
|
|
156
|
+
>
|
|
157
|
+
Permanently Delete
|
|
158
|
+
</button>
|
|
159
|
+
</div>
|
|
160
|
+
</div>
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
return decision === "confirm" ? code : null;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export function* DangerZone(
|
|
168
|
+
props: { id: string; name: string },
|
|
169
|
+
ctx: Ctx<{ id: string; name: string }>,
|
|
170
|
+
) {
|
|
171
|
+
let confirming = false;
|
|
172
|
+
let deleted = false;
|
|
173
|
+
|
|
174
|
+
for (props of ctx) {
|
|
175
|
+
if (deleted) {
|
|
176
|
+
yield <p>Workspace deleted.</p>;
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (confirming) {
|
|
181
|
+
// Delegates rendering to `promptTotpCode` and resumes here with `string | null`!
|
|
182
|
+
const totp = yield* promptTotpCode(props.name);
|
|
183
|
+
confirming = false;
|
|
184
|
+
if (totp) {
|
|
185
|
+
await deleteWorkspace(props.id, totp);
|
|
186
|
+
deleted = true;
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
yield (
|
|
192
|
+
<button class="danger" onClick={() => (confirming = true)}>
|
|
193
|
+
Delete Workspace…
|
|
194
|
+
</button>
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
```
|