sordo 0.4.0 → 0.5.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 CHANGED
@@ -1,5 +1,15 @@
1
1
  # sordo
2
2
 
3
+ ## 0.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 9d53d86: Routing: handler files with a content extension (`sitemap.xml.ts`, `robots.txt.ts`, `llms.txt.ts`) now work anywhere under `app/routes/`, and `app/routes/_404.tsx` renders a custom 404 page (status 404) for unknown paths. Handlers can call `ctx.notFound()` to respond with it.
8
+
9
+ ### Patch Changes
10
+
11
+ - 5a49288: Fix the gaps found verifying the Cloudflare recipe. The UI starter now installs `tailwindcss`, and `--deploy cloudflare` on edge adds `@sordo/deploy-cloudflare` plus a `plugins` entry to `sordo.config.ts`. Edge builds in the default inline mode now serve `public/` files at `/_sordo/assets/<name>`. Build failures report the bundler's logs instead of a bare "Bundle failed", and a css build that cannot resolve a package names it. The generated edge `fetch` is typed so it passes a strict tsconfig. The README augments `SordoBindings` through `sordo/middleware` and no longer claims the scaffold's `build` script generates CSS.
12
+
3
13
  ## 0.4.0
4
14
 
5
15
  ### Minor Changes
package/README.md CHANGED
@@ -100,7 +100,7 @@ export default defineConfig({
100
100
 
101
101
  ```sh
102
102
  bunx wrangler login
103
- bun run build # scaffolded apps generate CSS first, then build
103
+ bun run build # runs `sordo build`
104
104
  sordo deploy --target edge
105
105
  ```
106
106
 
@@ -112,8 +112,8 @@ vars. See the plugin README for options (`wranglerEnv`, `dryRun`, `args`).
112
112
 
113
113
  Sordo emits no `wrangler.jsonc` — you own it. `sordo build --target edge` writes
114
114
  `.sordo/worker.js` (default `outDir` is `./.sordo`, not `dist/`). Scaffolded
115
- apps generate Tailwind CSS in their `build` script, so use `bun run build`
116
- rather than calling `sordo build` directly.
115
+ apps compile Tailwind CSS through the `css` entry in `sordo.config.ts`, so
116
+ `bun run build` and `sordo build` are equivalent.
117
117
 
118
118
  ```sh
119
119
  bun run build
@@ -137,7 +137,7 @@ and read bindings (service, KV, R2, D1) from `ctx.bindings`; `ctx.waitUntil(p)`
137
137
  extends the request. Type bindings by augmenting the interface:
138
138
 
139
139
  ```ts
140
- declare module "sordo" {
140
+ declare module "sordo/middleware" {
141
141
  interface SordoBindings {
142
142
  CMS: { fetch: typeof fetch };
143
143
  }
@@ -145,9 +145,12 @@ declare module "sordo" {
145
145
  ```
146
146
 
147
147
  By default `worker.js` is self-contained (client chunks and CSS are inlined), so
148
- `main` is the only file Wrangler needs. With `adapter.edge.assets: "external"`
149
- also set `assets.directory`; files from `app/public/` are then served at
150
- `/_sordo/assets/<name>` (not at `/<name>`). Only `config.env.public` values are
148
+ `main` is the only file Wrangler needs. Files from `app/public/` are inlined
149
+ too and served at `/_sordo/assets/<name>` (not at `/<name>`), with
150
+ `must-revalidate` caching since their names are not content-hashed; they count
151
+ toward the worker's size, so keep large files out of `public/`. With
152
+ `adapter.edge.assets: "external"` also set `assets.directory`, and the same
153
+ files are served from there instead. Only `config.env.public` values are
151
154
  inlined at build; secrets never are.
152
155
 
153
156
  UI components (upstream shadcn/ui, local paths, or registries):
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sordo",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Bun-native full-stack meta-framework with React rendering",
5
5
  "repository": {
6
6
  "type": "git",
@@ -16,6 +16,7 @@ export function render(data: CollectedData): string {
16
16
  } else {
17
17
  out.push("| File | URL | Methods |", "|---|---|---|");
18
18
  const rows = data.routes
19
+ .filter((r) => r.kind !== "notFound")
19
20
  .map((r) => ({
20
21
  file: relPath(r.filePath),
21
22
  pattern: r.bunPattern,
package/src/build/css.ts CHANGED
@@ -22,6 +22,28 @@ export interface CssBuildInput {
22
22
 
23
23
  const TAILWIND_RE = /@import\s+(?:url\(\s*)?["']tailwindcss["']|@tailwind\s/;
24
24
 
25
+ // Bun logs an unresolvable import as `Could not resolve: "pkg"`, and
26
+ // bun-plugin-tailwind as `Can't resolve 'pkg' in '<dir>'`.
27
+ export function missingPackageHint(msgs: string): string {
28
+ const pkgs = new Set<string>();
29
+ for (const m of msgs.matchAll(
30
+ /(?:resolve|find)[^"'`\n]*["'`]([^"'`]+)["'`]/gi,
31
+ )) {
32
+ const spec = m[1] as string;
33
+ if (spec.startsWith(".") || spec.startsWith("/")) continue;
34
+ // Aliases, builtins and file-like specifiers (a missing url() asset)
35
+ // are not installable packages.
36
+ if (/^(@\/|~|node:|bun:)/.test(spec)) continue;
37
+ if (/\.(?:[a-z0-9]{1,5})$/i.test(spec) && spec.includes("/")) continue;
38
+ const parts = spec.split("/");
39
+ pkgs.add(
40
+ spec.startsWith("@") ? parts.slice(0, 2).join("/") : (parts[0] as string),
41
+ );
42
+ }
43
+ if (pkgs.size === 0) return "";
44
+ return `\nMissing package${pkgs.size > 1 ? "s" : ""}: ${[...pkgs].join(", ")}. Run \`bun add -d ${[...pkgs].join(" ")}\`.`;
45
+ }
46
+
25
47
  const TAILWIND_MISSING =
26
48
  'sordo build: the css entry imports Tailwind but "bun-plugin-tailwind" is not installed. Run `bun add -D bun-plugin-tailwind`, or set `css: { entry, tailwind: false }` to build it as plain CSS.';
27
49
 
@@ -75,10 +97,14 @@ export async function buildCss(input: CssBuildInput): Promise<CssBuildOutput> {
75
97
  naming: "[name]-[hash].[ext]",
76
98
  minify: input.mode === "production",
77
99
  plugins,
100
+ // Default is to reject with a bare "Bundle failed"; we want the logs.
101
+ throw: false,
78
102
  });
79
103
  if (!result.success) {
80
104
  const msgs = result.logs.map((l) => l.message ?? String(l)).join("\n");
81
- throw new Error(`sordo build: css build failed\n${msgs}`);
105
+ throw new Error(
106
+ `sordo build: css build failed\n${msgs}${missingPackageHint(msgs)}`,
107
+ );
82
108
  }
83
109
 
84
110
  const files = result.outputs.map((o) => ({
@@ -181,6 +181,7 @@ export async function build(options: BuildOptions): Promise<BuildResult> {
181
181
  // React picks its dev or prod build from NODE_ENV; without this the
182
182
  // browser bundle ships React's development build in production.
183
183
  define: { "process.env.NODE_ENV": JSON.stringify(mode) },
184
+ throw: false,
184
185
  plugins: [
185
186
  stripServerExportsPlugin(hydratedPages.map((p) => p.entry.filePath)),
186
187
  ],
@@ -218,16 +219,41 @@ export async function build(options: BuildOptions): Promise<BuildResult> {
218
219
  manifest.css = cssOut.href;
219
220
  }
220
221
 
222
+ // Listed once here: the inline list below and adapter.emit both read it.
223
+ const assets = await copyAssets(appDir, outDir, { write: !compile });
224
+
221
225
  // Non-compiled servers (bun + edge) serve every client output (island and
222
226
  // page chunks, the CSS sheet and its assets) from bytes inlined at build
223
227
  // time; compile mode embeds client/ into the binary instead.
224
228
  let inlineAssetsPath: string | undefined;
225
229
  const externalAssets = target === "edge" && options.edgeAssets === "external";
226
230
  if (!compile && !externalAssets) {
227
- const clientFiles = (await collectClientChunks(clientOutDir)).map((c) => ({
231
+ const clientFiles: Array<{
232
+ url: string;
233
+ path: string;
234
+ mutable?: boolean;
235
+ etag?: string;
236
+ }> = (await collectClientChunks(clientOutDir)).map((c) => ({
228
237
  url: c.url,
229
238
  path: c.src,
230
239
  }));
240
+ // Edge has no filesystem at runtime, so public/ is inlined too, served
241
+ // at /_sordo/assets/<name> like the external layout. Requests arrive
242
+ // percent-encoded, so the key must be too.
243
+ if (target === "edge") {
244
+ for (const a of assets) {
245
+ clientFiles.push({
246
+ // Round-trip through URL so the key matches `new URL(req.url).pathname`.
247
+ url: new URL(
248
+ a.publicPath.split("/").map(encodeURIComponent).join("/"),
249
+ "http://x",
250
+ ).pathname,
251
+ path: a.src,
252
+ mutable: true,
253
+ etag: a.hash,
254
+ });
255
+ }
256
+ }
231
257
  if (clientFiles.length > 0) {
232
258
  inlineAssetsPath = `${outDir}/inline-assets.json`;
233
259
  await Bun.write(inlineAssetsPath, JSON.stringify(clientFiles, null, 2));
@@ -303,6 +329,7 @@ export async function build(options: BuildOptions): Promise<BuildResult> {
303
329
  target: adapter.buildTarget,
304
330
  outdir: serverOutDir,
305
331
  minify: false,
332
+ throw: false,
306
333
  });
307
334
 
308
335
  if (!serverResult.success) {
@@ -320,8 +347,6 @@ export async function build(options: BuildOptions): Promise<BuildResult> {
320
347
  : `${serverOutDir}/server-entry.js`;
321
348
  }
322
349
 
323
- const assets = await copyAssets(appDir, outDir, { write: !compile });
324
-
325
350
  const emitted = await adapter.emit(
326
351
  { serverEntryOut, serverEntrySrc: serverEntryPath, assets, clientOutDir },
327
352
  { appDir, outDir, mode, compile, edgeAssets: options.edgeAssets },
@@ -11,18 +11,24 @@ export async function INLINE_ASSETS(
11
11
  const list = (await Bun.file(listPath).json()) as Array<{
12
12
  url: string;
13
13
  path: string;
14
+ mutable?: boolean;
15
+ etag?: string;
14
16
  }>;
15
17
  const out: Record<string, InlineAsset> = {};
16
- for (const { url, path } of list) {
18
+ for (const { url, path, mutable, etag } of list) {
17
19
  const file = Bun.file(path);
18
20
  const type = file.type || "application/octet-stream";
19
- out[url] = type.startsWith("text/")
20
- ? { type, body: await file.text(), base64: false }
21
- : {
22
- type,
23
- body: Buffer.from(await file.arrayBuffer()).toString("base64"),
24
- base64: true,
25
- };
21
+ out[url] = {
22
+ ...(type.startsWith("text/")
23
+ ? { type, body: await file.text(), base64: false }
24
+ : {
25
+ type,
26
+ body: Buffer.from(await file.arrayBuffer()).toString("base64"),
27
+ base64: true,
28
+ }),
29
+ ...(mutable ? { mutable } : {}),
30
+ ...(etag ? { etag } : {}),
31
+ };
26
32
  }
27
33
  return out;
28
34
  }
@@ -203,7 +203,7 @@ export { server }
203
203
  ${triggerWire}
204
204
  const __compiled = compilePatterns(router.routes)
205
205
  export default {
206
- async fetch(req, env, execCtx) {${inline ? "\n const asset = matchInlineAsset(INLINE_ASSET_DATA, req)\n if (asset) return asset" : ""}
206
+ async fetch(req: Request, env: Record<string, unknown>, execCtx: { waitUntil(p: Promise<unknown>): void }) {${inline ? "\n const asset = matchInlineAsset(INLINE_ASSET_DATA, req)\n if (asset) return asset" : ""}
207
207
  const hit = await dispatch(router.routes, req, { env, execCtx }, __compiled)
208
208
  if (hit) return hit
209
209
  return router.fallback(Object.assign(req, { env, execCtx }))
@@ -10,7 +10,7 @@ import {
10
10
  } from "./response-helpers.ts";
11
11
 
12
12
  // Apps augment this to type their Worker bindings on the edge target:
13
- // declare module "sordo" { interface SordoBindings { CMS: Fetcher } }
13
+ // declare module "sordo/middleware" { interface SordoBindings { CMS: Fetcher } }
14
14
  // biome-ignore lint/suspicious/noEmptyInterface: declaration-merging seam
15
15
  export interface SordoBindings {}
16
16
 
@@ -33,6 +33,8 @@ export interface SordoContext {
33
33
  json(body: unknown, init?: ResponseInit): Response;
34
34
  html(body: string | ReadableStream, init?: ResponseInit): Response;
35
35
  redirect(to: string, status?: 301 | 302 | 303 | 307 | 308): Response;
36
+ // Responds 404 with the app's `app/routes/_404.tsx` page, or plain text if none.
37
+ notFound(): Response | Promise<Response>;
36
38
  }
37
39
 
38
40
  export type Handler = (
@@ -69,6 +71,7 @@ export function compose(middlewares: Middleware[], handler: Handler): Handler {
69
71
  export function makeContext(
70
72
  req: Request,
71
73
  params: Record<string, string> = {},
74
+ renderNotFound?: (req: Request, ctx: SordoContext) => Promise<Response>,
72
75
  ): SordoContext {
73
76
  let urlCache: URL | null = null;
74
77
  let cookiesCache: unknown;
@@ -120,6 +123,11 @@ export function makeContext(
120
123
  json: jsonResponse,
121
124
  html: htmlResponse,
122
125
  redirect: redirectResponse,
126
+ notFound() {
127
+ return renderNotFound
128
+ ? renderNotFound(req, ctx)
129
+ : new Response("Not Found", { status: 404 });
130
+ },
123
131
  };
124
132
  return ctx;
125
133
  }
@@ -1,6 +1,6 @@
1
1
  import type { RouteEntry } from "../types.ts";
2
2
  import { assertNoConflicts } from "./conflict.ts";
3
- import { compareRoutes, parseRouteFile } from "./pattern.ts";
3
+ import { compareRoutes, NOT_FOUND_FILE, parseRouteFile } from "./pattern.ts";
4
4
 
5
5
  const TEST_FILE_RE = /\.test\.tsx?$/;
6
6
 
@@ -13,7 +13,7 @@ export async function scanRoutes(appDir: string): Promise<RouteEntry[]> {
13
13
  try {
14
14
  for await (const rel of glob.scan({ cwd: routesDir, onlyFiles: true })) {
15
15
  const base = rel.split("/").pop() ?? rel;
16
- if (base.startsWith("_")) continue;
16
+ if (base.startsWith("_") && rel !== NOT_FOUND_FILE) continue;
17
17
  if (TEST_FILE_RE.test(base)) continue;
18
18
 
19
19
  const parsed = parseRouteFile(rel);
@@ -8,7 +8,13 @@ import {
8
8
  type PluginServer,
9
9
  } from "../plugin/index.ts";
10
10
  import type { Renderer } from "../render/index.tsx";
11
- import type { BunRoutes, Handler, HTTPMethod, RouteEntry } from "../types.ts";
11
+ import type {
12
+ BunRoutes,
13
+ Handler,
14
+ HTTPMethod,
15
+ RouteEntry,
16
+ SordoContext,
17
+ } from "../types.ts";
12
18
  import { HTTP_METHODS } from "../types.ts";
13
19
 
14
20
  export interface RouterOptions {
@@ -120,11 +126,29 @@ export async function createCompiledRouter(
120
126
  const preloadedModules = options.modules;
121
127
  const routes: BunRoutes = {};
122
128
 
129
+ const notFoundEntry = entries.find((e) => e.kind === "notFound");
130
+ const renderNotFound = notFoundEntry
131
+ ? async (req: Request, ctx: SordoContext): Promise<Response> => {
132
+ const res = await renderer.renderPage(notFoundEntry, req, ctx);
133
+ return new Response(res.body, {
134
+ status: 404,
135
+ statusText: "Not Found",
136
+ headers: res.headers,
137
+ });
138
+ }
139
+ : undefined;
140
+
123
141
  for (const entry of entries) {
142
+ if (entry.kind === "notFound") continue;
124
143
  if (entry.kind === "page") {
125
144
  const handler: Handler = (req, ctx) =>
126
145
  renderer.renderPage(entry, req, ctx);
127
- attach(routes, entry.bunPattern, { GET: wrap(handler, middlewareChain) });
146
+ attach(
147
+ routes,
148
+ entry.bunPattern,
149
+ { GET: wrap(handler, middlewareChain) },
150
+ renderNotFound,
151
+ );
128
152
  } else {
129
153
  const mod = (preloadedModules?.[entry.filePath] ??
130
154
  (await import(entry.filePath))) as Record<string, unknown>;
@@ -149,7 +173,7 @@ export async function createCompiledRouter(
149
173
  `(GET/POST/PUT/DELETE/PATCH/OPTIONS/HEAD).`,
150
174
  );
151
175
  }
152
- attach(routes, entry.bunPattern, methodMap);
176
+ attach(routes, entry.bunPattern, methodMap, renderNotFound);
153
177
  }
154
178
  }
155
179
 
@@ -161,19 +185,16 @@ export async function createCompiledRouter(
161
185
  ][]) {
162
186
  wrapped[m] = wrap(h, middlewareChain);
163
187
  }
164
- attach(routes, pr.pattern, wrapped);
188
+ attach(routes, pr.pattern, wrapped, renderNotFound);
165
189
  }
166
190
 
167
- const fallback = wrap(
168
- () => new Response("Not Found", { status: 404 }),
169
- middlewareChain,
170
- );
191
+ const fallback = wrap((_req, ctx) => ctx.notFound(), middlewareChain);
171
192
 
172
193
  return {
173
194
  routes,
174
195
  fallback: async (req: Request) => {
175
196
  const startMs = now();
176
- const ctx = makeContext(req);
197
+ const ctx = makeContext(req, {}, renderNotFound);
177
198
  const res = await fallback(req, ctx);
178
199
  return finalizeResponse(res, ctx, { startMs });
179
200
  },
@@ -185,6 +206,7 @@ function attach(
185
206
  routes: BunRoutes,
186
207
  pattern: string,
187
208
  methodMap: Partial<Record<HTTPMethod, Handler>>,
209
+ renderNotFound?: (req: Request, ctx: SordoContext) => Promise<Response>,
188
210
  ): void {
189
211
  const existing = routes[pattern];
190
212
  const bunWrapped: Record<
@@ -196,7 +218,7 @@ function attach(
196
218
  bunWrapped[m] = (req) => {
197
219
  const startMs = now();
198
220
  const params = req.params ?? {};
199
- const ctx = makeContext(req, params);
221
+ const ctx = makeContext(req, params, renderNotFound);
200
222
  return Promise.resolve(h(req, ctx)).then((res) =>
201
223
  finalizeResponse(res, ctx, { startMs }),
202
224
  );
@@ -3,7 +3,7 @@ import type { Segment } from "../types.ts";
3
3
  export interface ParsedFile {
4
4
  bunPattern: string;
5
5
  segments: Segment[];
6
- kind: "page" | "api";
6
+ kind: "page" | "api" | "notFound";
7
7
  }
8
8
 
9
9
  const CATCHALL_RE = /^\[\.\.\.([^\]]+)\]$/;
@@ -11,7 +11,16 @@ const PARAM_RE = /^\[([^\]]+)\]$/;
11
11
 
12
12
  // relPath is path under app/routes/, e.g. "index.tsx", "hotels/[city].tsx",
13
13
  // "api/revenue.ts", "files/[...rest].tsx".
14
+ export const NOT_FOUND_FILE = "_404.tsx";
15
+
16
+ // A `.ts` file outside api/ is a handler route only when its name carries a
17
+ // content extension before `.ts` (sitemap.xml.ts, robots.txt.ts, llms.txt.ts).
18
+ const CONTENT_EXT_RE = /\.[A-Za-z0-9]+\.ts$/;
19
+
14
20
  export function parseRouteFile(relPath: string): ParsedFile {
21
+ if (relPath === NOT_FOUND_FILE) {
22
+ return { bunPattern: "/_404", segments: [], kind: "notFound" };
23
+ }
15
24
  const isApi = relPath === "api" || relPath.startsWith("api/");
16
25
  const ext = relPath.endsWith(".tsx")
17
26
  ? ".tsx"
@@ -23,10 +32,13 @@ export function parseRouteFile(relPath: string): ParsedFile {
23
32
  if (isApi && ext === ".tsx") {
24
33
  throw new Error(`API route must be .ts, not .tsx: ${relPath}`);
25
34
  }
26
- if (!isApi && ext === ".ts") {
35
+ const isContentHandler =
36
+ !isApi && ext === ".ts" && CONTENT_EXT_RE.test(relPath);
37
+ if (!isApi && ext === ".ts" && !isContentHandler) {
27
38
  throw new Error(
28
39
  `Non-API route must be .tsx (pages) - got .ts: ${relPath}. ` +
29
- `Move it under app/routes/api/ for an API route.`,
40
+ `Move it under app/routes/api/, or name it with a content extension ` +
41
+ `(e.g. sitemap.xml.ts) for a handler route.`,
30
42
  );
31
43
  }
32
44
 
@@ -61,7 +73,11 @@ export function parseRouteFile(relPath: string): ParsedFile {
61
73
  bunPattern = bunPattern.slice(0, -1);
62
74
  }
63
75
 
64
- return { bunPattern, segments, kind: isApi ? "api" : "page" };
76
+ return {
77
+ bunPattern,
78
+ segments,
79
+ kind: isApi || isContentHandler ? "api" : "page",
80
+ };
65
81
  }
66
82
 
67
83
  // Sort so that more-specific patterns come first:
@@ -5,18 +5,36 @@ export interface InlineAsset {
5
5
  type: string;
6
6
  body: string;
7
7
  base64: boolean;
8
+ // public/ files keep their names, so they must not be cached as immutable.
9
+ mutable?: boolean;
10
+ // Content hash; lets revalidating clients get a 304 instead of the body.
11
+ etag?: string;
8
12
  }
9
13
 
10
14
  // URLs carry a content hash, so a cached copy never goes stale.
11
15
  const IMMUTABLE = "public, max-age=31536000, immutable";
16
+ const REVALIDATE = "public, max-age=0, must-revalidate";
12
17
 
13
- export function inlineAssetResponse(asset: InlineAsset): Response {
18
+ export function inlineAssetResponse(
19
+ asset: InlineAsset,
20
+ req?: Request,
21
+ ): Response {
22
+ const headers: Record<string, string> = {
23
+ "content-type": asset.type,
24
+ "cache-control": asset.mutable ? REVALIDATE : IMMUTABLE,
25
+ };
26
+ if (asset.etag) {
27
+ const etag = `"${asset.etag}"`;
28
+ headers.etag = etag;
29
+ const inm = req?.headers.get("if-none-match");
30
+ if (inm?.split(",").some((t) => t.trim().replace(/^W\//, "") === etag)) {
31
+ return new Response(null, { status: 304, headers });
32
+ }
33
+ }
14
34
  const body = asset.base64
15
35
  ? Uint8Array.from(atob(asset.body), (c) => c.charCodeAt(0))
16
36
  : asset.body;
17
- return new Response(body, {
18
- headers: { "content-type": asset.type, "cache-control": IMMUTABLE },
19
- });
37
+ return new Response(body, { headers });
20
38
  }
21
39
 
22
40
  export function inlineAssetRoutes(
@@ -35,5 +53,5 @@ export function matchInlineAsset(
35
53
  ): Response | null {
36
54
  if (req.method !== "GET" && req.method !== "HEAD") return null;
37
55
  const asset = assets[new URL(req.url).pathname];
38
- return asset ? inlineAssetResponse(asset) : null;
56
+ return asset ? inlineAssetResponse(asset, req) : null;
39
57
  }
package/src/types.ts CHANGED
@@ -30,7 +30,7 @@ export interface Segment {
30
30
  export interface RouteEntry {
31
31
  filePath: string;
32
32
  bunPattern: string;
33
- kind: "page" | "api";
33
+ kind: "page" | "api" | "notFound";
34
34
  segments: Segment[];
35
35
  }
36
36