sordo 0.4.0 → 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.
Files changed (152) hide show
  1. package/CHANGELOG.md +6 -116
  2. package/README.md +8 -175
  3. package/bin/sordo.ts +1 -4
  4. package/package.json +17 -41
  5. package/src/agents-md.ts +1 -0
  6. package/src/ai.ts +1 -0
  7. package/src/build.ts +1 -0
  8. package/src/client.ts +1 -0
  9. package/src/config.ts +1 -0
  10. package/src/dev.ts +1 -0
  11. package/src/index.ts +1 -55
  12. package/src/middleware.ts +1 -0
  13. package/src/plugin.ts +1 -0
  14. package/src/render.ts +1 -0
  15. package/src/router.ts +1 -0
  16. package/src/server.ts +1 -0
  17. package/CLAUDE.md +0 -124
  18. package/src/adapters/bun.ts +0 -59
  19. package/src/adapters/edge.ts +0 -75
  20. package/src/adapters/types.ts +0 -43
  21. package/src/agents-md/collect.ts +0 -113
  22. package/src/agents-md/generate.ts +0 -44
  23. package/src/agents-md/index.ts +0 -9
  24. package/src/agents-md/render.ts +0 -150
  25. package/src/agents-md/subprocess-entry.ts +0 -92
  26. package/src/agents-md/subprocess-runner.ts +0 -111
  27. package/src/agents-md/write.ts +0 -38
  28. package/src/agents-md/zod-to-json-schema.ts +0 -18
  29. package/src/ai/context.ts +0 -72
  30. package/src/ai/define.ts +0 -15
  31. package/src/ai/errors.ts +0 -51
  32. package/src/ai/index.ts +0 -36
  33. package/src/ai/middleware.ts +0 -21
  34. package/src/ai/registry.ts +0 -96
  35. package/src/ai/run.ts +0 -185
  36. package/src/ai/scan.ts +0 -42
  37. package/src/ai/stream.ts +0 -71
  38. package/src/ai/triggers.ts +0 -124
  39. package/src/ai/types.ts +0 -67
  40. package/src/ai/validate.ts +0 -82
  41. package/src/build/assets.ts +0 -48
  42. package/src/build/client-entry.ts +0 -43
  43. package/src/build/css.ts +0 -102
  44. package/src/build/embedded.ts +0 -66
  45. package/src/build/hash.ts +0 -21
  46. package/src/build/index.ts +0 -480
  47. package/src/build/macros/agents-hash.macro.ts +0 -9
  48. package/src/build/macros/agents.macro.ts +0 -21
  49. package/src/build/macros/env.macro.ts +0 -25
  50. package/src/build/macros/inline-assets.macro.ts +0 -28
  51. package/src/build/macros/manifest.macro.ts +0 -8
  52. package/src/build/macros/routes.macro.ts +0 -10
  53. package/src/build/page-entry.ts +0 -136
  54. package/src/build/scan-islands.ts +0 -39
  55. package/src/build/server-entry.ts +0 -256
  56. package/src/cli/ansi.ts +0 -41
  57. package/src/cli/build.ts +0 -195
  58. package/src/cli/commands/add/apply.ts +0 -31
  59. package/src/cli/commands/add/component-diff.ts +0 -116
  60. package/src/cli/commands/add/diff.ts +0 -153
  61. package/src/cli/commands/add/internal.ts +0 -41
  62. package/src/cli/commands/add/load-catalog.ts +0 -22
  63. package/src/cli/commands/add/peer-deps.ts +0 -115
  64. package/src/cli/commands/add/registry-fetch.ts +0 -122
  65. package/src/cli/commands/add/shadcn.ts +0 -285
  66. package/src/cli/commands/add/source.ts +0 -273
  67. package/src/cli/commands/add/stamper.ts +0 -73
  68. package/src/cli/commands/add/tokens.ts +0 -81
  69. package/src/cli/commands/add/ui-paths.ts +0 -113
  70. package/src/cli/commands/add.ts +0 -427
  71. package/src/cli/commands/deploy.ts +0 -143
  72. package/src/cli/commands/migrate.ts +0 -149
  73. package/src/cli/commands/secret.ts +0 -316
  74. package/src/cli/commands/ui/build.ts +0 -111
  75. package/src/cli/commands/ui/init.ts +0 -135
  76. package/src/cli/commands/ui/migrate/git-guard.ts +0 -19
  77. package/src/cli/commands/ui/migrate/radix.ts +0 -67
  78. package/src/cli/commands/ui/migrate/rtl.ts +0 -148
  79. package/src/cli/commands/ui/shadcn.ts +0 -82
  80. package/src/cli/commands/ui/view.ts +0 -63
  81. package/src/cli/commands/ui.ts +0 -86
  82. package/src/cli/commands/update.ts +0 -134
  83. package/src/cli/commands/upgrade.ts +0 -53
  84. package/src/cli/commands/view.ts +0 -34
  85. package/src/cli/dev.ts +0 -393
  86. package/src/cli/doctor/config-checks.ts +0 -63
  87. package/src/cli/doctor/deps.ts +0 -295
  88. package/src/cli/doctor/hydrate.ts +0 -65
  89. package/src/cli/doctor/monorepo.ts +0 -158
  90. package/src/cli/doctor/probes.ts +0 -16
  91. package/src/cli/doctor/report.ts +0 -72
  92. package/src/cli/doctor/toolchain.ts +0 -95
  93. package/src/cli/doctor/types.ts +0 -36
  94. package/src/cli/doctor.ts +0 -127
  95. package/src/cli/index.ts +0 -168
  96. package/src/cli/log.ts +0 -135
  97. package/src/cli/run/affected.ts +0 -79
  98. package/src/cli/run/cache-key.ts +0 -177
  99. package/src/cli/run/cache-store.ts +0 -0
  100. package/src/cli/run/files.ts +0 -96
  101. package/src/cli/run/git.ts +0 -13
  102. package/src/cli/run/runner.ts +0 -189
  103. package/src/cli/run/workspace.ts +0 -216
  104. package/src/cli/run.ts +0 -184
  105. package/src/cli/start.ts +0 -99
  106. package/src/cli/update-check.ts +0 -157
  107. package/src/client/index.ts +0 -65
  108. package/src/client/link.tsx +0 -61
  109. package/src/client/page.ts +0 -250
  110. package/src/config/define.ts +0 -5
  111. package/src/config/env.ts +0 -36
  112. package/src/config/load.ts +0 -152
  113. package/src/config/schema.ts +0 -135
  114. package/src/config/secrets.ts +0 -108
  115. package/src/dev/client.ts +0 -112
  116. package/src/dev/hot.ts +0 -24
  117. package/src/dev/index.ts +0 -4
  118. package/src/dev/tree.ts +0 -95
  119. package/src/dev/watcher.ts +0 -95
  120. package/src/internal/hmr-client.ts +0 -52
  121. package/src/internal/open-in-editor.ts +0 -23
  122. package/src/internal/runtime.ts +0 -30
  123. package/src/middleware/cookie-jar.ts +0 -135
  124. package/src/middleware/cookies.ts +0 -60
  125. package/src/middleware/index.ts +0 -127
  126. package/src/middleware/request-id.ts +0 -22
  127. package/src/middleware/response-helpers.ts +0 -25
  128. package/src/plugin/index.ts +0 -109
  129. package/src/render/bootstrap.ts +0 -44
  130. package/src/render/dev-error.tsx +0 -73
  131. package/src/render/index.tsx +0 -261
  132. package/src/render/island.tsx +0 -33
  133. package/src/render/meta.tsx +0 -48
  134. package/src/render/shell.tsx +0 -41
  135. package/src/router/conflict.ts +0 -20
  136. package/src/router/filesystem.ts +0 -37
  137. package/src/router/index.ts +0 -247
  138. package/src/router/match.ts +0 -91
  139. package/src/router/pattern.ts +0 -88
  140. package/src/server/index.ts +0 -250
  141. package/src/server/inline-assets.ts +0 -39
  142. package/src/types.ts +0 -53
  143. package/src/ui/schema.ts +0 -68
  144. package/src/ui/types.ts +0 -10
  145. package/templates/_internal/cn.ts +0 -6
  146. package/templates/_internal/slot.ts +0 -50
  147. package/templates/_internal/variants.ts +0 -1
  148. package/templates/themes/neutral/tokens.css +0 -46
  149. package/templates/themes/slate/tokens.css +0 -46
  150. package/templates/themes/stone/tokens.css +0 -46
  151. package/templates/themes/zinc/tokens.css +0 -46
  152. package/templates/tokens.css +0 -46
