@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
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
# 04. Routing, Nested Layouts, URL State, and Webhooks
|
|
2
|
+
|
|
3
|
+
`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.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. File-System Route Mapping
|
|
8
|
+
|
|
9
|
+
| File in `src/routes/` | Matched URL Pattern | Notes |
|
|
10
|
+
| --------------------------- | ------------------------------------------- | ------------------------------------------------------------ |
|
|
11
|
+
| `index.tsx` | `/` | Root home page |
|
|
12
|
+
| `pricing.tsx` | `/pricing` | Static segment (score `100` per segment) |
|
|
13
|
+
| `projects/index.tsx` | `/projects` | Directory index |
|
|
14
|
+
| `projects/[id].tsx` | `/projects/:id` | Dynamic parameter (`props.params.id`, score `10`) |
|
|
15
|
+
| `docs/[...slug].tsx` | `/docs/*` | Catch-all parameter (`props.params.slug`, score `1`) |
|
|
16
|
+
| `layout.tsx` | Wraps `/` and all descendants | Persistent root layout (`props.children`) |
|
|
17
|
+
| `(marketing)/layout.tsx` | Pathless layout group | Wraps `(marketing)/*` without adding `/marketing` to the URL |
|
|
18
|
+
| `(app)/dashboard/index.tsx` | `/dashboard` | Inherits both root `layout.tsx` and `(app)/layout.tsx` |
|
|
19
|
+
| `404.tsx` | Any unmatched route (or `throw notFound()`) | Rendered with HTTP `404` inside root `layout.tsx` |
|
|
20
|
+
| `error.tsx` | Root `<ErrorBoundary>` fallback | Catches uncaught SSR & client errors (`{ error, reset }`) |
|
|
21
|
+
| `api/stripe.ts` | `/api/stripe` | Server-only HTTP verb endpoint (`POST`, `GET`, etc.) |
|
|
22
|
+
|
|
23
|
+
> **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.
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## 2. Zero-Codegen Typed Route Params (`RouteProps<Path>`)
|
|
28
|
+
|
|
29
|
+
Use `RouteProps<"/projects/[id]/tasks/[taskId]">` to infer `props.params` purely at the TypeScript type level with zero generated `.d.ts` files:
|
|
30
|
+
|
|
31
|
+
```tsx
|
|
32
|
+
import { useRoute, type RouteProps } from "@fierst/c7t";
|
|
33
|
+
|
|
34
|
+
export default function* TaskDetailPage(props: RouteProps<"/projects/[id]/tasks/[taskId]">) {
|
|
35
|
+
// TypeScript infers: props.params = { id: string; taskId: string }
|
|
36
|
+
return () => (
|
|
37
|
+
<article>
|
|
38
|
+
<h1>
|
|
39
|
+
Project {props.params.id} — Task #{props.params.taskId}
|
|
40
|
+
</h1>
|
|
41
|
+
<p>Pathname: {props.pathname}</p>
|
|
42
|
+
</article>
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Deep child components can also read route state via `useRoute()`
|
|
47
|
+
export function Breadcrumb() {
|
|
48
|
+
const route = useRoute();
|
|
49
|
+
return <nav aria-label="Breadcrumb">Current path: {route.pathname}</nav>;
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## 3. Persistent Nested & Pathless Group Layouts
|
|
56
|
+
|
|
57
|
+
Layouts render `{props.children}` inside a `<c7t-outlet>` boundary. When navigating from `/projects/alpha` to `/projects/beta`:
|
|
58
|
+
|
|
59
|
+
- **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!
|
|
60
|
+
- **Outgoing child page generators dispose cleanly** (`ctx.signal` aborts in-flight requests and `finally` blocks run) before the incoming page mounts.
|
|
61
|
+
- **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.
|
|
62
|
+
|
|
63
|
+
```tsx
|
|
64
|
+
// src/routes/(app)/layout.tsx
|
|
65
|
+
import type { RouteProps } from "@fierst/c7t";
|
|
66
|
+
|
|
67
|
+
export default function* AppShellLayout(props: RouteProps) {
|
|
68
|
+
let sidebarCollapsed = false;
|
|
69
|
+
|
|
70
|
+
return () => (
|
|
71
|
+
<div class="workspace-grid" class:collapsed={sidebarCollapsed}>
|
|
72
|
+
<aside>
|
|
73
|
+
<button onClick={() => (sidebarCollapsed = !sidebarCollapsed)}>
|
|
74
|
+
{sidebarCollapsed ? "Expand" : "Collapse"}
|
|
75
|
+
</button>
|
|
76
|
+
<nav>
|
|
77
|
+
<a href="/dashboard">Dashboard</a>
|
|
78
|
+
<a href="/settings">Settings</a>
|
|
79
|
+
</nav>
|
|
80
|
+
</aside>
|
|
81
|
+
<div class="workspace-content">{props.children}</div>
|
|
82
|
+
</div>
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## 4. Custom `404.tsx` and `error.tsx` Boundaries
|
|
90
|
+
|
|
91
|
+
Create `src/routes/404.tsx` and `src/routes/error.tsx` to handle missing routes and unexpected runtime exceptions automatically:
|
|
92
|
+
|
|
93
|
+
```tsx
|
|
94
|
+
// src/routes/404.tsx
|
|
95
|
+
import { head } from "@fierst/c7t";
|
|
96
|
+
|
|
97
|
+
export default function NotFoundPage(props: { pathname: string }) {
|
|
98
|
+
head({ title: "404 — Page Not Found" });
|
|
99
|
+
return (
|
|
100
|
+
<section>
|
|
101
|
+
<h1>Page not found</h1>
|
|
102
|
+
<p>
|
|
103
|
+
We couldn't find <code>{props.pathname}</code>.
|
|
104
|
+
</p>
|
|
105
|
+
<a href="/">Back to Dashboard</a>
|
|
106
|
+
</section>
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
```tsx
|
|
112
|
+
// src/routes/error.tsx
|
|
113
|
+
export default function GlobalErrorFallback(props: { error: unknown; reset: () => void }) {
|
|
114
|
+
const message = props.error instanceof Error ? props.error.message : "Unexpected error";
|
|
115
|
+
|
|
116
|
+
return (
|
|
117
|
+
<section role="alert" class="error-panel">
|
|
118
|
+
<h2>Something went wrong</h2>
|
|
119
|
+
<p>{message}</p>
|
|
120
|
+
<button onClick={props.reset}>Try Again</button>
|
|
121
|
+
</section>
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## 5. Isomorphic Document Metadata (`head()`)
|
|
129
|
+
|
|
130
|
+
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:
|
|
131
|
+
|
|
132
|
+
```tsx
|
|
133
|
+
import { head } from "@fierst/c7t";
|
|
134
|
+
|
|
135
|
+
export default function* BlogPostPage() {
|
|
136
|
+
const post = yield* getPost();
|
|
137
|
+
|
|
138
|
+
head({
|
|
139
|
+
title: `${post.title} — Fierst Engineering`,
|
|
140
|
+
description: post.summary,
|
|
141
|
+
canonical: `https://example.com/blog/${post.slug}`,
|
|
142
|
+
meta: [
|
|
143
|
+
{ property: "og:title", content: post.title },
|
|
144
|
+
{ property: "og:type", content: "article" },
|
|
145
|
+
{ name: "twitter:card", content: "summary_large_image" },
|
|
146
|
+
],
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
return () => (
|
|
150
|
+
<article>
|
|
151
|
+
<h1>{post.title}</h1>
|
|
152
|
+
</article>
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
---
|
|
158
|
+
|
|
159
|
+
## 6. Bindable URL Search Params (`searchParam()`)
|
|
160
|
+
|
|
161
|
+
`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`!
|
|
162
|
+
|
|
163
|
+
- Writing its default value automatically **removes** the query key to keep URLs clean (`?q=` disappears when cleared!).
|
|
164
|
+
- Defaults to `replace: true` so typing into a search box doesn't spam browser Back history; pass `{ replace: false }` for discrete pagination steps.
|
|
165
|
+
|
|
166
|
+
```tsx
|
|
167
|
+
import { searchParam } from "@fierst/c7t";
|
|
168
|
+
|
|
169
|
+
export default function* DirectoryFilter() {
|
|
170
|
+
const q = searchParam("q", "");
|
|
171
|
+
const page = searchParam("page", 1, { replace: false });
|
|
172
|
+
const activeOnly = searchParam("active", false);
|
|
173
|
+
|
|
174
|
+
return () => (
|
|
175
|
+
<section>
|
|
176
|
+
{/* Two-way bound straight to `?q=...` and `?active=true`! */}
|
|
177
|
+
<input bind:value={q} placeholder="Filter members…" />
|
|
178
|
+
<label>
|
|
179
|
+
<input type="checkbox" bind:checked={activeOnly} />
|
|
180
|
+
Active only
|
|
181
|
+
</label>
|
|
182
|
+
|
|
183
|
+
<p>
|
|
184
|
+
Showing query "{q()}" (page {page()})
|
|
185
|
+
</p>
|
|
186
|
+
<button onClick={() => page.update((n) => n + 1)}>Next Page</button>
|
|
187
|
+
</section>
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
---
|
|
193
|
+
|
|
194
|
+
## 7. Hover / Focus Preloading & Escape Attributes
|
|
195
|
+
|
|
196
|
+
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.
|
|
197
|
+
|
|
198
|
+
Control link behavior with two HTML attributes:
|
|
199
|
+
|
|
200
|
+
- `data-c7t-preload="off"` — Disable hover/focus preloading on a specific `<a href>` (e.g. a sign-out link).
|
|
201
|
+
- `data-c7t-reload` — Bypass the client router and perform a full browser document load.
|
|
202
|
+
|
|
203
|
+
Programmatic navigation is also available via `import { navigate } from "@fierst/c7t"`:
|
|
204
|
+
|
|
205
|
+
```ts
|
|
206
|
+
await navigate("/projects/alpha", { replace: false, transition: true });
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
---
|
|
210
|
+
|
|
211
|
+
## 8. File-System HTTP API & Webhook Endpoints
|
|
212
|
+
|
|
213
|
+
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.
|
|
214
|
+
|
|
215
|
+
Files without a `default` UI component export are **100% excluded from the client browser bundle**:
|
|
216
|
+
|
|
217
|
+
```ts
|
|
218
|
+
// src/routes/api/webhooks/stripe.ts
|
|
219
|
+
import type { Context } from "hono";
|
|
220
|
+
import { cookies } from "@fierst/c7t/server";
|
|
221
|
+
|
|
222
|
+
export async function POST(c: Context) {
|
|
223
|
+
const signature = c.req.header("stripe-signature");
|
|
224
|
+
if (!signature) {
|
|
225
|
+
return c.json({ error: "Missing signature" }, 400);
|
|
226
|
+
}
|
|
227
|
+
const rawBody = await c.req.text();
|
|
228
|
+
// Verify webhook signature & process event...
|
|
229
|
+
return c.json({ received: true, bytes: rawBody.length });
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export function GET(c: Context) {
|
|
233
|
+
const sid = cookies.get("sid") ?? null;
|
|
234
|
+
return c.json({ status: "healthy", authenticated: Boolean(sid) });
|
|
235
|
+
}
|
|
236
|
+
```
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
# 05. Authentication, Sessions, Environment Variables, and Security
|
|
2
|
+
|
|
3
|
+
`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.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Ambient `req` & `cookies` (`AsyncLocalStorage`)
|
|
8
|
+
|
|
9
|
+
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:
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { server } from "@fierst/c7t";
|
|
13
|
+
import { cookies, req } from "@fierst/c7t/server";
|
|
14
|
+
|
|
15
|
+
export const getClientDiagnostics = server(async () => {
|
|
16
|
+
const userAgent = req.headers.get("user-agent") ?? "unknown";
|
|
17
|
+
const theme = cookies.get("theme") ?? "system";
|
|
18
|
+
return { url: req.url, method: req.method, userAgent, theme };
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
export const setThemePreference = server(async (theme: "light" | "dark") => {
|
|
22
|
+
cookies.set("theme", theme, {
|
|
23
|
+
httpOnly: false,
|
|
24
|
+
sameSite: "Lax",
|
|
25
|
+
maxAge: 60 * 60 * 24 * 365,
|
|
26
|
+
});
|
|
27
|
+
return { theme };
|
|
28
|
+
});
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## 2. Web-Crypto Signed Cookie Sessions (`createSession()`)
|
|
34
|
+
|
|
35
|
+
`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**.
|
|
36
|
+
|
|
37
|
+
- Sets `httpOnly: true`, `sameSite: "Lax"`, and `secure: true` (automatically on `https://`) by default.
|
|
38
|
+
- Rejects tampered payloads or forged signatures in constant time via `crypto.subtle.verify()`.
|
|
39
|
+
- 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!
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
// src/lib/auth.server.ts
|
|
43
|
+
import { redirect, server, unauthorized } from "@fierst/c7t";
|
|
44
|
+
import { createSession } from "@fierst/c7t/server";
|
|
45
|
+
import * as v from "valibot";
|
|
46
|
+
|
|
47
|
+
export interface SessionData {
|
|
48
|
+
userId: string;
|
|
49
|
+
email: string;
|
|
50
|
+
role: "admin" | "member";
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export const authSession = createSession<SessionData>({
|
|
54
|
+
name: "app_session",
|
|
55
|
+
// Rotate secrets without logging anyone out: [newKey, oldKey]
|
|
56
|
+
secret: [process.env.SESSION_SECRET ?? "dev-only-secret-at-least-32-chars-long!"],
|
|
57
|
+
maxAge: 60 * 60 * 24 * 7, // 7 days
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
export const getCurrentUser = server(async () => {
|
|
61
|
+
return authSession.get(); // SessionData | null
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
export const login = server(
|
|
65
|
+
v.object({
|
|
66
|
+
email: v.pipe(v.string(), v.email()),
|
|
67
|
+
password: v.pipe(v.string(), v.minLength(8)),
|
|
68
|
+
}),
|
|
69
|
+
async ({ email, password }) => {
|
|
70
|
+
// Replace with real password hash check (e.g. Scrypt / Argon2 / WebCrypto PBKDF2)
|
|
71
|
+
if (password !== "correct-horse-battery") {
|
|
72
|
+
throw unauthorized("Invalid email or password");
|
|
73
|
+
}
|
|
74
|
+
await authSession.set({
|
|
75
|
+
userId: "usr_01",
|
|
76
|
+
email,
|
|
77
|
+
role: "admin",
|
|
78
|
+
});
|
|
79
|
+
return { email };
|
|
80
|
+
},
|
|
81
|
+
);
|
|
82
|
+
|
|
83
|
+
export const logout = server(async () => {
|
|
84
|
+
authSession.clear();
|
|
85
|
+
throw redirect("/login", 303);
|
|
86
|
+
});
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## 3. Inline Auth Gates vs `redirect()`
|
|
92
|
+
|
|
93
|
+
With `c7t`, you can protect routes in two complementary ways:
|
|
94
|
+
|
|
95
|
+
### Pattern A: HTTP Redirect (`throw redirect("/login")`)
|
|
96
|
+
|
|
97
|
+
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:
|
|
98
|
+
|
|
99
|
+
```tsx
|
|
100
|
+
import { redirect } from "@fierst/c7t";
|
|
101
|
+
import { getCurrentUser } from "../lib/auth.server";
|
|
102
|
+
|
|
103
|
+
export default function* BillingPage() {
|
|
104
|
+
const user = yield* getCurrentUser();
|
|
105
|
+
if (!user) throw redirect("/login");
|
|
106
|
+
|
|
107
|
+
return () => <h1>Billing for {user.email}</h1>;
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### Pattern B: Zero-Redirect Inline Auth Gate
|
|
112
|
+
|
|
113
|
+
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!
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
## 4. Custom Hono Middleware & `RequestContext` Augmentation
|
|
118
|
+
|
|
119
|
+
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()`:
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
// src/server.ts
|
|
123
|
+
import { createServer, req } from "@fierst/c7t/server";
|
|
124
|
+
import { authSession, type SessionData } from "./lib/auth.server";
|
|
125
|
+
|
|
126
|
+
// Augment `RequestContext` once — `req.user` is now typed everywhere!
|
|
127
|
+
declare module "@fierst/c7t/server" {
|
|
128
|
+
interface RequestContext {
|
|
129
|
+
user: SessionData | null;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export default createServer({
|
|
134
|
+
middleware: [
|
|
135
|
+
async (c, next) => {
|
|
136
|
+
req.user = await authSession.get();
|
|
137
|
+
await next();
|
|
138
|
+
},
|
|
139
|
+
],
|
|
140
|
+
configure(app) {
|
|
141
|
+
// Optional raw Hono escape hatch (custom sub-apps, OpenAPI docs, metrics)
|
|
142
|
+
app.get("/healthz", (c) => c.json({ ok: true }));
|
|
143
|
+
},
|
|
144
|
+
});
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
## 5. Isomorphic Environment Validation (`defineEnv()`)
|
|
150
|
+
|
|
151
|
+
`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:
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
// src/env.ts
|
|
155
|
+
import { defineEnv } from "@fierst/c7t";
|
|
156
|
+
import * as v from "valibot";
|
|
157
|
+
|
|
158
|
+
export const env = defineEnv({
|
|
159
|
+
server: {
|
|
160
|
+
DATABASE_URL: v.pipe(v.string(), v.url()),
|
|
161
|
+
STRIPE_SECRET_KEY: v.pipe(v.string(), v.startsWith("sk_")),
|
|
162
|
+
},
|
|
163
|
+
public: {
|
|
164
|
+
PUBLIC_APP_NAME: v.optional(v.string(), "Construct"),
|
|
165
|
+
},
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
// Safe anywhere (SSR & Browser): env.PUBLIC_APP_NAME
|
|
169
|
+
// Safe on Server; throws "[c7t] Attempted to access server-only environment variable..." in Browser: env.STRIPE_SECRET_KEY
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
---
|
|
173
|
+
|
|
174
|
+
## 6. Built-In Security Protections
|
|
175
|
+
|
|
176
|
+
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`).
|
|
177
|
+
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.
|
|
178
|
+
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.
|
|
179
|
+
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.
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
# 06. Static Site Generation (SSG) and Deployment Adapters
|
|
2
|
+
|
|
3
|
+
`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.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Hybrid Per-Route Prerendering (`export const prerender`)
|
|
8
|
+
|
|
9
|
+
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`:
|
|
10
|
+
|
|
11
|
+
### Static Route (`prerender = true`)
|
|
12
|
+
|
|
13
|
+
```tsx
|
|
14
|
+
// src/routes/pricing.tsx
|
|
15
|
+
import { head, server } from "@fierst/c7t";
|
|
16
|
+
|
|
17
|
+
export const prerender = true;
|
|
18
|
+
|
|
19
|
+
const loadPricingTiers = server(async () => [
|
|
20
|
+
{ name: "Starter", price: "\$0" },
|
|
21
|
+
{ name: "Pro", price: "\$29" },
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
export default function* PricingPage() {
|
|
25
|
+
const tiers = yield* loadPricingTiers();
|
|
26
|
+
head({ title: "Pricing" });
|
|
27
|
+
|
|
28
|
+
return () => (
|
|
29
|
+
<section>
|
|
30
|
+
<h1>Pricing</h1>
|
|
31
|
+
<ul>
|
|
32
|
+
{tiers.map((t) => (
|
|
33
|
+
<li key={t.name}>
|
|
34
|
+
{t.name}: {t.price}
|
|
35
|
+
</li>
|
|
36
|
+
))}
|
|
37
|
+
</ul>
|
|
38
|
+
</section>
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Dynamic Parameterized Route (`prerender = async () => [...]`)
|
|
44
|
+
|
|
45
|
+
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!
|
|
46
|
+
|
|
47
|
+
```tsx
|
|
48
|
+
// src/routes/blog/[slug].tsx
|
|
49
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
50
|
+
import { head, server, type RouteProps } from "@fierst/c7t";
|
|
51
|
+
|
|
52
|
+
export async function prerender() {
|
|
53
|
+
const files = await readdir("./content/blog");
|
|
54
|
+
return files.filter((f) => f.endsWith(".md")).map((f) => ({ slug: f.replace(/\.md$/, "") }));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const getPost = server(async (slug: string) => {
|
|
58
|
+
const body = await readFile(`./content/blog/${slug}.md`, "utf-8");
|
|
59
|
+
return { slug, body };
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
export default function* BlogPost(props: RouteProps<"/blog/[slug]">) {
|
|
63
|
+
const post = yield* getPost(props.params.slug);
|
|
64
|
+
head({ title: post.slug });
|
|
65
|
+
return () => <article>{post.body}</article>;
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### How `__c7t.json` Static Receipt Sidecars Work
|
|
70
|
+
|
|
71
|
+
For every prerendered route (e.g. `/blog/hello`), `c7t build` writes **two** static files into `dist/client/`:
|
|
72
|
+
|
|
73
|
+
1. `dist/client/blog/hello/index.html` — Served directly from CDN/disk on initial page visits with embedded State Receipts.
|
|
74
|
+
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**!
|
|
75
|
+
|
|
76
|
+
---
|
|
77
|
+
|
|
78
|
+
## 2. Automatic Zero-JS Pages (`csr: "auto"`) & Cascading Route Defaults
|
|
79
|
+
|
|
80
|
+
Out of the box, `c7t` defaults to **`csr: "auto"`** across every route—meaning **you almost never need to write `export const csr = false`!**
|
|
81
|
+
|
|
82
|
+
### How `csr` Modes Work
|
|
83
|
+
|
|
84
|
+
| `csr` Value | Behavior |
|
|
85
|
+
| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
86
|
+
| **`"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. |
|
|
87
|
+
| **`"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>`. |
|
|
88
|
+
| **`true`** | Always include the client SPA router + lazy revival bootstrap, even on purely stateless pages. |
|
|
89
|
+
| **`false`** | Strict 0-JS lock — omit all island markers and `<script>` tags even if a stateful component rendered. |
|
|
90
|
+
|
|
91
|
+
### Cascading `prerender` & `csr` Inheritance (`vite.config.ts` -> `layout.tsx` -> `route.tsx`)
|
|
92
|
+
|
|
93
|
+
Both `prerender` and `csr` cascade cleanly from **project config -> ancestor `layout.tsx` -> leaf `route.tsx`**, so you never repeat flags across dozens of files:
|
|
94
|
+
|
|
95
|
+
1. **Pure Static Marketing / Docs Site (`staticAdapter()`):**
|
|
96
|
+
- `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!**
|
|
97
|
+
2. **Marketing-Heavy Hybrid Site (`c7t({ prerender: true, csr: "islands" })`):**
|
|
98
|
+
- Every static route prerenders with 0-JS-by-default MPA islands, and your 1–2 live dynamic routes simply opt out with one line:
|
|
99
|
+
```tsx
|
|
100
|
+
// src/routes/portal.tsx — stays live SSR while the rest of the site prerenders!
|
|
101
|
+
export const prerender = false;
|
|
102
|
+
export const csr = true;
|
|
103
|
+
```
|
|
104
|
+
3. **Mixed SaaS + Marketing Monolith via Pathless Group Layouts:**
|
|
105
|
+
- 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!
|
|
106
|
+
|
|
107
|
+
```tsx
|
|
108
|
+
// src/routes/terms.tsx — 0 flags needed!
|
|
109
|
+
// Plain `function` + stateless layout => 0 <blokd-island>s => 0 <script> tags emitted automatically!
|
|
110
|
+
export default function TermsOfService() {
|
|
111
|
+
return (
|
|
112
|
+
<main>
|
|
113
|
+
<h1>Terms of Service</h1>
|
|
114
|
+
<p>100% pure HTML & CSS — zero script tags emitted automatically.</p>
|
|
115
|
+
</main>
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
---
|
|
121
|
+
|
|
122
|
+
## 3. Prerendering `sitemap.xml`, `rss.xml`, & Broken-Link Detection
|
|
123
|
+
|
|
124
|
+
- **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`!
|
|
125
|
+
- **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.
|
|
126
|
+
- **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.
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
## 4. Official Deployment Adapters
|
|
131
|
+
|
|
132
|
+
Configure your target adapter in `vite.config.ts` (or override on the CLI via `c7t build --adapter=<name>`):
|
|
133
|
+
|
|
134
|
+
### A. Node.js (`@fierst/c7t/node` — Default)
|
|
135
|
+
|
|
136
|
+
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:
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
// vite.config.ts
|
|
140
|
+
import { defineConfig } from "vite-plus";
|
|
141
|
+
import c7t from "@fierst/c7t/vite";
|
|
142
|
+
import { nodeAdapter } from "@fierst/c7t/node";
|
|
143
|
+
|
|
144
|
+
export default defineConfig({
|
|
145
|
+
plugins: [c7t({ adapter: nodeAdapter({ port: 3000 }) })],
|
|
146
|
+
});
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
Run in production (even in a minimal Docker image without `node_modules`—`dist/` is self-contained!):
|
|
150
|
+
|
|
151
|
+
```bash
|
|
152
|
+
c7t build
|
|
153
|
+
PORT=8080 node dist/server/start.mjs
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### B. Cloudflare Workers (`@fierst/c7t/cloudflare`)
|
|
157
|
+
|
|
158
|
+
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:
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
// vite.config.ts
|
|
162
|
+
import { defineConfig } from "vite-plus";
|
|
163
|
+
import c7t from "@fierst/c7t/vite";
|
|
164
|
+
import { cloudflarePreset } from "@fierst/c7t/cloudflare";
|
|
165
|
+
|
|
166
|
+
export default defineConfig({
|
|
167
|
+
plugins: [c7t({ adapter: cloudflarePreset({ assetsBinding: "ASSETS" }) })],
|
|
168
|
+
});
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Minimal `wrangler.jsonc`:
|
|
172
|
+
|
|
173
|
+
```jsonc
|
|
174
|
+
{
|
|
175
|
+
"name": "my-c7t-app",
|
|
176
|
+
"main": "dist/worker.mjs",
|
|
177
|
+
"compatibility_date": "2026-01-01",
|
|
178
|
+
"compatibility_flags": ["nodejs_als"],
|
|
179
|
+
"assets": {
|
|
180
|
+
"directory": "dist/client",
|
|
181
|
+
"binding": "ASSETS",
|
|
182
|
+
},
|
|
183
|
+
}
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
### C. Vercel (`@fierst/c7t/vercel` — Build Output API v3)
|
|
187
|
+
|
|
188
|
+
Emits a ready-to-deploy `.vercel/output` directory (`config.json` v3 + `static/` CDN assets/SSG sidecars + `functions/index.func` Web `fetch` handler):
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
// vite.config.ts
|
|
192
|
+
import { defineConfig } from "vite-plus";
|
|
193
|
+
import c7t from "@fierst/c7t/vite";
|
|
194
|
+
import { vercelAdapter } from "@fierst/c7t/vercel";
|
|
195
|
+
|
|
196
|
+
export default defineConfig({
|
|
197
|
+
plugins: [
|
|
198
|
+
c7t({
|
|
199
|
+
adapter: vercelAdapter({
|
|
200
|
+
runtime: "nodejs22.x",
|
|
201
|
+
regions: ["iad1"],
|
|
202
|
+
}),
|
|
203
|
+
}),
|
|
204
|
+
],
|
|
205
|
+
});
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Deploy with `c7t build && vercel deploy --prebuilt`.
|
|
209
|
+
|
|
210
|
+
### D. Bun (`@fierst/c7t/bun`)
|
|
211
|
+
|
|
212
|
+
Emits `dist/server/start.bun.mjs` powered by `Bun.serve()` and zero-copy `Bun.file()` static/SSG serving:
|
|
213
|
+
|
|
214
|
+
```ts
|
|
215
|
+
// vite.config.ts
|
|
216
|
+
import { defineConfig } from "vite-plus";
|
|
217
|
+
import c7t from "@fierst/c7t/vite";
|
|
218
|
+
import { bunAdapter } from "@fierst/c7t/bun";
|
|
219
|
+
|
|
220
|
+
export default defineConfig({
|
|
221
|
+
plugins: [c7t({ adapter: bunAdapter({ port: 3000 }) })],
|
|
222
|
+
});
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
Run with `c7t build && bun dist/server/start.bun.mjs`.
|
|
226
|
+
|
|
227
|
+
### E. Pure Static Site Hosting (`@fierst/c7t/static`)
|
|
228
|
+
|
|
229
|
+
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:
|
|
230
|
+
|
|
231
|
+
```ts
|
|
232
|
+
// vite.config.ts
|
|
233
|
+
import { defineConfig } from "vite-plus";
|
|
234
|
+
import c7t from "@fierst/c7t/vite";
|
|
235
|
+
import { staticAdapter } from "@fierst/c7t/static";
|
|
236
|
+
|
|
237
|
+
export default defineConfig({
|
|
238
|
+
plugins: [
|
|
239
|
+
c7t({
|
|
240
|
+
adapter: staticAdapter({
|
|
241
|
+
fallback: "404.html",
|
|
242
|
+
onBrokenLink: "error",
|
|
243
|
+
}),
|
|
244
|
+
}),
|
|
245
|
+
],
|
|
246
|
+
});
|
|
247
|
+
```
|