@thexjs/core 0.1.0 → 0.1.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.
Files changed (3) hide show
  1. package/README.md +192 -0
  2. package/dist/index.js +13 -4
  3. package/package.json +1 -1
package/README.md ADDED
@@ -0,0 +1,192 @@
1
+ # @thexjs/core
2
+
3
+ The rendering/routing engine behind **x** — a full-stack React framework built on [Bun](https://bun.sh). This package provides file-based routing, SSR/SSG rendering, islands, server functions, a content layer, and a lightweight data layer (SQLite/Postgres).
4
+
5
+ You typically don't install this directly — [`@thexjs/cli`](https://www.npmjs.com/package/@thexjs/cli) depends on it and drives `x dev` / `x build` / `x start` for you. Install it explicitly only if you're calling the APIs below directly (e.g. a custom server entry).
6
+
7
+ ```sh
8
+ bun add @thexjs/core
9
+ ```
10
+
11
+ > Requires the Bun runtime — this package uses `Bun.serve`, `Bun.file`, `bun:sqlite`, and `Bun.sql` internally.
12
+
13
+ ## Quick start
14
+
15
+ ```ts
16
+ // x.config.ts
17
+ import { defineConfig } from "@thexjs/core";
18
+
19
+ export default defineConfig({
20
+ pagesDir: "./src/pages",
21
+ contentDir: "./src/content",
22
+ port: 3000,
23
+ });
24
+ ```
25
+
26
+ ```ts
27
+ // src/pages/index.tsx
28
+ import type { RouteProps } from "@thexjs/core";
29
+
30
+ export const mode = "static"; // prerender at build time (default is "server")
31
+
32
+ export default function HomePage({}: RouteProps) {
33
+ return <h1>Hello from x</h1>;
34
+ }
35
+ ```
36
+
37
+ Run it via the CLI: `x dev` (or `bun run dev` if that's wired up in your `package.json`).
38
+
39
+ ## File-based routing
40
+
41
+ Given a `pagesDir`, `scanPages` walks the directory and maps files to routes:
42
+
43
+ | File | Route |
44
+ |---|---|
45
+ | `src/pages/index.tsx` | `/` |
46
+ | `src/pages/about.tsx` | `/about` |
47
+ | `src/pages/blog/[slug].tsx` | `/blog/:slug` |
48
+ | `src/pages/api/users.ts` | API route at `/api/users` |
49
+ | `src/pages/_layout.tsx` | Wraps every route in the same directory (and below) |
50
+ | `src/pages/_middleware.ts` | Runs before matching routes in the same directory (and below) |
51
+ | `src/pages/_404.tsx` | Custom not-found page |
52
+
53
+ Files and directories prefixed with `_` or `.` are never treated as routes.
54
+
55
+ Underlying scanners (`scanRoutes`, `scanPages`, `scanApiDir`, `scanLayouts`, `scanLayoutsDir`, `scanMiddleware`, `scanNotFound`) and chain resolvers (`findLayoutChain`, `findMiddlewareChain`) are exported if you need to build custom tooling on top of the same conventions.
56
+
57
+ ## Route modes: static vs. server
58
+
59
+ Every page defaults to **server-rendered (SSR)**. Opt into build-time prerendering per page:
60
+
61
+ ```ts
62
+ export const mode: "static" | "server" = "static";
63
+ ```
64
+
65
+ - **`static`** — rendered once at `x build` time to a `.html` file. Best for marketing pages, docs, blog posts — anything that doesn't need per-request data. No page in your app defaults to this; you must set it explicitly, or the build step will silently ship an empty/server-only route with no prerendered HTML.
66
+ - **`server`** (default) — rendered per-request via `renderPage` / `renderStreamingPage` when running under `x start` (or `x dev`). Requires a live Bun server; **not deployable to static hosts** (see Deployment below).
67
+
68
+ ## Loaders
69
+
70
+ Export a `loader` alongside your page to fetch data before render:
71
+
72
+ ```ts
73
+ import type { RouteProps } from "@thexjs/core";
74
+
75
+ export async function loader({ params }: { params: Record<string, string> }) {
76
+ return { user: await getUser(params.id) };
77
+ }
78
+
79
+ export default function UserPage({ loaderData }: RouteProps<typeof loader>) {
80
+ return <p>{loaderData.user.name}</p>;
81
+ }
82
+ ```
83
+
84
+ `LoaderArgs` / `LoaderReturn` types are exported for typing loaders manually if needed.
85
+
86
+ ## Server functions / actions
87
+
88
+ Files under an `actionsDir` (or a page's colocated `actions` export) register callable server functions:
89
+
90
+ ```ts
91
+ // src/pages/contact/_actions.ts
92
+ export async function submitContact(data: { email: string; message: string }) {
93
+ // runs on the server, callable from a client island
94
+ }
95
+ ```
96
+
97
+ `registerServerFunctions`, `generateServerFunctionClient`, and `getServerFunctionHandler` are the lower-level primitives the router wires up automatically — most apps won't call these directly.
98
+
99
+ ## Islands (selective hydration)
100
+
101
+ Wrap any interactive piece of a static/server-rendered page in `<Island>` to ship it as a separately-hydrated client bundle:
102
+
103
+ ```tsx
104
+ import { Island } from "@thexjs/core";
105
+
106
+ <Island name="like-button" client="visible">
107
+ <LikeButton />
108
+ </Island>
109
+ ```
110
+
111
+ `client` accepts `"idle" | "visible" | "load"`, controlling when the island hydrates on the client. Everything outside an `<Island>` stays static/server-rendered HTML with no client JS shipped.
112
+
113
+ ## Content collections (Markdown)
114
+
115
+ Point `contentDir` at a folder of Markdown files with frontmatter; `scanContent` + `renderMarkdown` turn them into routable entries (e.g. for a blog):
116
+
117
+ ```ts
118
+ import { scanContent, renderMarkdown } from "@thexjs/core";
119
+
120
+ const posts = scanContent("./src/content/blog");
121
+ const html = renderMarkdown(posts[0].body);
122
+ ```
123
+
124
+ ## Data layer
125
+
126
+ Thin, typed wrappers over Bun's built-in SQLite and Postgres clients, plus a minimal migration runner:
127
+
128
+ ```ts
129
+ import { connectSQLite, runSQLiteMigrations } from "@thexjs/core";
130
+
131
+ const db = connectSQLite({ filename: "./data/dev.db" });
132
+ await runSQLiteMigrations(db, "./data/migrations");
133
+ ```
134
+
135
+ ```ts
136
+ import { connectPostgres, runPostgresMigrations } from "@thexjs/core";
137
+
138
+ const sql = connectPostgres({ url: process.env.DATABASE_URL! });
139
+ await runPostgresMigrations(sql, "./data/migrations");
140
+ ```
141
+
142
+ ## Middleware
143
+
144
+ ```ts
145
+ // src/pages/dashboard/_middleware.ts
146
+ import type { MiddlewareFn } from "@thexjs/core";
147
+
148
+ export const middleware: MiddlewareFn = async (ctx, next) => {
149
+ if (!ctx.session) return new Response("Unauthorized", { status: 401 });
150
+ return next();
151
+ };
152
+ ```
153
+
154
+ `composeMiddleware` chains multiple middleware functions together; `findMiddlewareChain` resolves which ones apply to a given route based on directory nesting.
155
+
156
+ ## Building an app server yourself
157
+
158
+ Most apps just use `x dev` / `x build` / `x start` from `@thexjs/cli`. If you're embedding `x` in a custom entry point:
159
+
160
+ ```ts
161
+ import { createApp, build } from "@thexjs/core";
162
+
163
+ // Dev / runtime server
164
+ const app = createApp({ pagesDir: "./src/pages", development: true });
165
+ Bun.serve(app);
166
+
167
+ // Static + server build
168
+ await build({ pagesDir: "./src/pages", outDir: "./.x" });
169
+ ```
170
+
171
+ ## Deployment note
172
+
173
+ `build()` writes prerendered `static` pages (and copies `public/`) to `<outDir>/client` — that output is a plain static site, deployable anywhere (Vercel, Netlify, any CDN). Any page left in the default `server` mode requires a running Bun process (`x start`) and **is not included in the static output** — it needs a Bun-capable host (Fly.io, a VPS, Docker, etc.), not a static host or a Node-only serverless platform.
174
+
175
+ ## Exports reference
176
+
177
+ | Export | Purpose |
178
+ |---|---|
179
+ | `defineConfig`, `createApp`, `CreateAppOptions`, `RouteProps`, `RevalidateOptions` | App setup / dev & runtime server |
180
+ | `build`, `BuildOptions`, `RouteMode` | Static/server build step |
181
+ | `renderPage`, `renderStaticPage`, `renderStreamingPage`, `LoaderArgs`, `LoaderReturn` | Lower-level render functions |
182
+ | `scanRoutes`, `scanPages`, `scanApiDir`, `scanLayouts`, `scanLayoutsDir`, `scanMiddleware`, `scanNotFound`, `findLayoutChain`, `findMiddlewareChain`, `generateManifestSource`, `writeManifest` | Routing internals |
183
+ | `Island`, `IslandProvider`, `IslandMode`, `IslandEntry` | Selective hydration |
184
+ | `scanContent`, `renderMarkdown`, `escapeHtml`, `ContentEntry`, `Frontmatter` | Markdown content collections |
185
+ | `composeMiddleware`, `MiddlewareContext`, `MiddlewareFn`, `MiddlewareNext` | Middleware |
186
+ | `registerServerFunctions`, `generateServerFunctionClient`, `getServerFunctionHandler`, `resetServerFunctions` | Server functions/actions internals |
187
+ | `connectSQLite`, `connectPostgres`, `runSQLiteMigrations`, `runPostgresMigrations` | Data layer |
188
+ | `DefaultNotFound`, `renderErrorOverlay`, `CLIENT_NAV_SCRIPT` | Defaults / dev tooling |
189
+
190
+ ## License
191
+
192
+ MIT
package/dist/index.js CHANGED
@@ -1307,7 +1307,7 @@ data: ${data}
1307
1307
  }
1308
1308
 
1309
1309
  // src/build.ts
1310
- import { existsSync as existsSync2, mkdirSync, writeFileSync as writeFileSync3 } from "fs";
1310
+ import { cpSync, existsSync as existsSync2, mkdirSync, writeFileSync as writeFileSync3 } from "fs";
1311
1311
  import { basename, join as join5, relative as relative3 } from "path";
1312
1312
  import { createElement as createElement2 } from "react";
1313
1313
 
@@ -1351,6 +1351,14 @@ async function build(options) {
1351
1351
  const apiDir = options.apiDir;
1352
1352
  const actionsDir = options.actionsDir;
1353
1353
  const layoutsDir = options.layoutsDir ?? pagesDir;
1354
+ const projectRoot = pagesDir ? join5(pagesDir, "..", "..") : process.cwd();
1355
+ const publicDir = join5(projectRoot, "public");
1356
+ const hasPublicDir = existsSync2(publicDir);
1357
+ const stylesheetHref = hasPublicDir && existsSync2(join5(publicDir, "styles.css")) ? "/styles.css" : void 0;
1358
+ if (hasPublicDir) {
1359
+ cpSync(publicDir, clientDir, { recursive: true });
1360
+ console.log(`[x] build: copied public/ -> ${relative3(process.cwd(), clientDir)}`);
1361
+ }
1354
1362
  let routeEntries = [];
1355
1363
  if (pagesDir && existsSync2(pagesDir)) {
1356
1364
  routeEntries = scanPages(pagesDir);
@@ -1426,7 +1434,7 @@ async function build(options) {
1426
1434
  const registry = createIslandRegistry();
1427
1435
  const pageContent = renderPageWithLayout(page.Component, params, page.layoutModules);
1428
1436
  const content = createElement2(IslandProvider, { registry }, pageContent);
1429
- const html = renderStaticPage(content);
1437
+ const html = renderStaticPage(content, { stylesheet: stylesheetHref });
1430
1438
  const outPath = page.entry.routePath === "/" ? "/index.html" : `${page.entry.routePath}/index.html`;
1431
1439
  const fullPath = join5(clientDir, outPath);
1432
1440
  mkdirSync(join5(fullPath, ".."), { recursive: true });
@@ -1442,7 +1450,7 @@ async function build(options) {
1442
1450
  ` [islands] ${uniqueNames.length} island(s) on ${page.entry.routePath} -> ${islandScripts.join(", ")}`
1443
1451
  );
1444
1452
  }
1445
- const finalHtml = renderStaticPage(content, { islandScripts });
1453
+ const finalHtml = renderStaticPage(content, { islandScripts, stylesheet: stylesheetHref });
1446
1454
  writeFileSync3(fullPath, finalHtml, "utf-8");
1447
1455
  console.log(` [static] ${page.entry.routePath} -> ${outPath}`);
1448
1456
  }
@@ -1455,7 +1463,8 @@ async function build(options) {
1455
1463
  });
1456
1464
  const rendered = createElement2(IslandProvider, { registry }, pageContent);
1457
1465
  const html = renderStaticPage(rendered, {
1458
- title: content.frontmatter.title ?? content.slug
1466
+ title: content.frontmatter.title ?? content.slug,
1467
+ stylesheet: stylesheetHref
1459
1468
  });
1460
1469
  const outPath = content.routePath === "/" ? "/index.html" : `${content.routePath}/index.html`;
1461
1470
  const fullPath = join5(clientDir, outPath);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thexjs/core",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Full-stack React framework core (router, SSR/SSG renderer, islands, server functions) for the x framework, built on Bun.",
5
5
  "license": "MIT",
6
6
  "type": "module",