@@ -1,127 +0,0 @@
1
- import type { AiContext } from "../ai/types.ts";
2
- import { bunGlobal, runtimeEnv } from "../internal/runtime.ts";
3
- import { CookieJar } from "./cookie-jar.ts";
4
- import { finalizeResponse } from "./cookies.ts";
5
- import { resolveRequestId } from "./request-id.ts";
6
- import {
7
- htmlResponse,
8
- jsonResponse,
9
- redirectResponse,
10
- } from "./response-helpers.ts";
11
-
12
- // Apps augment this to type their Worker bindings on the edge target:
13
- // declare module "sordo" { interface SordoBindings { CMS: Fetcher } }
14
- // biome-ignore lint/suspicious/noEmptyInterface: declaration-merging seam
15
- export interface SordoBindings {}
16
-
17
- export interface SordoContext {
18
- params: Record<string, string>;
19
- // Framework-generated correlation id, populated before user middleware runs.
20
- // User middleware/plugins read it; they MUST NOT re-generate it.
21
- requestId: string;
22
- cookies: unknown;
23
- // Process env merged with the string vars/secrets from the Worker env on edge.
24
- env: Record<string, string | undefined>;
25
- // Raw Worker env (KV/R2/D1/service bindings) on edge; empty object on bun.
26
- bindings: SordoBindings;
27
- // Extends the request lifetime on edge; awaits nothing and swallows nothing on bun.
28
- waitUntil(p: Promise<unknown>): void;
29
- aiContext?: AiContext;
30
- csrf?: { token(): string; verify(t: string | null): boolean };
31
- vars: Record<string, unknown>;
32
- url: URL;
33
- json(body: unknown, init?: ResponseInit): Response;
34
- html(body: string | ReadableStream, init?: ResponseInit): Response;
35
- redirect(to: string, status?: 301 | 302 | 303 | 307 | 308): Response;
36
- }
37
-
38
- export type Handler = (
39
- req: Request,
40
- ctx: SordoContext,
41
- ) => Response | Promise<Response>;
42
-
43
- export type Middleware = (
44
- req: Request,
45
- ctx: SordoContext,
46
- next: () => Promise<Response>,
47
- ) => Promise<Response>;
48
-
49
- export function defineMiddleware(m: Middleware): Middleware {
50
- return m;
51
- }
52
-
53
- export function compose(middlewares: Middleware[], handler: Handler): Handler {
54
- return (req, ctx) => {
55
- let lastIdx = -1;
56
- const dispatch = (idx: number): Promise<Response> => {
57
- if (idx <= lastIdx) {
58
- return Promise.reject(new Error("next() called multiple times"));
59
- }
60
- lastIdx = idx;
61
- const fn = idx < middlewares.length ? middlewares[idx] : null;
62
- if (!fn) return Promise.resolve(handler(req, ctx));
63
- return Promise.resolve(fn(req, ctx, () => dispatch(idx + 1)));
64
- };
65
- return dispatch(0);
66
- };
67
- }
68
-
69
- export function makeContext(
70
- req: Request,
71
- params: Record<string, string> = {},
72
- ): SordoContext {
73
- let urlCache: URL | null = null;
74
- let cookiesCache: unknown;
75
- const { env: workerEnv, execCtx } = req as unknown as {
76
- env?: unknown;
77
- execCtx?: { waitUntil?: (p: Promise<unknown>) => void };
78
- };
79
- const bindings = (
80
- workerEnv && typeof workerEnv === "object" ? workerEnv : {}
81
- ) as SordoBindings;
82
- const env = { ...runtimeEnv() };
83
- for (const [k, v] of Object.entries(bindings)) {
84
- if (typeof v === "string") env[k] = v;
85
- }
86
-
87
- const ctx: SordoContext = {
88
- params,
89
- requestId: resolveRequestId(req),
90
- get cookies() {
91
- if (cookiesCache === undefined) {
92
- const anyReq = req as unknown as { cookies?: unknown };
93
- if (anyReq.cookies != null) {
94
- cookiesCache = anyReq.cookies;
95
- } else {
96
- // Bun's `fetch:` catch-all (404 fallback) and non-Bun runtimes (edge)
97
- // don't populate req.cookies. Synthesize one from the Cookie header so
98
- // middleware can read/set cookies on every path.
99
- const header = req.headers.get("cookie") ?? "";
100
- const Ctor = bunGlobal()?.CookieMap;
101
- cookiesCache = Ctor ? new Ctor(header) : new CookieJar(header);
102
- }
103
- }
104
- return cookiesCache;
105
- },
106
- env,
107
- bindings,
108
- waitUntil(p) {
109
- if (typeof execCtx?.waitUntil === "function") {
110
- execCtx.waitUntil(p);
111
- } else {
112
- p.catch(() => {});
113
- }
114
- },
115
- vars: {},
116
- get url() {
117
- if (!urlCache) urlCache = new URL(req.url);
118
- return urlCache;
119
- },
120
- json: jsonResponse,
121
- html: htmlResponse,
122
- redirect: redirectResponse,
123
- };
124
- return ctx;
125
- }
126
-
127
- export { finalizeResponse };
@@ -1,22 +0,0 @@
1
- // Request-id generation + inbound validation, shared by the request composer
2
- // (makeContext) and the AI context. UUIDv7 on Bun (time-ordered), UUIDv4 on
3
- // non-Bun targets (edge / workerd) — best-effort time-ordering across targets.
4
-
5
- // Allowlist for an inbound X-Request-Id we are willing to echo back. Keeps
6
- // control characters and oversize payloads out of log lines.
7
- export const REQUEST_ID_RE = /^[A-Za-z0-9._-]{8,128}$/;
8
-
9
- export function generateRequestId(): string {
10
- const bun = (globalThis as { Bun?: { randomUUIDv7?: () => string } }).Bun;
11
- if (bun && typeof bun.randomUUIDv7 === "function") return bun.randomUUIDv7();
12
- if (typeof crypto !== "undefined" && "randomUUID" in crypto)
13
- return crypto.randomUUID();
14
- return Math.random().toString(36).slice(2) + Date.now().toString(36);
15
- }
16
-
17
- // Echo a well-shaped inbound id from an upstream proxy; otherwise mint a fresh
18
- // one. Inbound values that fail the allowlist are ignored, not echoed.
19
- export function resolveRequestId(req: Request): string {
20
- const inbound = req.headers.get("x-request-id");
21
- return inbound && REQUEST_ID_RE.test(inbound) ? inbound : generateRequestId();
22
- }
@@ -1,25 +0,0 @@
1
- export function jsonResponse(body: unknown, init?: ResponseInit): Response {
2
- const headers = new Headers(init?.headers);
3
- if (!headers.has("Content-Type")) {
4
- headers.set("Content-Type", "application/json; charset=utf-8");
5
- }
6
- return new Response(JSON.stringify(body), { ...init, headers });
7
- }
8
-
9
- export function htmlResponse(
10
- body: string | ReadableStream,
11
- init?: ResponseInit,
12
- ): Response {
13
- const headers = new Headers(init?.headers);
14
- if (!headers.has("Content-Type")) {
15
- headers.set("Content-Type", "text/html; charset=utf-8");
16
- }
17
- return new Response(body, { ...init, headers });
18
- }
19
-
20
- export function redirectResponse(
21
- to: string,
22
- status: 301 | 302 | 303 | 307 | 308 = 302,
23
- ): Response {
24
- return new Response(null, { status, headers: { Location: to } });
25
- }
@@ -1,109 +0,0 @@
1
- import type { BuildOptions, BuildResult } from "../build/index.ts";
2
- import type { DevServer } from "../dev/watcher.ts";
3
- import { bunGlobal } from "../internal/runtime.ts";
4
- import type { Handler, Middleware } from "../middleware/index.ts";
5
- import type { HTTPMethod } from "../types.ts";
6
-
7
- export interface PluginLogger {
8
- info(msg: string, ...args: unknown[]): void;
9
- warn(msg: string, ...args: unknown[]): void;
10
- error(msg: string, ...args: unknown[]): void;
11
- }
12
-
13
- export interface PluginContext {
14
- config: unknown;
15
- root: string;
16
- logger: PluginLogger;
17
- }
18
-
19
- export interface PluginServer {
20
- route(pattern: string, methods: Partial<Record<HTTPMethod, Handler>>): void;
21
- use(middleware: Middleware): void;
22
- }
23
-
24
- export interface JobSummary {
25
- name: string;
26
- schedule?: string;
27
- tz?: string;
28
- filePath?: string;
29
- }
30
-
31
- export interface AgentsMdDocument {
32
- markdown: string;
33
- }
34
-
35
- export interface PluginHooks {
36
- onBuildStart?(opts: BuildOptions): void | Promise<void>;
37
- onBuildEnd?(result: BuildResult): void | Promise<void>;
38
- onDevStart?(server: DevServer): void | Promise<void>;
39
- onAgentsMdGenerate?(
40
- doc: AgentsMdDocument,
41
- ): AgentsMdDocument | Promise<AgentsMdDocument>;
42
- onJobsCollect?(jobs: JobSummary[]): void | Promise<void>;
43
- }
44
-
45
- export interface Plugin {
46
- name: string;
47
- compat?: string;
48
- setup?(server: PluginServer, ctx: PluginContext): void | Promise<void>;
49
- hooks?: PluginHooks;
50
- }
51
-
52
- export interface DeployArtifacts {
53
- outDir: string;
54
- serverEntry: string;
55
- }
56
-
57
- export interface DeployContext {
58
- env?: string;
59
- cwd: string;
60
- logger: PluginLogger;
61
- }
62
-
63
- export interface DeployPlugin extends Plugin {
64
- deployTarget: "bun" | "edge";
65
- deploy(
66
- artifacts: DeployArtifacts,
67
- ctx: DeployContext,
68
- ): Promise<string | undefined>;
69
- }
70
-
71
- export function isDeployPlugin(p: Plugin): p is DeployPlugin {
72
- const dp = p as Partial<DeployPlugin>;
73
- return (
74
- (dp.deployTarget === "bun" || dp.deployTarget === "edge") &&
75
- typeof dp.deploy === "function"
76
- );
77
- }
78
-
79
- export function definePlugin(p: Plugin): Plugin {
80
- if (!p || typeof p.name !== "string" || p.name.length === 0) {
81
- throw new Error("definePlugin: `name` is required");
82
- }
83
- return p;
84
- }
85
-
86
- export function assertPluginCompat(
87
- frameworkVersion: string,
88
- plugin: Plugin,
89
- logger: PluginLogger = console,
90
- ): void {
91
- if (!plugin.compat) {
92
- logger.warn(
93
- `[sordo] plugin "${plugin.name}" has no \`compat\` range — pinning is encouraged.`,
94
- );
95
- return;
96
- }
97
- const semver = bunGlobal()?.semver;
98
- if (!semver || typeof semver.satisfies !== "function") {
99
- // No-op when Bun.semver isn't available (non-Bun runtime in tests).
100
- return;
101
- }
102
- if (!semver.satisfies(frameworkVersion, plugin.compat)) {
103
- throw new Error(
104
- `[plugin ${plugin.name}] incompatible with framework version ${frameworkVersion} (requires ${plugin.compat})`,
105
- );
106
- }
107
- }
108
-
109
- export type { BuildOptions, BuildResult, DevServer };
@@ -1,44 +0,0 @@
1
- // Shared by the SSR renderer and the browser runtime, so it must stay free of
2
- // DOM, Bun and React imports.
3
-
4
- export const BOOTSTRAP_ID = "__sordo_bootstrap";
5
-
6
- // Request header the client navigator sets to ask for the route's bootstrap
7
- // payload as JSON instead of an HTML document.
8
- export const NAV_HEADER = "x-sordo-nav";
9
-
10
- export interface BootstrapPayload {
11
- params: Record<string, string>;
12
- // Present only when the page exports `loader()`. Already passed through the
13
- // page's `serialize` hook, so it is plain JSON.
14
- data?: unknown;
15
- }
16
-
17
- // Answer to a navigation request. `hydrated: false` tells the client to fall
18
- // back to a full document load (the target route ships no page bundle).
19
- export type NavPayload =
20
- | {
21
- hydrated: true;
22
- route: string;
23
- script: string;
24
- bootstrap: BootstrapPayload;
25
- title?: string;
26
- }
27
- | { hydrated: false };
28
-
29
- export function encodeBootstrap(payload: BootstrapPayload): string {
30
- return JSON.stringify(payload);
31
- }
32
-
33
- // Rebuild the props the server rendered the page with. `deserialize` is the
34
- // page's optional hook for non-JSON types (Date, Map, …).
35
- export function bootstrapProps(
36
- payload: BootstrapPayload,
37
- deserialize?: (data: unknown) => unknown,
38
- ): Record<string, unknown> {
39
- const props: Record<string, unknown> = { ...payload.params };
40
- if ("data" in payload) {
41
- props.data = deserialize ? deserialize(payload.data) : payload.data;
42
- }
43
- return props;
44
- }
@@ -1,73 +0,0 @@
1
- // Build the dev error page as an HTML string using Bun.escapeHTML, then return
2
- // a Response. We bypass React for the error page so a broken render path can
3
- // always produce something useful.
4
-
5
- interface StackFrame {
6
- file: string;
7
- line: number;
8
- column?: number;
9
- }
10
-
11
- function parseStack(stack: string): StackFrame[] {
12
- const frames: StackFrame[] = [];
13
- for (const raw of stack.split("\n")) {
14
- const m = raw.match(/\(?([^()\s]+\.tsx?):(\d+)(?::(\d+))?\)?/);
15
- if (!m?.[1] || !m[2]) continue;
16
- frames.push({
17
- file: m[1],
18
- line: Number(m[2]),
19
- column: m[3] ? Number(m[3]) : undefined,
20
- });
21
- }
22
- return frames;
23
- }
24
-
25
- async function snippetFor(file: string, line: number): Promise<string> {
26
- try {
27
- const text = await Bun.file(file).text();
28
- const lines = text.split("\n");
29
- const start = Math.max(0, line - 3);
30
- const end = Math.min(lines.length, line + 2);
31
- const out: string[] = [];
32
- for (let i = start; i < end; i++) {
33
- const marker = i + 1 === line ? "> " : " ";
34
- const num = String(i + 1).padStart(4, " ");
35
- out.push(`${marker}${num} | ${lines[i] ?? ""}`);
36
- }
37
- return Bun.escapeHTML(out.join("\n"));
38
- } catch {
39
- return "";
40
- }
41
- }
42
-
43
- export async function renderDevErrorPage(err: unknown): Promise<Response> {
44
- const inspected = Bun.escapeHTML(Bun.inspect(err, { colors: false }));
45
- const stack = err instanceof Error && err.stack ? err.stack : "";
46
- const frames = parseStack(stack);
47
-
48
- const frameBlocks: string[] = [];
49
- for (const f of frames.slice(0, 5)) {
50
- const snippet = await snippetFor(f.file, f.line);
51
- const link = `/__sordo_open?file=${encodeURIComponent(f.file)}&line=${f.line}`;
52
- frameBlocks.push(
53
- `<section><a href="${Bun.escapeHTML(link)}"><code>${Bun.escapeHTML(f.file)}:${f.line}</code></a>` +
54
- (snippet ? `<pre>${snippet}</pre>` : "") +
55
- `</section>`,
56
- );
57
- }
58
-
59
- const body =
60
- `<!DOCTYPE html><html><head><meta charset="utf-8"><title>Sordo dev error</title>` +
61
- `<style>body{font:14px/1.4 ui-monospace,Menlo,monospace;padding:24px;color:#222;background:#fff8f6}` +
62
- `h1{color:#b00020}pre{background:#fff;border:1px solid #eee;padding:8px 12px;overflow:auto}` +
63
- `section{margin:12px 0}a{color:#0049b0;text-decoration:none}</style></head><body>` +
64
- `<h1>Render error</h1><pre>${inspected}</pre>` +
65
- frameBlocks.join("") +
66
- `<footer><small>HMR connected - this page will reload when you fix the source.</small></footer>` +
67
- `</body></html>`;
68
-
69
- return new Response(body, {
70
- status: 500,
71
- headers: { "Content-Type": "text/html; charset=utf-8" },
72
- });
73
- }
@@ -1,261 +0,0 @@
1
- import * as React from "react";
2
- import { renderToReadableStream } from "react-dom/server";
3
- import type { RouteEntry, SordoContext } from "../types.ts";
4
- import {
5
- type BootstrapPayload,
6
- encodeBootstrap,
7
- NAV_HEADER,
8
- type NavPayload,
9
- } from "./bootstrap.ts";
10
- import { renderDevErrorPage } from "./dev-error.tsx";
11
- import { defaultHead, type MetaInput, renderMetaTags } from "./meta.tsx";
12
- import { Shell } from "./shell.tsx";
13
-
14
- export { Island, type IslandProps } from "./island.tsx";
15
-
16
- import { HMR_CLIENT_SCRIPT } from "../internal/hmr-client.ts";
17
-
18
- export interface ClientManifest {
19
- // URL of the synthetic island-registration entry; null when project has zero islands.
20
- entry?: string | null;
21
- // Island name → bundled chunk URL. Populated by the build module.
22
- islands?: Record<string, string>;
23
- // Legacy lookup (page-route bunPattern → script URL). Kept for callers that
24
- // still drive the renderer without going through `build()`.
25
- byEntry?: Record<string, string>;
26
- // Whole-tree hydrated routes: page-route bunPattern → page entry chunk URL.
27
- // Presence here is what marks a route as hydrated at request time.
28
- pages?: Record<string, string>;
29
- // Hashed stylesheet URL from the `css` build entry; linked on every page.
30
- css?: string;
31
- }
32
-
33
- // The page-module surface the renderer reads. Everything is optional except
34
- // the default-exported component.
35
- export interface PageModule {
36
- default?: unknown;
37
- meta?: MetaInput;
38
- head?: () => React.ReactNode;
39
- // Opt into whole-tree hydration. Read statically at build time.
40
- hydrate?: boolean;
41
- // Runs on the server before render. Its result reaches the page as `data`.
42
- // Returning a Response (e.g. a redirect) short-circuits the render.
43
- loader?: (req: Request, ctx: SordoContext) => unknown;
44
- // Converts `loader()` output to JSON-safe data for the bootstrap payload.
45
- serialize?: (data: unknown) => unknown;
46
- // Client-side inverse of `serialize`.
47
- deserialize?: (data: unknown) => unknown;
48
- }
49
-
50
- export interface RenderOptions {
51
- manifest?: ClientManifest;
52
- dev?: boolean;
53
- // Pre-imported page modules keyed by entry.filePath. When provided, used instead of `await import(entry.filePath)`.
54
- modules?: Record<string, unknown>;
55
- }
56
-
57
- export interface Renderer {
58
- renderPage(
59
- entry: RouteEntry,
60
- req: Request,
61
- ctx: SordoContext,
62
- ): Promise<Response>;
63
- }
64
-
65
- const HMR_TAG_BYTES = new TextEncoder().encode(
66
- `<script>${HMR_CLIENT_SCRIPT}</script>`,
67
- );
68
- const BODY_CLOSE_RE = /<\/body>/i;
69
-
70
- export function createRenderer(options: RenderOptions = {}): Renderer {
71
- const { manifest, dev = false, modules } = options;
72
-
73
- return {
74
- async renderPage(entry, req, ctx) {
75
- try {
76
- const mod = (modules?.[entry.filePath] ??
77
- (await import(entry.filePath))) as PageModule;
78
-
79
- const Page = mod.default;
80
- if (typeof Page !== "function") {
81
- throw new Error(
82
- `Page module ${entry.filePath} has no default-exported component`,
83
- );
84
- }
85
-
86
- const pageScript = manifest?.pages?.[entry.bunPattern];
87
- const isNav = req.headers.get(NAV_HEADER) === "1";
88
- if (isNav && !pageScript) {
89
- return navResponse({ hydrated: false });
90
- }
91
-
92
- let data: unknown;
93
- let hasData = false;
94
- if (typeof mod.loader === "function") {
95
- const result = await mod.loader(req, ctx);
96
- if (result instanceof Response) return result;
97
- data = result;
98
- hasData = true;
99
- }
100
-
101
- let bootstrap: BootstrapPayload | undefined;
102
- if (pageScript) {
103
- bootstrap = { params: { ...ctx.params } };
104
- if (hasData) {
105
- bootstrap.data = mod.serialize ? mod.serialize(data) : data;
106
- }
107
- }
108
-
109
- if (isNav && pageScript && bootstrap) {
110
- return navResponse({
111
- hydrated: true,
112
- route: entry.bunPattern,
113
- script: pageScript,
114
- bootstrap,
115
- title: mod.meta?.title,
116
- });
117
- }
118
-
119
- const headNodes: React.ReactNode[] = [];
120
- if (mod.meta) {
121
- // Always include charset/viewport so opting into `meta` doesn't
122
- // silently drop the baseline head tags.
123
- headNodes.push(
124
- <meta key="charset" charSet="utf-8" />,
125
- <meta
126
- key="viewport"
127
- name="viewport"
128
- content="width=device-width, initial-scale=1"
129
- />,
130
- );
131
- headNodes.push(...renderMetaTags(mod.meta));
132
- } else if (!mod.head) {
133
- headNodes.push(...defaultHead(ctx.url.pathname));
134
- } else {
135
- // head() but no meta — still emit charset/viewport defaults.
136
- headNodes.push(
137
- <meta key="charset" charSet="utf-8" />,
138
- <meta
139
- key="viewport"
140
- name="viewport"
141
- content="width=device-width, initial-scale=1"
142
- />,
143
- );
144
- }
145
- // Before the page's own head() so its tags can override the sheet.
146
- if (manifest?.css) {
147
- headNodes.push(
148
- <link key="sordo-css" rel="stylesheet" href={manifest.css} />,
149
- );
150
- }
151
- if (mod.head) {
152
- headNodes.push(
153
- <React.Fragment key="user-head">{mod.head()}</React.Fragment>,
154
- );
155
- }
156
-
157
- // A hydrated page's bundle replaces the island entry: the whole tree
158
- // hydrates, so per-island roots would be redundant.
159
- const clientScriptUrl =
160
- pageScript ??
161
- manifest?.byEntry?.[entry.bunPattern] ??
162
- manifest?.entry ??
163
- undefined;
164
-
165
- const props: Record<string, unknown> = { ...ctx.params };
166
- if (hasData) props.data = data;
167
-
168
- const tree = (
169
- <Shell
170
- headNodes={headNodes}
171
- clientScriptUrl={clientScriptUrl}
172
- bootstrap={bootstrap ? encodeBootstrap(bootstrap) : undefined}
173
- >
174
- {React.createElement(Page as React.FC, props)}
175
- </Shell>
176
- );
177
-
178
- const reactStream = await renderToReadableStream(tree, {
179
- onError(error) {
180
- if (dev) console.error("[sordo] render error:", error);
181
- },
182
- });
183
-
184
- const combined = composeStream(reactStream, dev);
185
-
186
- const headers: Record<string, string> = {
187
- "Content-Type": "text/html; charset=utf-8",
188
- };
189
- // Same URL serves HTML or a nav payload depending on NAV_HEADER.
190
- if (pageScript) headers.Vary = NAV_HEADER;
191
- return new Response(combined, { headers });
192
- } catch (err) {
193
- if (dev) return renderDevErrorPage(err);
194
- return new Response("Internal Server Error", { status: 500 });
195
- }
196
- },
197
- };
198
- }
199
-
200
- function navResponse(payload: NavPayload): Response {
201
- return new Response(JSON.stringify(payload), {
202
- headers: {
203
- "Content-Type": "application/json; charset=utf-8",
204
- "Cache-Control": "no-store",
205
- Vary: NAV_HEADER,
206
- },
207
- });
208
- }
209
-
210
- function composeStream(
211
- reactStream: ReadableStream<Uint8Array>,
212
- dev: boolean,
213
- ): ReadableStream<Uint8Array> {
214
- return new ReadableStream<Uint8Array>({
215
- async start(controller) {
216
- const reader = reactStream.getReader();
217
- const decoder = new TextDecoder();
218
- const encoder = new TextEncoder();
219
- let buffered = "";
220
- let injected = false;
221
-
222
- try {
223
- while (true) {
224
- const { done, value } = await reader.read();
225
- if (done) break;
226
- if (!dev || injected) {
227
- if (buffered) {
228
- controller.enqueue(encoder.encode(buffered));
229
- buffered = "";
230
- }
231
- controller.enqueue(value);
232
- continue;
233
- }
234
- buffered += decoder.decode(value, { stream: true });
235
- if (BODY_CLOSE_RE.test(buffered)) {
236
- const withInjection = buffered.replace(
237
- BODY_CLOSE_RE,
238
- `<script>${HMR_CLIENT_SCRIPT}</script></body>`,
239
- );
240
- controller.enqueue(encoder.encode(withInjection));
241
- buffered = "";
242
- injected = true;
243
- }
244
- }
245
- if (buffered) {
246
- if (dev && !injected) {
247
- controller.enqueue(encoder.encode(buffered));
248
- controller.enqueue(HMR_TAG_BYTES);
249
- } else {
250
- controller.enqueue(encoder.encode(buffered));
251
- }
252
- } else if (dev && !injected) {
253
- controller.enqueue(HMR_TAG_BYTES);
254
- }
255
- controller.close();
256
- } catch (err) {
257
- controller.error(err);
258
- }
259
- },
260
- });
261
- }
@@ -1,33 +0,0 @@
1
- import type * as React from "react";
2
-
3
- export interface IslandProps {
4
- // Registered island name (matches the file in `app/islands/`).
5
- name: string;
6
- // JSON-serializable props passed to the client component on hydrate.
7
- props?: Record<string, unknown>;
8
- // Pre-rendered SSR output of the island component. Required so SSR HTML
9
- // matches what `hydrateRoot` will render — otherwise React logs a
10
- // hydration-mismatch warning and discards the SSR tree.
11
- children?: React.ReactNode;
12
- }
13
-
14
- // Renders the marker + props blob the client runtime (`createClient().hydrateAll()`)
15
- // looks for. Layout:
16
- // <div data-island="<name>">…SSR output…</div>
17
- // <script type="application/json" data-props data-for="<name>">{"…":…}</script>
18
- //
19
- // The script must be the marker's `nextElementSibling` — that's how the
20
- // runtime locates it via `matches('script[data-props][data-for="<name>"]')`.
21
- export function Island({ name, props, children }: IslandProps) {
22
- // `<` is the only character that can break out of a <script> raw-text element.
23
- // React escapes it inside text children to `<`, which JSON.parse accepts.
24
- const json = JSON.stringify(props ?? {});
25
- return (
26
- <>
27
- <div data-island={name}>{children}</div>
28
- <script type="application/json" data-props data-for={name}>
29
- {json}
30
- </script>
31
- </>
32
- );
33
- }