@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/CHANGELOG.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to **`@fierst/c7t` ("Construct")** are documented in this file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## [1.0.0] - 2026-11-30
|
|
8
|
+
|
|
9
|
+
Initial release of **`c7t` ("Construct" — `@fierst/c7t`)** — Fierst LLC's full-stack generator meta-framework built on `@fierst/blokd` (`>=1.3.0`), Hono, and Vite+ (`vp`).
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- **Dual-Protocol `server()` Callables & Parallel `all()` (`@fierst/c7t`):**
|
|
14
|
+
- `server(fn)` and `server(Schema, fn)` return `ServerCall<T>`, implementing both `Generator<StepEffect<T>, T, any>` (`yield*` in generator setup for direct SSR execution + 0-microtask State Receipt revival) and `PromiseLike<T>` (`await` in event handlers for live `POST /_c7t/rpc/:id` calls).
|
|
15
|
+
- Supports both colocated `server(...)` calls inside `.tsx` routes (with automatic Oxc dead server-import pruning) and dedicated `*.server.ts` module boundaries.
|
|
16
|
+
- `all([...calls])` parallel checkpoint combinator for waterfall-free concurrent queries.
|
|
17
|
+
- Standard Schema v1 input validation (Valibot, Zod, ArkType) returning HTTP `400` and reconstructing `ValidationError` with lazy dot-path `err.fields` on the client.
|
|
18
|
+
- Automatic `multipart/form-data` wire transport and `File` reconstruction whenever RPC arguments contain `File`, `Blob`, or `FormData`.
|
|
19
|
+
- **Bidirectional NDJSON Streaming (`server(async function* ...)`):**
|
|
20
|
+
- Streams `application/x-ndjson` frames over standard `fetch()`, automatically scheduling compiled DOM slot updates on each yielded chunk.
|
|
21
|
+
- Full cancellation propagation: breaking out of `for await` or unmounting aborts the HTTP request, triggers `req.signal`, and runs `gen.return()` (`finally` cleanup) on the server generator.
|
|
22
|
+
- **Hierarchical `$ref` State Receipts (`@fierst/c7t` & `@fierst/c7t/client`):**
|
|
23
|
+
- Per-request `(id, args)` SSR memoization, shared object pool `$ref` deduplication preserving reference identity (`a === b`), lossless `Date` / `URLSearchParams` encoding, and out-of-order streaming `<script>` receipt chunks.
|
|
24
|
+
- **Nested File-System Router, Layouts, & URL State (`@fierst/c7t/router`):**
|
|
25
|
+
- Automatic discovery of `src/routes/**` (`index.tsx`, `[param].tsx`, `[...catchall].tsx`, `layout.tsx`, pathless `(group)/layout.tsx` with duplicate-route collision detection, `404.tsx`, `error.tsx`, and HTTP verb endpoints `GET`/`POST`/`PUT`/`PATCH`/`DELETE`/`HEAD`/`OPTIONS`).
|
|
26
|
+
- Persistent `<c7t-outlet>` boundaries preserving parent layout `let` and `Context` state across client navigations with View Transitions and `pointerenter`/`focusin` preloading.
|
|
27
|
+
- Zero-codegen `RouteProps<Path>` template-literal param inference, `useRoute()`, isomorphic `head()` SEO metadata, and bindable `searchParam()` `Signal`s (`bind:value` / `bind:checked`).
|
|
28
|
+
- **Hono Server Runtime, Sessions, Env, & Security (`@fierst/c7t/server`):**
|
|
29
|
+
- `AsyncLocalStorage`-backed `req` and `cookies` proxies, augmentable `RequestContext`, and `createServer()` factory with zero-FOUC `<link rel="stylesheet">` injection in both `vp dev` and production.
|
|
30
|
+
- Zero-dependency Web-Crypto (`HMAC-SHA256`) `createSession()` with `httpOnly` cookies and `[currentSecret, oldSecret]` key rotation.
|
|
31
|
+
- ORM-agnostic lazy `defineDb()` proxy bridging Node/Bun connection pools and Cloudflare Workers per-request `req.env.DB` / Hyperdrive bindings, paired with opt-in `c7t create --db=sqlite|postgres|d1` Drizzle + `drizzle-valibot` starter presets.
|
|
32
|
+
- `defineEnv({ server, public })` Standard Schema environment validator across Cloudflare `req.env`, `process.env`, and `import.meta.env`.
|
|
33
|
+
- Built-in `Origin` / `Sec-Fetch-Site` CSRF guard, SHA-256 production RPC ID hashing, and `NODE_ENV="production"` `500` error masking.
|
|
34
|
+
- **Complete SSG Engine, 3-Stage `c7t build` CLI, & 5 Official Adapters:**
|
|
35
|
+
- `@fierst/c7t/ssg` (`prerenderApp`) supporting hybrid `export const prerender = true | false | (() => [...])` and full static `mode: "all"`, cascading `prerender` & `csr` inheritance (`c7t()` config -> `layout.tsx` -> leaf route), automatic `csr: "auto"` default (0 `<script>` tags when 0 islands render; automatic lazy revival when 1+ islands render) plus `csr: "islands"` MPA mode, `<a href>` link crawling, broken-link detection, `__c7t.json` static receipt sidecars, static XML/RSS endpoints, and build-time dynamic cookie guardrails.
|
|
36
|
+
- Unified `c7t` CLI (`c7t create`, `c7t build`, `c7t start`) and programmatic `buildApp()` pipeline.
|
|
37
|
+
- Official adapters: `@fierst/c7t/node`, `@fierst/c7t/cloudflare`, `@fierst/c7t/vercel` (Build Output API v3), `@fierst/c7t/bun`, and `@fierst/c7t/static`.
|
|
38
|
+
- Complete documentation suite (`docs/guides/01–07`, `docs/reference.md`, and generated `llms.txt` handbook) plus end-to-end Chromium production smoke test (`npm run test:smoke`).
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Fierst LLC
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,63 @@
|
|
|
1
|
-
#
|
|
1
|
+
# c7t ("Construct" — `@fierst/c7t`)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Full-stack generator meta-framework built on [`@fierst/blokd`](https://blokd.dev), [Hono](https://hono.dev), and [Vite+ (`vp`)](https://viteplus.dev).**
|
|
4
|
+
|
|
5
|
+
Write plain `let` state, `return () => (<JSX />)`, `yield*` server queries, `await` mutations, and `for await` real-time streams in cohesive `.tsx` route modules—with **zero VDOM**, **zero hydration waterfall**, **zero-FOUC CSS**, **hybrid SSG sidecars**, and **~2.5 kB gzip** of client runtime overhead.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Highlights
|
|
10
|
+
|
|
11
|
+
- **Dual-Protocol `server()` Callables:** Call `yield* getTasks()` in component setup (runs in-process on SSR, emits a `$ref`-deduplicated State Receipt, and revives synchronously in **0 microtasks** with **0 client refetches**) and `await addTask(text)` in event handlers (posts to `/_c7t/rpc/:hash` with Standard Schema validation & CSRF protection).
|
|
12
|
+
- **Bidirectional NDJSON Server Streams:** Export `server(async function* ...)` and consume with `for await (const chunk of stream())`. Breaking out of the loop or unmounting aborts the HTTP stream and runs your backend `finally` cleanup immediately.
|
|
13
|
+
- **Persistent Nested & Pathless Group Layouts:** File-system routing (`src/routes/**`) with `<c7t-outlet>` boundaries that preserve parent layout `let` state across View Transition navigations, plus `404.tsx`, `error.tsx`, `head()`, bindable `searchParam()`, and raw HTTP webhook routes (`GET`, `POST`, etc.).
|
|
14
|
+
- **Automatic Zero-JS Static Pages & Hybrid SSG:** Defaults to `csr: "auto"` (pages with 0 interactive islands automatically emit **0 `<script>` tags**; pages with `function*` islands wake lazily on interaction), cascading `prerender` & `csr` inheritance across `c7t()` config, `layout.tsx`, and routes, `<a href>` link crawling, and `__c7t.json` static receipt sidecars.
|
|
15
|
+
- **Built-In Auth, Databases, Multipart Uploads, & Validated Env:** Zero-dep Web-Crypto (`HMAC-SHA256`) `createSession()` with key rotation, ORM-agnostic `defineDb()` + `--db=sqlite|postgres|d1` Drizzle scaffolding, automatic `File`/`Blob` multipart RPC uploads, and `defineEnv()` across Cloudflare Workers, Node, and Vite.
|
|
16
|
+
- **5 Official Production Adapters:** Deploy to **Node.js** (`@fierst/c7t/node`), **Cloudflare Workers** (`@fierst/c7t/cloudflare`), **Vercel Build Output v3** (`@fierst/c7t/vercel`), **Bun** (`@fierst/c7t/bun`), or **Static CDNs** (`@fierst/c7t/static`).
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## Quick Start
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
# Scaffold a new Construct project (add --db=sqlite, --db=postgres, or --db=d1 for Drizzle ORM!)
|
|
24
|
+
npx @fierst/c7t my-app
|
|
25
|
+
cd my-app
|
|
26
|
+
npm install
|
|
27
|
+
|
|
28
|
+
# Start Vite+ SSR + HMR dev server
|
|
29
|
+
npm run dev
|
|
30
|
+
|
|
31
|
+
# Build 3-stage production output (Client -> SSR -> SSG + Adapter) & start server
|
|
32
|
+
npm run build
|
|
33
|
+
npm start
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## Documentation
|
|
39
|
+
|
|
40
|
+
Browse the [documentation index](./docs/README.md), jump straight into a guide, or look up signatures in the [API Reference](./docs/reference.md). The [single-file handbook (`llms.txt`)](./llms.txt) ships in every scaffolded project for AI coding assistants.
|
|
41
|
+
|
|
42
|
+
1. [01. Getting Started](./docs/guides/01-getting-started.md)
|
|
43
|
+
2. [02. Data Fetching, Validation, Optimistic UI, and File Uploads](./docs/guides/02-data-fetching-and-mutations.md)
|
|
44
|
+
3. [03. Streaming SSR, NDJSON Server Streams, and `yield*` Workflows](./docs/guides/03-streaming-and-workflows.md)
|
|
45
|
+
4. [04. Routing, Nested Layouts, URL State, and Webhooks](./docs/guides/04-routing-layouts-and-state.md)
|
|
46
|
+
5. [05. Authentication, Sessions, Environment Variables, and Security](./docs/guides/05-auth-sessions-and-security.md)
|
|
47
|
+
6. [06. Static Site Generation (SSG) and Deployment Adapters](./docs/guides/06-ssg-and-deployment.md)
|
|
48
|
+
7. [07. Databases, `defineDb()`, and Drizzle ORM](./docs/guides/07-databases-and-drizzle.md)
|
|
49
|
+
|
|
50
|
+
- [Complete API Reference & Troubleshooting](./docs/reference.md)
|
|
51
|
+
- [Changelog (`v1.0.0`)](./CHANGELOG.md)
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## Repository Commands
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
npm run check # Oxfmt + Oxlint + TypeScript type-check (0 warnings, 0 errors)
|
|
59
|
+
npm run test:node # Vitest Node suite (RPCs, Receipts, Router, Compiler, SSG, Sessions, Adapters)
|
|
60
|
+
npm run test:browser # Vitest Playwright Chromium suite (Lazy Revival, Streaming, SearchParams, SSG Sidecars)
|
|
61
|
+
npm run pack # Build dist/ ESM + .d.mts outputs
|
|
62
|
+
npm run test:smoke # End-to-end production scaffold -> c7t build -> Node server -> Chromium verification
|
|
63
|
+
```
|
package/bin/c7t.d.mts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/bin/c7t.mjs
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// c7t ("Construct") — Unified CLI (`c7t build`, `c7t start`, `c7t create <dir> [--db=...]`, or `c7t <dir>`)
|
|
3
|
+
|
|
4
|
+
import { existsSync } from "node:fs";
|
|
5
|
+
import { resolve } from "node:path";
|
|
6
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
7
|
+
import { scaffoldProject } from "./create.mjs";
|
|
8
|
+
|
|
9
|
+
function parseFlag(args, prefix) {
|
|
10
|
+
for (let i = 0; i < args.length; i++) {
|
|
11
|
+
const a = args[i];
|
|
12
|
+
if (a.startsWith(`${prefix}=`)) return a.slice(prefix.length + 1);
|
|
13
|
+
if (a === prefix && args[i + 1] && !args[i + 1].startsWith("-")) return args[i + 1];
|
|
14
|
+
}
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function collectPositional(args, valuedFlags) {
|
|
19
|
+
const out = [];
|
|
20
|
+
for (let i = 0; i < args.length; i++) {
|
|
21
|
+
const a = args[i];
|
|
22
|
+
if (valuedFlags.has(a) && args[i + 1]) {
|
|
23
|
+
i++;
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
if (!a.startsWith("-")) out.push(a);
|
|
27
|
+
}
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function runCli() {
|
|
32
|
+
const rawArgs = process.argv.slice(2);
|
|
33
|
+
const cmd = rawArgs[0];
|
|
34
|
+
|
|
35
|
+
if (cmd === "--help" || cmd === "-h" || cmd === "help") {
|
|
36
|
+
console.log(
|
|
37
|
+
[
|
|
38
|
+
"c7t (Construct) CLI",
|
|
39
|
+
"",
|
|
40
|
+
"Usage:",
|
|
41
|
+
" c7t <project-dir> [--db=sqlite|postgres|d1] Scaffold a new c7t project",
|
|
42
|
+
" c7t create <dir> [--db=sqlite|postgres|d1] Scaffold a new c7t project",
|
|
43
|
+
" c7t build [--adapter=<target>] Build client + SSR + SSG + adapter output",
|
|
44
|
+
" c7t start [--port=3000] Start built Node production server",
|
|
45
|
+
].join("\n"),
|
|
46
|
+
);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (cmd === "build") {
|
|
51
|
+
const adapterFlag = parseFlag(rawArgs, "--adapter");
|
|
52
|
+
const prerenderFlag = parseFlag(rawArgs, "--prerender");
|
|
53
|
+
const rootFlag = parseFlag(rawArgs, "--root");
|
|
54
|
+
|
|
55
|
+
const distViteUrl = new URL("../dist/vite.mjs", import.meta.url);
|
|
56
|
+
const srcViteUrl = new URL("../src/vite.ts", import.meta.url);
|
|
57
|
+
const viteMod = existsSync(fileURLToPath(distViteUrl))
|
|
58
|
+
? await import(distViteUrl.href)
|
|
59
|
+
: await import(srcViteUrl.href);
|
|
60
|
+
|
|
61
|
+
let prerender;
|
|
62
|
+
if (prerenderFlag === "false" || prerenderFlag === "0") prerender = false;
|
|
63
|
+
else if (prerenderFlag === "true" || prerenderFlag === "1" || prerenderFlag === "all")
|
|
64
|
+
prerender = "all";
|
|
65
|
+
else if (prerenderFlag === "marked") prerender = "marked";
|
|
66
|
+
|
|
67
|
+
const result = await viteMod.buildApp({
|
|
68
|
+
root: rootFlag ? resolve(process.cwd(), rootFlag) : process.cwd(),
|
|
69
|
+
adapter: adapterFlag,
|
|
70
|
+
prerender,
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
const pageCount = result.prerendered?.pages.length ?? 0;
|
|
74
|
+
console.log(
|
|
75
|
+
`[c7t] Built target "${result.adapter}" (${pageCount} prerendered page${pageCount === 1 ? "" : "s"}).`,
|
|
76
|
+
);
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (cmd === "start") {
|
|
81
|
+
const portFlag = parseFlag(rawArgs, "--port");
|
|
82
|
+
if (portFlag) process.env.PORT = portFlag;
|
|
83
|
+
process.env.NODE_ENV ??= "production";
|
|
84
|
+
const startFile = resolve(process.cwd(), "dist", "server", "start.mjs");
|
|
85
|
+
if (!existsSync(startFile)) {
|
|
86
|
+
throw new Error(`Missing "${startFile}". Run \`c7t build\` first.`);
|
|
87
|
+
}
|
|
88
|
+
await import(pathToFileURL(startFile).href);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const targetArgs = cmd === "create" ? rawArgs.slice(1) : rawArgs;
|
|
93
|
+
const dbFlag = parseFlag(targetArgs, "--db");
|
|
94
|
+
const positional = collectPositional(targetArgs, new Set(["--db"]));
|
|
95
|
+
const dir = positional[0] ?? "my-c7t-app";
|
|
96
|
+
const force = rawArgs.includes("--force") || rawArgs.includes("-f");
|
|
97
|
+
|
|
98
|
+
scaffoldProject(dir, { force, db: dbFlag });
|
|
99
|
+
console.log(`\nConstructed c7t project in ./${dir}${dbFlag ? ` (Drizzle ${dbFlag})` : ""}`);
|
|
100
|
+
const dbStep = dbFlag === "sqlite" || dbFlag === "postgres" ? "\n npm run db:push" : "";
|
|
101
|
+
console.log(`\nNext steps:\n cd ${dir}\n npm install${dbStep}\n npm run dev\n`);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
runCli().catch((err) => {
|
|
105
|
+
console.error(`[c7t] ${err instanceof Error ? err.message : String(err)}`);
|
|
106
|
+
process.exit(1);
|
|
107
|
+
});
|
package/bin/create.d.mts
ADDED
package/bin/create.mjs
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// c7t ("Construct") — Zero-Dependency Project Scaffolder (`npx @fierst/c7t my-app [--db=sqlite|postgres|d1]`)
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
cpSync,
|
|
6
|
+
existsSync,
|
|
7
|
+
mkdirSync,
|
|
8
|
+
readFileSync,
|
|
9
|
+
readdirSync,
|
|
10
|
+
rmSync,
|
|
11
|
+
writeFileSync,
|
|
12
|
+
} from "node:fs";
|
|
13
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
14
|
+
import { fileURLToPath } from "node:url";
|
|
15
|
+
|
|
16
|
+
const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
17
|
+
const selfPkg = JSON.parse(readFileSync(join(pkgRoot, "package.json"), "utf-8"));
|
|
18
|
+
const VALID_DB_PRESETS = new Set(["sqlite", "postgres", "d1"]);
|
|
19
|
+
|
|
20
|
+
function parseFlag(args, prefix) {
|
|
21
|
+
for (let i = 0; i < args.length; i++) {
|
|
22
|
+
const a = args[i];
|
|
23
|
+
if (a.startsWith(`${prefix}=`)) return a.slice(prefix.length + 1);
|
|
24
|
+
if (a === prefix && args[i + 1] && !args[i + 1].startsWith("-")) return args[i + 1];
|
|
25
|
+
}
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function writeDbFiles(absTarget, pkgName, dbPreset, pkg) {
|
|
30
|
+
const dbDir = join(absTarget, "src", "db");
|
|
31
|
+
mkdirSync(dbDir, { recursive: true });
|
|
32
|
+
|
|
33
|
+
pkg.dependencies["drizzle-orm"] = "^0.40.0";
|
|
34
|
+
pkg.dependencies["drizzle-valibot"] = "^0.4.0";
|
|
35
|
+
pkg.dependencies["valibot"] = "^1.0.0";
|
|
36
|
+
pkg.devDependencies["drizzle-kit"] = "^0.30.0";
|
|
37
|
+
|
|
38
|
+
pkg.scripts["db:generate"] = "drizzle-kit generate";
|
|
39
|
+
pkg.scripts["db:push"] = "drizzle-kit push";
|
|
40
|
+
pkg.scripts["db:studio"] = "drizzle-kit studio";
|
|
41
|
+
|
|
42
|
+
const sqliteSchema =
|
|
43
|
+
`import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";\n` +
|
|
44
|
+
`import { createInsertSchema } from "drizzle-valibot";\n` +
|
|
45
|
+
`import * as v from "valibot";\n\n` +
|
|
46
|
+
`export const notes = sqliteTable("notes", {\n` +
|
|
47
|
+
` id: integer("id").primaryKey({ autoIncrement: true }),\n` +
|
|
48
|
+
` text: text("text").notNull(),\n` +
|
|
49
|
+
` createdAt: integer("created_at", { mode: "timestamp" })\n` +
|
|
50
|
+
` .notNull()\n` +
|
|
51
|
+
` .$defaultFn(() => new Date()),\n` +
|
|
52
|
+
`});\n\n` +
|
|
53
|
+
`export const InsertNoteSchema = createInsertSchema(notes, {\n` +
|
|
54
|
+
` text: v.pipe(v.string(), v.trim(), v.minLength(1, "Please enter a note")),\n` +
|
|
55
|
+
`});\n`;
|
|
56
|
+
|
|
57
|
+
if (dbPreset === "sqlite") {
|
|
58
|
+
pkg.dependencies["@libsql/client"] = "^0.15.0";
|
|
59
|
+
writeFileSync(join(dbDir, "schema.ts"), sqliteSchema);
|
|
60
|
+
writeFileSync(
|
|
61
|
+
join(dbDir, "index.ts"),
|
|
62
|
+
`import { createClient } from "@libsql/client";\n` +
|
|
63
|
+
`import { drizzle } from "drizzle-orm/libsql";\n` +
|
|
64
|
+
`import { defineDb } from "@fierst/c7t/server";\n` +
|
|
65
|
+
`import * as schema from "./schema";\n\n` +
|
|
66
|
+
`export const db = defineDb((env) => {\n` +
|
|
67
|
+
` const client = createClient({\n` +
|
|
68
|
+
` url: env.DATABASE_URL ?? "file:local.db",\n` +
|
|
69
|
+
` authToken: env.DATABASE_AUTH_TOKEN,\n` +
|
|
70
|
+
` });\n` +
|
|
71
|
+
` return drizzle(client, { schema });\n` +
|
|
72
|
+
`});\n\n` +
|
|
73
|
+
`export * from "./schema";\n`,
|
|
74
|
+
);
|
|
75
|
+
writeFileSync(
|
|
76
|
+
join(absTarget, "drizzle.config.ts"),
|
|
77
|
+
`import { defineConfig } from "drizzle-kit";\n\n` +
|
|
78
|
+
`export default defineConfig({\n` +
|
|
79
|
+
` schema: "./src/db/schema.ts",\n` +
|
|
80
|
+
` out: "./drizzle",\n` +
|
|
81
|
+
` dialect: "sqlite",\n` +
|
|
82
|
+
` dbCredentials: {\n` +
|
|
83
|
+
` url: process.env.DATABASE_URL ?? "file:local.db",\n` +
|
|
84
|
+
` },\n` +
|
|
85
|
+
`});\n`,
|
|
86
|
+
);
|
|
87
|
+
const envBody = `DATABASE_URL="file:local.db"\n# Optional Turso token:\n# DATABASE_AUTH_TOKEN=""\n`;
|
|
88
|
+
writeFileSync(join(absTarget, ".env.example"), envBody);
|
|
89
|
+
writeFileSync(join(absTarget, ".env"), `DATABASE_URL="file:local.db"\n`);
|
|
90
|
+
} else if (dbPreset === "postgres") {
|
|
91
|
+
pkg.dependencies["postgres"] = "^3.4.5";
|
|
92
|
+
writeFileSync(
|
|
93
|
+
join(dbDir, "schema.ts"),
|
|
94
|
+
`import { pgTable, serial, text, timestamp } from "drizzle-orm/pg-core";\n` +
|
|
95
|
+
`import { createInsertSchema } from "drizzle-valibot";\n` +
|
|
96
|
+
`import * as v from "valibot";\n\n` +
|
|
97
|
+
`export const notes = pgTable("notes", {\n` +
|
|
98
|
+
` id: serial("id").primaryKey(),\n` +
|
|
99
|
+
` text: text("text").notNull(),\n` +
|
|
100
|
+
` createdAt: timestamp("created_at").defaultNow().notNull(),\n` +
|
|
101
|
+
`});\n\n` +
|
|
102
|
+
`export const InsertNoteSchema = createInsertSchema(notes, {\n` +
|
|
103
|
+
` text: v.pipe(v.string(), v.trim(), v.minLength(1, "Please enter a note")),\n` +
|
|
104
|
+
`});\n`,
|
|
105
|
+
);
|
|
106
|
+
writeFileSync(
|
|
107
|
+
join(dbDir, "index.ts"),
|
|
108
|
+
`import { drizzle } from "drizzle-orm/postgres-js";\n` +
|
|
109
|
+
`import postgres from "postgres";\n` +
|
|
110
|
+
`import { defineDb } from "@fierst/c7t/server";\n` +
|
|
111
|
+
`import * as schema from "./schema";\n\n` +
|
|
112
|
+
`export const db = defineDb((env) => {\n` +
|
|
113
|
+
` if (!env.DATABASE_URL) {\n` +
|
|
114
|
+
` throw new Error("Missing DATABASE_URL environment variable");\n` +
|
|
115
|
+
` }\n` +
|
|
116
|
+
` const client = postgres(env.DATABASE_URL);\n` +
|
|
117
|
+
` return drizzle(client, { schema });\n` +
|
|
118
|
+
`});\n\n` +
|
|
119
|
+
`export * from "./schema";\n`,
|
|
120
|
+
);
|
|
121
|
+
writeFileSync(
|
|
122
|
+
join(absTarget, "drizzle.config.ts"),
|
|
123
|
+
`import { defineConfig } from "drizzle-kit";\n\n` +
|
|
124
|
+
`export default defineConfig({\n` +
|
|
125
|
+
` schema: "./src/db/schema.ts",\n` +
|
|
126
|
+
` out: "./drizzle",\n` +
|
|
127
|
+
` dialect: "postgresql",\n` +
|
|
128
|
+
` dbCredentials: {\n` +
|
|
129
|
+
` url: process.env.DATABASE_URL!,\n` +
|
|
130
|
+
` },\n` +
|
|
131
|
+
`});\n`,
|
|
132
|
+
);
|
|
133
|
+
writeFileSync(
|
|
134
|
+
join(absTarget, ".env.example"),
|
|
135
|
+
`DATABASE_URL="postgres://postgres:postgres@localhost:5432/${pkgName.replace(/-/g, "_")}"\n`,
|
|
136
|
+
);
|
|
137
|
+
} else if (dbPreset === "d1") {
|
|
138
|
+
pkg.devDependencies["wrangler"] = "^4.0.0";
|
|
139
|
+
pkg.scripts["deploy"] = "c7t build && wrangler deploy";
|
|
140
|
+
writeFileSync(join(dbDir, "schema.ts"), sqliteSchema);
|
|
141
|
+
writeFileSync(
|
|
142
|
+
join(dbDir, "index.ts"),
|
|
143
|
+
`import { drizzle } from "drizzle-orm/d1";\n` +
|
|
144
|
+
`import { defineDb } from "@fierst/c7t/server";\n` +
|
|
145
|
+
`import * as schema from "./schema";\n\n` +
|
|
146
|
+
`export const db = defineDb((env) => {\n` +
|
|
147
|
+
` if (!env.DB) {\n` +
|
|
148
|
+
` throw new Error('Missing Cloudflare D1 binding "DB" on req.env');\n` +
|
|
149
|
+
` }\n` +
|
|
150
|
+
` return drizzle(env.DB, { schema });\n` +
|
|
151
|
+
`});\n\n` +
|
|
152
|
+
`export * from "./schema";\n`,
|
|
153
|
+
);
|
|
154
|
+
writeFileSync(
|
|
155
|
+
join(absTarget, "drizzle.config.ts"),
|
|
156
|
+
`import { defineConfig } from "drizzle-kit";\n\n` +
|
|
157
|
+
`export default defineConfig({\n` +
|
|
158
|
+
` schema: "./src/db/schema.ts",\n` +
|
|
159
|
+
` out: "./drizzle",\n` +
|
|
160
|
+
` dialect: "sqlite",\n` +
|
|
161
|
+
`});\n`,
|
|
162
|
+
);
|
|
163
|
+
writeFileSync(
|
|
164
|
+
join(absTarget, "vite.config.ts"),
|
|
165
|
+
`import { defineConfig } from "vite-plus";\n` +
|
|
166
|
+
`import c7t from "@fierst/c7t/vite";\n` +
|
|
167
|
+
`import { cloudflarePreset } from "@fierst/c7t/cloudflare";\n\n` +
|
|
168
|
+
`export default defineConfig({\n` +
|
|
169
|
+
` plugins: [c7t({ adapter: cloudflarePreset() })],\n` +
|
|
170
|
+
` lint: {\n` +
|
|
171
|
+
` ignorePatterns: ["node_modules/**", "dist/**", ".wrangler/**"],\n` +
|
|
172
|
+
` rules: {\n` +
|
|
173
|
+
` "require-yield": "off",\n` +
|
|
174
|
+
` },\n` +
|
|
175
|
+
` options: {\n` +
|
|
176
|
+
` typeAware: true,\n` +
|
|
177
|
+
` typeCheck: true,\n` +
|
|
178
|
+
` },\n` +
|
|
179
|
+
` },\n` +
|
|
180
|
+
`});\n`,
|
|
181
|
+
);
|
|
182
|
+
writeFileSync(
|
|
183
|
+
join(absTarget, "wrangler.jsonc"),
|
|
184
|
+
JSON.stringify(
|
|
185
|
+
{
|
|
186
|
+
name: pkgName,
|
|
187
|
+
main: "dist/worker.mjs",
|
|
188
|
+
compatibility_date: "2026-01-01",
|
|
189
|
+
compatibility_flags: ["nodejs_als"],
|
|
190
|
+
assets: {
|
|
191
|
+
directory: "dist/client",
|
|
192
|
+
binding: "ASSETS",
|
|
193
|
+
},
|
|
194
|
+
d1_databases: [
|
|
195
|
+
{
|
|
196
|
+
binding: "DB",
|
|
197
|
+
database_name: `${pkgName}-db`,
|
|
198
|
+
database_id: "00000000-0000-0000-0000-000000000000",
|
|
199
|
+
},
|
|
200
|
+
],
|
|
201
|
+
},
|
|
202
|
+
null,
|
|
203
|
+
2,
|
|
204
|
+
) + "\n",
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Upgrade `src/routes/index.tsx` to use Drizzle + `InsertNoteSchema` (Standard Schema v1) + `ValidationError`
|
|
209
|
+
writeFileSync(
|
|
210
|
+
join(absTarget, "src", "routes", "index.tsx"),
|
|
211
|
+
`import { desc } from "drizzle-orm";\n` +
|
|
212
|
+
`import { head, server, ValidationError } from "@fierst/c7t";\n` +
|
|
213
|
+
`import { db, InsertNoteSchema, notes } from "../db";\n\n` +
|
|
214
|
+
`export const getNotes = server(async () => {\n` +
|
|
215
|
+
` return db.select().from(notes).orderBy(desc(notes.id));\n` +
|
|
216
|
+
`});\n\n` +
|
|
217
|
+
`export const addNote = server(InsertNoteSchema, async (input) => {\n` +
|
|
218
|
+
` const [created] = await db.insert(notes).values({ text: input.text }).returning();\n` +
|
|
219
|
+
` return created;\n` +
|
|
220
|
+
`});\n\n` +
|
|
221
|
+
`export default function* HomePage() {\n` +
|
|
222
|
+
` let items = yield* getNotes();\n` +
|
|
223
|
+
` let draft = "";\n` +
|
|
224
|
+
` let error = "";\n\n` +
|
|
225
|
+
` head({ title: "Construct + Drizzle" });\n\n` +
|
|
226
|
+
` return () => (\n` +
|
|
227
|
+
` <main>\n` +
|
|
228
|
+
` <h1>Construct (c7t) + Drizzle</h1>\n` +
|
|
229
|
+
` <form\n` +
|
|
230
|
+
` class="note-form"\n` +
|
|
231
|
+
` onSubmit={async (e) => {\n` +
|
|
232
|
+
` e.preventDefault();\n` +
|
|
233
|
+
` error = "";\n` +
|
|
234
|
+
` try {\n` +
|
|
235
|
+
` const created = await addNote({ text: draft });\n` +
|
|
236
|
+
` items = [created, ...items];\n` +
|
|
237
|
+
` draft = "";\n` +
|
|
238
|
+
` } catch (err) {\n` +
|
|
239
|
+
` if (err instanceof ValidationError) {\n` +
|
|
240
|
+
` error = err.fields.text ?? err.message;\n` +
|
|
241
|
+
` return;\n` +
|
|
242
|
+
` }\n` +
|
|
243
|
+
` throw err;\n` +
|
|
244
|
+
` }\n` +
|
|
245
|
+
` }}\n` +
|
|
246
|
+
` >\n` +
|
|
247
|
+
` <input bind:value={draft} placeholder="Write a note..." />\n` +
|
|
248
|
+
` <button type="submit">Save</button>\n` +
|
|
249
|
+
` </form>\n` +
|
|
250
|
+
` {error && <p role="alert">{error}</p>}\n` +
|
|
251
|
+
` <ul>\n` +
|
|
252
|
+
` {items.map((item) => (\n` +
|
|
253
|
+
` <li key={item.id}>{item.text}</li>\n` +
|
|
254
|
+
` ))}\n` +
|
|
255
|
+
` </ul>\n` +
|
|
256
|
+
` </main>\n` +
|
|
257
|
+
` );\n` +
|
|
258
|
+
`}\n`,
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export function scaffoldProject(targetDir, options = {}) {
|
|
263
|
+
if (options.db !== undefined && !VALID_DB_PRESETS.has(options.db)) {
|
|
264
|
+
throw new Error(
|
|
265
|
+
`Unsupported --db preset "${options.db}". Expected one of: sqlite, postgres, d1.`,
|
|
266
|
+
);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
const absTarget = resolve(process.cwd(), targetDir);
|
|
270
|
+
if (existsSync(absTarget) && readdirSync(absTarget).length > 0 && !options.force) {
|
|
271
|
+
throw new Error(`Target directory "${targetDir}" already exists and is not empty.`);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
mkdirSync(absTarget, { recursive: true });
|
|
275
|
+
const templateDir = join(pkgRoot, "template");
|
|
276
|
+
cpSync(templateDir, absTarget, { recursive: true });
|
|
277
|
+
|
|
278
|
+
// Rename `gitignore` -> `.gitignore`
|
|
279
|
+
const rawGitignore = join(absTarget, "gitignore");
|
|
280
|
+
if (existsSync(rawGitignore)) {
|
|
281
|
+
writeFileSync(join(absTarget, ".gitignore"), readFileSync(rawGitignore, "utf-8"));
|
|
282
|
+
rmSync(rawGitignore, { force: true });
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// Copy `llms.txt` so AI coding tools know idiomatic c7t + Blokd + Drizzle immediately
|
|
286
|
+
const llmsSrc = join(pkgRoot, "llms.txt");
|
|
287
|
+
if (existsSync(llmsSrc)) {
|
|
288
|
+
cpSync(llmsSrc, join(absTarget, "llms.txt"));
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// Stamp project name & optional `--db` Drizzle setup in `package.json`
|
|
292
|
+
const pkgJsonPath = join(absTarget, "package.json");
|
|
293
|
+
if (existsSync(pkgJsonPath)) {
|
|
294
|
+
const rawName =
|
|
295
|
+
(options.name ?? basename(absTarget))
|
|
296
|
+
.toLowerCase()
|
|
297
|
+
.replace(/[^a-z0-9-_]/g, "-")
|
|
298
|
+
.replace(/^-+|-+$/g, "") || "c7t-app";
|
|
299
|
+
const pkg = JSON.parse(readFileSync(pkgJsonPath, "utf-8"));
|
|
300
|
+
pkg.name = rawName;
|
|
301
|
+
if (pkg.dependencies?.["@fierst/c7t"]) {
|
|
302
|
+
pkg.dependencies["@fierst/c7t"] = `^${selfPkg.version}`;
|
|
303
|
+
}
|
|
304
|
+
if (pkg.dependencies?.["@fierst/blokd"] && selfPkg.dependencies?.["@fierst/blokd"]) {
|
|
305
|
+
pkg.dependencies["@fierst/blokd"] = selfPkg.dependencies["@fierst/blokd"];
|
|
306
|
+
}
|
|
307
|
+
if (options.db) {
|
|
308
|
+
writeDbFiles(absTarget, rawName, options.db, pkg);
|
|
309
|
+
}
|
|
310
|
+
writeFileSync(pkgJsonPath, JSON.stringify(pkg, null, 2) + "\n");
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
return absTarget;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const isDirectCli =
|
|
317
|
+
process.argv[1] &&
|
|
318
|
+
resolve(process.argv[1]).replace(/\\/g, "/") ===
|
|
319
|
+
fileURLToPath(import.meta.url).replace(/\\/g, "/");
|
|
320
|
+
|
|
321
|
+
if (isDirectCli) {
|
|
322
|
+
const rawArgs = process.argv.slice(2);
|
|
323
|
+
const dbFlag = parseFlag(rawArgs, "--db");
|
|
324
|
+
const force = rawArgs.includes("--force") || rawArgs.includes("-f");
|
|
325
|
+
const positional = [];
|
|
326
|
+
for (let i = 0; i < rawArgs.length; i++) {
|
|
327
|
+
const a = rawArgs[i];
|
|
328
|
+
if (a === "--db" && rawArgs[i + 1]) {
|
|
329
|
+
i++;
|
|
330
|
+
continue;
|
|
331
|
+
}
|
|
332
|
+
if (!a.startsWith("-")) positional.push(a);
|
|
333
|
+
}
|
|
334
|
+
const dir = positional[0] ?? "my-c7t-app";
|
|
335
|
+
try {
|
|
336
|
+
scaffoldProject(dir, { force, db: dbFlag });
|
|
337
|
+
console.log(`\nConstructed c7t project in ./${dir}${dbFlag ? ` (Drizzle ${dbFlag})` : ""}`);
|
|
338
|
+
const dbStep = dbFlag === "sqlite" || dbFlag === "postgres" ? "\n npm run db:push" : "";
|
|
339
|
+
console.log(`\nNext steps:\n cd ${dir}\n npm install${dbStep}\n npm run dev\n`);
|
|
340
|
+
} catch (err) {
|
|
341
|
+
console.error(`[c7t] ${err instanceof Error ? err.message : String(err)}`);
|
|
342
|
+
process.exit(1);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export interface BunAdapterOptions {
|
|
2
|
+
/** Port to listen on (default: `Number(process.env.PORT) || 3000`) */
|
|
3
|
+
port?: number;
|
|
4
|
+
/** Hostname to bind (default: `'0.0.0.0'`) */
|
|
5
|
+
hostname?: string;
|
|
6
|
+
/** Directory containing built static client assets & prerendered SSG files (default: `'dist/client'`) */
|
|
7
|
+
clientDir?: string;
|
|
8
|
+
/** Callback fired once `Bun.serve()` starts listening */
|
|
9
|
+
onListen?: (info: {
|
|
10
|
+
port: number;
|
|
11
|
+
hostname: string;
|
|
12
|
+
}) => void;
|
|
13
|
+
}
|
|
14
|
+
export interface BunServerInstance {
|
|
15
|
+
readonly port: number;
|
|
16
|
+
readonly hostname: string;
|
|
17
|
+
stop(closeActiveConnections?: boolean): void;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Declarative adapter preset for `c7t({ adapter: bunAdapter() })` in `vite.config.ts`.
|
|
21
|
+
*/
|
|
22
|
+
export declare function bunAdapter(options?: BunAdapterOptions): {
|
|
23
|
+
name: "bun";
|
|
24
|
+
options: BunAdapterOptions;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Create a Web-Standard `fetch` handler for `Bun.serve()` that serves static `dist/client` assets
|
|
28
|
+
* and prerendered SSG pages via `Bun.file()` (falling back to standard `fs.readFile` in non-Bun tests)
|
|
29
|
+
* before delegating dynamic SSR & NDJSON streaming RPCs to `app.fetch(request)`.
|
|
30
|
+
*/
|
|
31
|
+
export declare function createBunFetchHandler(app: {
|
|
32
|
+
fetch(req: Request): Response | Promise<Response>;
|
|
33
|
+
}, options?: Pick<BunAdapterOptions, "clientDir">): (req: Request) => Promise<Response>;
|
|
34
|
+
/**
|
|
35
|
+
* Start a native `Bun.serve()` HTTP server for a `c7t` Hono application.
|
|
36
|
+
*/
|
|
37
|
+
export declare function serveBun(app: {
|
|
38
|
+
fetch(req: Request): Response | Promise<Response>;
|
|
39
|
+
}, options?: BunAdapterOptions): BunServerInstance;
|
|
40
|
+
export { serveBun as default };
|