@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/dist/server.mjs
ADDED
|
@@ -0,0 +1,850 @@
|
|
|
1
|
+
import { a as _setRequestEnvReader, i as renderCollectedHeadTags, n as applyHeadToState, t as _setServerHeadHook } from "./head-CUiNFY7Q.mjs";
|
|
2
|
+
import { n as decodeMultipartRpcArgs } from "./multipart-CwqTb3AQ.mjs";
|
|
3
|
+
import { a as createServerCall, c as isStandardSchema, f as validateSchema, n as RedirectSignal, r as ValidationError, t as HttpStatusError } from "./protocol-CZANZJ5x.mjs";
|
|
4
|
+
import { c as matchNestedRoutes, d as createReceiptCollector, i as buildRoutes, n as buildApiRoutes, o as extractSpecialRoutes, r as buildMatchedRouteView, t as Outlet } from "./router-B50LekA_.mjs";
|
|
5
|
+
import { _comp } from "@fierst/blokd";
|
|
6
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
7
|
+
import { Hono } from "hono";
|
|
8
|
+
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
|
|
9
|
+
import { renderToStream, renderToStringAsync, resolveIslandSrc } from "@fierst/blokd/ssr";
|
|
10
|
+
// src/db.ts
|
|
11
|
+
let activeDbContextReader = null;
|
|
12
|
+
/** @internal Wired by `@fierst/c7t/server` to read the active Hono `AsyncLocalStorage` store. */
|
|
13
|
+
function _setDbContextReader(reader) {
|
|
14
|
+
activeDbContextReader = reader;
|
|
15
|
+
}
|
|
16
|
+
function buildMergedEnv(requestEnv) {
|
|
17
|
+
const procEnv = typeof process !== "undefined" && process.env ? process.env : {};
|
|
18
|
+
if (!requestEnv) return procEnv;
|
|
19
|
+
return new Proxy(requestEnv, {
|
|
20
|
+
get(target, prop) {
|
|
21
|
+
if (typeof prop === "symbol") return Reflect.get(target, prop);
|
|
22
|
+
if (prop in target && target[prop] !== void 0) return target[prop];
|
|
23
|
+
return procEnv[prop];
|
|
24
|
+
},
|
|
25
|
+
has(target, prop) {
|
|
26
|
+
return prop in target || typeof prop === "string" && prop in procEnv;
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
function hasRequestBindings(requestEnv) {
|
|
31
|
+
if (!requestEnv || typeof requestEnv !== "object") return false;
|
|
32
|
+
for (const _k in requestEnv) return true;
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Create a lazy, request-aware database proxy that works identically across Node.js/Bun connection pools
|
|
37
|
+
* (`process.env.DATABASE_URL`) and Cloudflare Workers per-request bindings (`req.env.DB` D1 / Hyperdrive).
|
|
38
|
+
*
|
|
39
|
+
* Works with Drizzle, Kysely, `node:sqlite`, `Bun.sql`, LibSQL/Turso, Neon, or any database client.
|
|
40
|
+
*/
|
|
41
|
+
function defineDb(factory, options = {}) {
|
|
42
|
+
const scope = options.scope ?? "auto";
|
|
43
|
+
let singleton;
|
|
44
|
+
const scopedCache = /* @__PURE__ */ new WeakMap();
|
|
45
|
+
function resolveClient() {
|
|
46
|
+
const ctx = activeDbContextReader?.() ?? null;
|
|
47
|
+
const mergedEnv = buildMergedEnv(ctx?.requestEnv);
|
|
48
|
+
if (scope === "singleton") {
|
|
49
|
+
if (singleton === void 0) singleton = factory(mergedEnv);
|
|
50
|
+
return singleton;
|
|
51
|
+
}
|
|
52
|
+
if (scope === "request") {
|
|
53
|
+
if (!ctx) return factory(mergedEnv);
|
|
54
|
+
let hit = scopedCache.get(ctx.requestKey);
|
|
55
|
+
if (hit === void 0) {
|
|
56
|
+
hit = factory(mergedEnv);
|
|
57
|
+
scopedCache.set(ctx.requestKey, hit);
|
|
58
|
+
}
|
|
59
|
+
return hit;
|
|
60
|
+
}
|
|
61
|
+
if (ctx && hasRequestBindings(ctx.requestEnv)) {
|
|
62
|
+
const cacheKey = ctx.requestEnv;
|
|
63
|
+
let hit = scopedCache.get(cacheKey);
|
|
64
|
+
if (hit === void 0) {
|
|
65
|
+
hit = factory(mergedEnv);
|
|
66
|
+
scopedCache.set(cacheKey, hit);
|
|
67
|
+
}
|
|
68
|
+
return hit;
|
|
69
|
+
}
|
|
70
|
+
if (singleton === void 0) singleton = factory(mergedEnv);
|
|
71
|
+
return singleton;
|
|
72
|
+
}
|
|
73
|
+
return new Proxy({}, {
|
|
74
|
+
get(_target, prop, _receiver) {
|
|
75
|
+
if (prop === "$client") return resolveClient();
|
|
76
|
+
if (prop === "then") return void 0;
|
|
77
|
+
const client = resolveClient();
|
|
78
|
+
const val = Reflect.get(client, prop, client);
|
|
79
|
+
return typeof val === "function" ? val.bind(client) : val;
|
|
80
|
+
},
|
|
81
|
+
set(_target, prop, value) {
|
|
82
|
+
const client = resolveClient();
|
|
83
|
+
return Reflect.set(client, prop, value, client);
|
|
84
|
+
},
|
|
85
|
+
has(_target, prop) {
|
|
86
|
+
if (prop === "$client") return true;
|
|
87
|
+
return prop in resolveClient();
|
|
88
|
+
},
|
|
89
|
+
ownKeys() {
|
|
90
|
+
return Reflect.ownKeys(resolveClient());
|
|
91
|
+
},
|
|
92
|
+
getOwnPropertyDescriptor(_target, prop) {
|
|
93
|
+
const desc = Object.getOwnPropertyDescriptor(resolveClient(), prop);
|
|
94
|
+
return desc ? {
|
|
95
|
+
...desc,
|
|
96
|
+
configurable: true
|
|
97
|
+
} : void 0;
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
// src/session.ts
|
|
102
|
+
const keyCache = /* @__PURE__ */ new Map();
|
|
103
|
+
const encoder = new TextEncoder();
|
|
104
|
+
const decoder = new TextDecoder();
|
|
105
|
+
function getHmacKey(secret) {
|
|
106
|
+
let cached = keyCache.get(secret);
|
|
107
|
+
if (!cached) {
|
|
108
|
+
cached = crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
109
|
+
name: "HMAC",
|
|
110
|
+
hash: "SHA-256"
|
|
111
|
+
}, false, ["sign", "verify"]);
|
|
112
|
+
keyCache.set(secret, cached);
|
|
113
|
+
}
|
|
114
|
+
return cached;
|
|
115
|
+
}
|
|
116
|
+
function toBase64Url(bytes) {
|
|
117
|
+
let binary = "";
|
|
118
|
+
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
|
|
119
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
120
|
+
}
|
|
121
|
+
function fromBase64Url(str) {
|
|
122
|
+
try {
|
|
123
|
+
const padded = str.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((str.length + 3) % 4);
|
|
124
|
+
const binary = atob(padded);
|
|
125
|
+
const bytes = new Uint8Array(binary.length);
|
|
126
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
127
|
+
return bytes;
|
|
128
|
+
} catch {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function createSessionWithCookies(config, cookieBridge) {
|
|
133
|
+
const secrets = Array.isArray(config.secret) ? config.secret : [config.secret];
|
|
134
|
+
if (secrets.length === 0 || !secrets[0]) throw new Error("[c7t session] `createSession` requires at least one non-empty `secret`.");
|
|
135
|
+
const cookieName = config.name ?? "c7t_session";
|
|
136
|
+
const maxAge = config.maxAge ?? 604800;
|
|
137
|
+
const path = config.path ?? "/";
|
|
138
|
+
const httpOnly = config.httpOnly ?? true;
|
|
139
|
+
const sameSite = config.sameSite ?? "Lax";
|
|
140
|
+
async function sign(data) {
|
|
141
|
+
const envelope = {
|
|
142
|
+
d: data,
|
|
143
|
+
exp: maxAge > 0 ? Math.floor(Date.now() / 1e3) + maxAge : void 0
|
|
144
|
+
};
|
|
145
|
+
const payloadB64 = toBase64Url(encoder.encode(JSON.stringify(envelope)));
|
|
146
|
+
const key = await getHmacKey(secrets[0]);
|
|
147
|
+
const sigBuf = await crypto.subtle.sign("HMAC", key, encoder.encode(payloadB64));
|
|
148
|
+
return `${payloadB64}.${toBase64Url(new Uint8Array(sigBuf))}`;
|
|
149
|
+
}
|
|
150
|
+
async function verify(token) {
|
|
151
|
+
const dotIdx = token.indexOf(".");
|
|
152
|
+
if (dotIdx <= 0 || dotIdx === token.length - 1) return null;
|
|
153
|
+
const payloadB64 = token.slice(0, dotIdx);
|
|
154
|
+
const sigBytes = fromBase64Url(token.slice(dotIdx + 1));
|
|
155
|
+
if (!sigBytes) return null;
|
|
156
|
+
const dataBytes = encoder.encode(payloadB64);
|
|
157
|
+
let matched = false;
|
|
158
|
+
for (const secret of secrets) {
|
|
159
|
+
const key = await getHmacKey(secret);
|
|
160
|
+
if (await crypto.subtle.verify("HMAC", key, sigBytes, dataBytes)) {
|
|
161
|
+
matched = true;
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (!matched) return null;
|
|
166
|
+
const payloadBytes = fromBase64Url(payloadB64);
|
|
167
|
+
if (!payloadBytes) return null;
|
|
168
|
+
try {
|
|
169
|
+
const parsed = JSON.parse(decoder.decode(payloadBytes));
|
|
170
|
+
if (parsed.exp !== void 0 && Math.floor(Date.now() / 1e3) > parsed.exp) return null;
|
|
171
|
+
return parsed.d;
|
|
172
|
+
} catch {
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return {
|
|
177
|
+
sign,
|
|
178
|
+
verify,
|
|
179
|
+
async get() {
|
|
180
|
+
const raw = cookieBridge.get(cookieName);
|
|
181
|
+
if (!raw) return null;
|
|
182
|
+
return verify(raw);
|
|
183
|
+
},
|
|
184
|
+
async set(data) {
|
|
185
|
+
const signed = await sign(data);
|
|
186
|
+
const isSecure = config.secure ?? cookieBridge.isHttps?.() ?? false;
|
|
187
|
+
cookieBridge.set(cookieName, signed, {
|
|
188
|
+
path,
|
|
189
|
+
maxAge,
|
|
190
|
+
httpOnly,
|
|
191
|
+
sameSite,
|
|
192
|
+
secure: isSecure
|
|
193
|
+
});
|
|
194
|
+
},
|
|
195
|
+
clear() {
|
|
196
|
+
cookieBridge.delete(cookieName, { path });
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
// src/server.ts
|
|
201
|
+
const requestAls = new AsyncLocalStorage();
|
|
202
|
+
_setServerHeadHook((config) => {
|
|
203
|
+
const store = requestAls.getStore();
|
|
204
|
+
if (!store) return false;
|
|
205
|
+
applyHeadToState(store.headState, config);
|
|
206
|
+
store.onHeadUpdate?.();
|
|
207
|
+
return true;
|
|
208
|
+
});
|
|
209
|
+
_setRequestEnvReader(() => {
|
|
210
|
+
return requestAls.getStore()?.c.env ?? void 0;
|
|
211
|
+
});
|
|
212
|
+
_setDbContextReader(() => {
|
|
213
|
+
const store = requestAls.getStore();
|
|
214
|
+
if (!store) return null;
|
|
215
|
+
return {
|
|
216
|
+
requestKey: store,
|
|
217
|
+
requestEnv: store.c.env ?? void 0
|
|
218
|
+
};
|
|
219
|
+
});
|
|
220
|
+
function requireStore(caller) {
|
|
221
|
+
const store = requestAls.getStore();
|
|
222
|
+
if (!store) throw new Error(`[c7t] \`${caller}\` was accessed outside an active HTTP/SSR request context.`);
|
|
223
|
+
return store;
|
|
224
|
+
}
|
|
225
|
+
function guardPrerenderDynamicAccess(store, apiName) {
|
|
226
|
+
if (store.isPrerender) {
|
|
227
|
+
const pathname = new URL(store.c.req.url, "http://prerender.local").pathname;
|
|
228
|
+
throw new Error(`[c7t SSG] Cannot call \`${apiName}\` while prerendering static route "${pathname}". Keep dynamic cookie/session access inside non-prerendered routes or RPC handlers.`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
function runWithRequestContext(c, fn, signal, onHeadUpdate) {
|
|
232
|
+
const existing = requestAls.getStore();
|
|
233
|
+
const isPrerender = existing?.isPrerender ?? c.req.header("x-c7t-prerender") === "1";
|
|
234
|
+
const store = {
|
|
235
|
+
c,
|
|
236
|
+
signal: signal ?? existing?.signal ?? c.req.raw.signal,
|
|
237
|
+
isPrerender,
|
|
238
|
+
headState: existing?.headState ?? { meta: /* @__PURE__ */ new Map() },
|
|
239
|
+
onHeadUpdate: onHeadUpdate ?? existing?.onHeadUpdate
|
|
240
|
+
};
|
|
241
|
+
return requestAls.run(store, fn);
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Ambient typed request proxy backed by `AsyncLocalStorage`.
|
|
245
|
+
* Exposes `req.url`, `req.headers`, `req.method`, `req.env`, `req.c`, and any
|
|
246
|
+
* middleware variables set via `c.set('user', ...)` directly as `req.user`!
|
|
247
|
+
*/
|
|
248
|
+
const req = new Proxy({}, {
|
|
249
|
+
get(_target, prop) {
|
|
250
|
+
if (typeof prop === "symbol") return void 0;
|
|
251
|
+
const { c, signal } = requireStore(`req.${prop}`);
|
|
252
|
+
switch (prop) {
|
|
253
|
+
case "c": return c;
|
|
254
|
+
case "raw": return c.req.raw;
|
|
255
|
+
case "url": return c.req.url;
|
|
256
|
+
case "method": return c.req.method;
|
|
257
|
+
case "headers": return c.req.raw.headers;
|
|
258
|
+
case "env": return c.env ?? {};
|
|
259
|
+
case "signal": return signal;
|
|
260
|
+
default: return c.get(prop);
|
|
261
|
+
}
|
|
262
|
+
},
|
|
263
|
+
set(_target, prop, value) {
|
|
264
|
+
if (typeof prop === "symbol") return false;
|
|
265
|
+
const { c } = requireStore(`req.${prop}`);
|
|
266
|
+
c.set(prop, value);
|
|
267
|
+
return true;
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
const cookies = {
|
|
271
|
+
get(name) {
|
|
272
|
+
const store = requireStore("cookies.get");
|
|
273
|
+
guardPrerenderDynamicAccess(store, "cookies.get");
|
|
274
|
+
return getCookie(store.c, name);
|
|
275
|
+
},
|
|
276
|
+
set(name, value, options) {
|
|
277
|
+
const store = requireStore("cookies.set");
|
|
278
|
+
guardPrerenderDynamicAccess(store, "cookies.set");
|
|
279
|
+
setCookie(store.c, name, value, {
|
|
280
|
+
path: "/",
|
|
281
|
+
...options
|
|
282
|
+
});
|
|
283
|
+
},
|
|
284
|
+
delete(name, options) {
|
|
285
|
+
const store = requireStore("cookies.delete");
|
|
286
|
+
guardPrerenderDynamicAccess(store, "cookies.delete");
|
|
287
|
+
deleteCookie(store.c, name, {
|
|
288
|
+
path: "/",
|
|
289
|
+
...options
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
/**
|
|
294
|
+
* Create a Web-Crypto (`HMAC-SHA256`) signed cookie session manager backed automatically
|
|
295
|
+
* by `c7t`'s request-scoped `cookies` store. Supports zero-downtime key rotation via `secret: [current, old]`.
|
|
296
|
+
*/
|
|
297
|
+
function createSession(config) {
|
|
298
|
+
return createSessionWithCookies(config, {
|
|
299
|
+
get: (name) => cookies.get(name),
|
|
300
|
+
set: (name, val, opts) => cookies.set(name, val, opts),
|
|
301
|
+
delete: (name, opts) => cookies.delete(name, opts),
|
|
302
|
+
isHttps: () => {
|
|
303
|
+
const store = requestAls.getStore();
|
|
304
|
+
return Boolean(store && store.c.req.url.startsWith("https://"));
|
|
305
|
+
}
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
const rpcRegistry = /* @__PURE__ */ new Map();
|
|
309
|
+
function getRegisteredRpc(id) {
|
|
310
|
+
return rpcRegistry.get(id);
|
|
311
|
+
}
|
|
312
|
+
function clearRegisteredRpcs() {
|
|
313
|
+
rpcRegistry.clear();
|
|
314
|
+
}
|
|
315
|
+
function isAsyncGeneratorFn(fn) {
|
|
316
|
+
return fn?.constructor?.name === "AsyncGeneratorFunction";
|
|
317
|
+
}
|
|
318
|
+
function isAsyncIterable(val) {
|
|
319
|
+
return Boolean(val && typeof val === "object" && Symbol.asyncIterator in val && typeof val[Symbol.asyncIterator] === "function");
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Register a server function or `async function*` stream under a canonical ID
|
|
323
|
+
* (invoked automatically by `@fierst/c7t/vite` on server builds, or manually in tests).
|
|
324
|
+
*/
|
|
325
|
+
function registerServerFn(id, schemaOrFn, maybeFn) {
|
|
326
|
+
const hasSchema = isStandardSchema(schemaOrFn);
|
|
327
|
+
const schema = hasSchema ? schemaOrFn : void 0;
|
|
328
|
+
const rawFn = hasSchema ? maybeFn : schemaOrFn;
|
|
329
|
+
if (typeof rawFn !== "function") throw new TypeError(`[c7t] Invalid server handler registered for "${id}".`);
|
|
330
|
+
const streamMode = isAsyncGeneratorFn(rawFn);
|
|
331
|
+
rpcRegistry.set(id, {
|
|
332
|
+
id,
|
|
333
|
+
isStream: streamMode,
|
|
334
|
+
schema,
|
|
335
|
+
handler: rawFn
|
|
336
|
+
});
|
|
337
|
+
if (streamMode) return async function* (...args) {
|
|
338
|
+
const finalArgs = schema ? [await validateSchema(schema, args[0])] : args;
|
|
339
|
+
return yield* rawFn(...finalArgs);
|
|
340
|
+
};
|
|
341
|
+
return (...args) => createServerCall(id, args, async () => {
|
|
342
|
+
const finalArgs = schema ? [await validateSchema(schema, args[0])] : args;
|
|
343
|
+
return rawFn(...finalArgs);
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
function verifySameOriginCsrf(c) {
|
|
347
|
+
if (c.req.header("sec-fetch-site") === "cross-site") return c.json({
|
|
348
|
+
ok: false,
|
|
349
|
+
error: {
|
|
350
|
+
name: "ForbiddenError",
|
|
351
|
+
message: "Cross-site RPC request blocked",
|
|
352
|
+
status: 403
|
|
353
|
+
}
|
|
354
|
+
}, 403);
|
|
355
|
+
const origin = c.req.header("origin");
|
|
356
|
+
if (origin && origin !== "null") {
|
|
357
|
+
const reqOrigin = new URL(c.req.url).origin;
|
|
358
|
+
if (origin !== reqOrigin) return c.json({
|
|
359
|
+
ok: false,
|
|
360
|
+
error: {
|
|
361
|
+
name: "ForbiddenError",
|
|
362
|
+
message: `CSRF Origin mismatch: expected ${reqOrigin}, got ${origin}`,
|
|
363
|
+
status: 403
|
|
364
|
+
}
|
|
365
|
+
}, 403);
|
|
366
|
+
} else if (origin === "null") return c.json({
|
|
367
|
+
ok: false,
|
|
368
|
+
error: {
|
|
369
|
+
name: "ForbiddenError",
|
|
370
|
+
message: "Null Origin RPC blocked",
|
|
371
|
+
status: 403
|
|
372
|
+
}
|
|
373
|
+
}, 403);
|
|
374
|
+
return null;
|
|
375
|
+
}
|
|
376
|
+
function isProductionMode() {
|
|
377
|
+
return typeof process !== "undefined" && process.env?.NODE_ENV === "production";
|
|
378
|
+
}
|
|
379
|
+
function serializeErrorToEnvelope(err) {
|
|
380
|
+
if (err instanceof RedirectSignal) return {
|
|
381
|
+
status: 200,
|
|
382
|
+
body: {
|
|
383
|
+
ok: false,
|
|
384
|
+
redirect: {
|
|
385
|
+
location: err.location,
|
|
386
|
+
status: err.status
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
if (err instanceof ValidationError) return {
|
|
391
|
+
status: 400,
|
|
392
|
+
body: {
|
|
393
|
+
ok: false,
|
|
394
|
+
error: {
|
|
395
|
+
name: "ValidationError",
|
|
396
|
+
message: err.message,
|
|
397
|
+
status: 400,
|
|
398
|
+
issues: err.issues
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
if (err instanceof HttpStatusError) return {
|
|
403
|
+
status: err.status,
|
|
404
|
+
body: {
|
|
405
|
+
ok: false,
|
|
406
|
+
error: {
|
|
407
|
+
name: err.name,
|
|
408
|
+
message: err.message,
|
|
409
|
+
status: err.status,
|
|
410
|
+
data: err.data
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
if (isProductionMode()) {
|
|
415
|
+
console.error("[c7t RPC error]", err);
|
|
416
|
+
return {
|
|
417
|
+
status: 500,
|
|
418
|
+
body: {
|
|
419
|
+
ok: false,
|
|
420
|
+
error: {
|
|
421
|
+
name: "InternalServerError",
|
|
422
|
+
message: "Internal Server Error",
|
|
423
|
+
status: 500
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
429
|
+
return {
|
|
430
|
+
status: 500,
|
|
431
|
+
body: {
|
|
432
|
+
ok: false,
|
|
433
|
+
error: {
|
|
434
|
+
name: err instanceof Error ? err.name : "ServerError",
|
|
435
|
+
message,
|
|
436
|
+
status: 500
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
async function handleRpcRequest(c, fnId) {
|
|
442
|
+
const csrfBlocked = verifySameOriginCsrf(c);
|
|
443
|
+
if (csrfBlocked) return csrfBlocked;
|
|
444
|
+
const entry = rpcRegistry.get(fnId);
|
|
445
|
+
if (!entry) return c.json({
|
|
446
|
+
ok: false,
|
|
447
|
+
error: {
|
|
448
|
+
name: "NotFoundError",
|
|
449
|
+
message: `Unknown server RPC "${fnId}"`,
|
|
450
|
+
status: 404
|
|
451
|
+
}
|
|
452
|
+
}, 404);
|
|
453
|
+
let args = [];
|
|
454
|
+
const contentType = c.req.header("content-type") ?? "";
|
|
455
|
+
try {
|
|
456
|
+
if (contentType.includes("multipart/form-data")) {
|
|
457
|
+
const formData = await c.req.formData();
|
|
458
|
+
args = decodeMultipartRpcArgs(formData);
|
|
459
|
+
} else {
|
|
460
|
+
const body = await c.req.json();
|
|
461
|
+
if (Array.isArray(body?.args)) args = body.args;
|
|
462
|
+
}
|
|
463
|
+
} catch {
|
|
464
|
+
return c.json({
|
|
465
|
+
ok: false,
|
|
466
|
+
error: {
|
|
467
|
+
name: "BadRequestError",
|
|
468
|
+
message: "Invalid RPC request body",
|
|
469
|
+
status: 400
|
|
470
|
+
}
|
|
471
|
+
}, 400);
|
|
472
|
+
}
|
|
473
|
+
if (entry.schema) try {
|
|
474
|
+
args = [await validateSchema(entry.schema, args[0])];
|
|
475
|
+
} catch (validationErr) {
|
|
476
|
+
const { status, body } = serializeErrorToEnvelope(validationErr);
|
|
477
|
+
return c.json(body, status);
|
|
478
|
+
}
|
|
479
|
+
if (entry.isStream) {
|
|
480
|
+
const streamAbort = new AbortController();
|
|
481
|
+
const onReqAbort = () => streamAbort.abort();
|
|
482
|
+
if (c.req.raw.signal.aborted) streamAbort.abort();
|
|
483
|
+
else c.req.raw.signal.addEventListener("abort", onReqAbort, { once: true });
|
|
484
|
+
const encoder = new TextEncoder();
|
|
485
|
+
let gen = null;
|
|
486
|
+
let closed = false;
|
|
487
|
+
const cleanupGenerator = async () => {
|
|
488
|
+
if (closed) return;
|
|
489
|
+
closed = true;
|
|
490
|
+
streamAbort.abort();
|
|
491
|
+
c.req.raw.signal.removeEventListener("abort", onReqAbort);
|
|
492
|
+
if (gen && typeof gen.return === "function") try {
|
|
493
|
+
await runWithRequestContext(c, () => gen.return(void 0), streamAbort.signal);
|
|
494
|
+
} catch {}
|
|
495
|
+
};
|
|
496
|
+
const bodyStream = new ReadableStream({
|
|
497
|
+
async start(controller) {
|
|
498
|
+
const sendFrame = (frame) => {
|
|
499
|
+
if (closed || streamAbort.signal.aborted) return;
|
|
500
|
+
controller.enqueue(encoder.encode(JSON.stringify(frame) + "\n"));
|
|
501
|
+
};
|
|
502
|
+
try {
|
|
503
|
+
gen = runWithRequestContext(c, () => entry.handler(...args), streamAbort.signal);
|
|
504
|
+
if (!isAsyncIterable(gen)) {
|
|
505
|
+
sendFrame({
|
|
506
|
+
type: "return",
|
|
507
|
+
value: await Promise.resolve(gen)
|
|
508
|
+
});
|
|
509
|
+
closed = true;
|
|
510
|
+
controller.close();
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
while (!streamAbort.signal.aborted) {
|
|
514
|
+
const step = await runWithRequestContext(c, () => gen.next(), streamAbort.signal);
|
|
515
|
+
if (streamAbort.signal.aborted) break;
|
|
516
|
+
if (step.done) {
|
|
517
|
+
sendFrame({
|
|
518
|
+
type: "return",
|
|
519
|
+
value: step.value
|
|
520
|
+
});
|
|
521
|
+
break;
|
|
522
|
+
}
|
|
523
|
+
sendFrame({
|
|
524
|
+
type: "yield",
|
|
525
|
+
value: step.value
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
if (!closed && !streamAbort.signal.aborted) {
|
|
529
|
+
closed = true;
|
|
530
|
+
c.req.raw.signal.removeEventListener("abort", onReqAbort);
|
|
531
|
+
controller.close();
|
|
532
|
+
}
|
|
533
|
+
} catch (err) {
|
|
534
|
+
if (!closed && !streamAbort.signal.aborted) {
|
|
535
|
+
if (err instanceof RedirectSignal) sendFrame({
|
|
536
|
+
type: "error",
|
|
537
|
+
name: "RedirectSignal",
|
|
538
|
+
message: err.message,
|
|
539
|
+
redirect: {
|
|
540
|
+
location: err.location,
|
|
541
|
+
status: err.status
|
|
542
|
+
}
|
|
543
|
+
});
|
|
544
|
+
else if (err instanceof ValidationError) sendFrame({
|
|
545
|
+
type: "error",
|
|
546
|
+
name: "ValidationError",
|
|
547
|
+
message: err.message,
|
|
548
|
+
status: 400,
|
|
549
|
+
issues: err.issues
|
|
550
|
+
});
|
|
551
|
+
else if (err instanceof HttpStatusError) sendFrame({
|
|
552
|
+
type: "error",
|
|
553
|
+
name: err.name,
|
|
554
|
+
message: err.message,
|
|
555
|
+
status: err.status
|
|
556
|
+
});
|
|
557
|
+
else if (isProductionMode()) {
|
|
558
|
+
console.error("[c7t stream error]", err);
|
|
559
|
+
sendFrame({
|
|
560
|
+
type: "error",
|
|
561
|
+
name: "InternalServerError",
|
|
562
|
+
message: "Internal Server Error",
|
|
563
|
+
status: 500
|
|
564
|
+
});
|
|
565
|
+
} else sendFrame({
|
|
566
|
+
type: "error",
|
|
567
|
+
name: err instanceof Error ? err.name : "StreamError",
|
|
568
|
+
message: err instanceof Error ? err.message : String(err),
|
|
569
|
+
status: 500
|
|
570
|
+
});
|
|
571
|
+
closed = true;
|
|
572
|
+
c.req.raw.signal.removeEventListener("abort", onReqAbort);
|
|
573
|
+
controller.close();
|
|
574
|
+
}
|
|
575
|
+
} finally {
|
|
576
|
+
await cleanupGenerator();
|
|
577
|
+
}
|
|
578
|
+
},
|
|
579
|
+
async cancel() {
|
|
580
|
+
await cleanupGenerator();
|
|
581
|
+
}
|
|
582
|
+
});
|
|
583
|
+
return new Response(bodyStream, {
|
|
584
|
+
status: 200,
|
|
585
|
+
headers: {
|
|
586
|
+
"Content-Type": "application/x-ndjson; charset=utf-8",
|
|
587
|
+
"Cache-Control": "no-store",
|
|
588
|
+
"X-Content-Type-Options": "nosniff"
|
|
589
|
+
}
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
try {
|
|
593
|
+
const value = await runWithRequestContext(c, () => entry.handler(...args));
|
|
594
|
+
if (value instanceof RedirectSignal || value instanceof HttpStatusError) {
|
|
595
|
+
const { status, body } = serializeErrorToEnvelope(value);
|
|
596
|
+
return c.json(body, status);
|
|
597
|
+
}
|
|
598
|
+
return c.json({
|
|
599
|
+
ok: true,
|
|
600
|
+
value
|
|
601
|
+
}, 200);
|
|
602
|
+
} catch (err) {
|
|
603
|
+
const { status, body } = serializeErrorToEnvelope(err);
|
|
604
|
+
return c.json(body, status);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
function isCompiledRouteArray(routes) {
|
|
608
|
+
return routes.length === 0 || "regex" in routes[0];
|
|
609
|
+
}
|
|
610
|
+
const DEFAULT_DEV_MANIFEST = {
|
|
611
|
+
"@fierst/blokd": "/@id/@fierst/blokd",
|
|
612
|
+
"@fierst/blokd/revive": "/@id/@fierst/blokd/revive",
|
|
613
|
+
"@fierst/c7t": "/@id/@fierst/c7t",
|
|
614
|
+
"@fierst/c7t/client": "/@id/@fierst/c7t/client",
|
|
615
|
+
"@fierst/c7t/router": "/@id/@fierst/c7t/router"
|
|
616
|
+
};
|
|
617
|
+
const API_SENTINEL = "x-c7t-api-miss";
|
|
618
|
+
function buildHonoApiSubApp(apiRoutes) {
|
|
619
|
+
if (apiRoutes.length === 0) return null;
|
|
620
|
+
const sub = new Hono();
|
|
621
|
+
for (const apiRoute of apiRoutes) for (const [method, handler] of Object.entries(apiRoute.handlers)) {
|
|
622
|
+
if (typeof handler !== "function") continue;
|
|
623
|
+
sub.on(method, apiRoute.honoPath, (c) => handler(c));
|
|
624
|
+
}
|
|
625
|
+
sub.notFound((c) => c.text("", 404, { [API_SENTINEL]: "1" }));
|
|
626
|
+
return sub;
|
|
627
|
+
}
|
|
628
|
+
let defaultRegisteredRoutes = null;
|
|
629
|
+
let defaultRegisteredApiApp = null;
|
|
630
|
+
let defaultSpecialRoutes = null;
|
|
631
|
+
let defaultClientRevivalUrl = null;
|
|
632
|
+
let defaultIslandsRevivalUrl = null;
|
|
633
|
+
let defaultProdManifest = null;
|
|
634
|
+
let defaultProdStyles = [];
|
|
635
|
+
let defaultRouteDefaults = {};
|
|
636
|
+
/** @internal Auto-populated by `@fierst/c7t/vite` from `virtual:c7t/routes` when `routes` is omitted in `createServer()`. */
|
|
637
|
+
function _setDefaultRoutes(routes, clientRevivalUrl, prodManifest, prodStyles, routeDefaults, islandsRevivalUrl) {
|
|
638
|
+
if (routeDefaults !== void 0) defaultRouteDefaults = routeDefaults ?? {};
|
|
639
|
+
if (!routes) {
|
|
640
|
+
defaultRegisteredRoutes = null;
|
|
641
|
+
defaultRegisteredApiApp = null;
|
|
642
|
+
defaultSpecialRoutes = null;
|
|
643
|
+
} else if (isCompiledRouteArray(routes)) {
|
|
644
|
+
defaultRegisteredRoutes = routes;
|
|
645
|
+
defaultRegisteredApiApp = null;
|
|
646
|
+
defaultSpecialRoutes = null;
|
|
647
|
+
} else {
|
|
648
|
+
defaultRegisteredRoutes = buildRoutes(routes, defaultRouteDefaults);
|
|
649
|
+
defaultRegisteredApiApp = buildHonoApiSubApp(buildApiRoutes(routes));
|
|
650
|
+
defaultSpecialRoutes = extractSpecialRoutes(routes);
|
|
651
|
+
}
|
|
652
|
+
if (clientRevivalUrl !== void 0) defaultClientRevivalUrl = clientRevivalUrl;
|
|
653
|
+
if (islandsRevivalUrl !== void 0) defaultIslandsRevivalUrl = islandsRevivalUrl;
|
|
654
|
+
if (prodManifest !== void 0) defaultProdManifest = prodManifest;
|
|
655
|
+
if (prodStyles !== void 0) defaultProdStyles = prodStyles ?? [];
|
|
656
|
+
}
|
|
657
|
+
function escapeTitleHtml(str) {
|
|
658
|
+
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
659
|
+
}
|
|
660
|
+
function renderStylesheetLinks(styles) {
|
|
661
|
+
if (styles.length === 0) return "";
|
|
662
|
+
const seen = /* @__PURE__ */ new Set();
|
|
663
|
+
let out = "";
|
|
664
|
+
for (const href of styles) {
|
|
665
|
+
if (!href || seen.has(href)) continue;
|
|
666
|
+
seen.add(href);
|
|
667
|
+
out += `<link rel="stylesheet" href="${escapeTitleHtml(href)}" />`;
|
|
668
|
+
}
|
|
669
|
+
return out;
|
|
670
|
+
}
|
|
671
|
+
function createServer(options = {}) {
|
|
672
|
+
const app = new Hono();
|
|
673
|
+
const rpcBase = (options.rpcBase ?? "/_c7t/rpc").replace(/\/$/, "");
|
|
674
|
+
const ssrMode = options.ssrMode ?? "stream";
|
|
675
|
+
const mergedDefaults = {
|
|
676
|
+
prerender: options.prerender ?? defaultRouteDefaults.prerender,
|
|
677
|
+
csr: options.csr ?? defaultRouteDefaults.csr
|
|
678
|
+
};
|
|
679
|
+
const explicitRoutes = options.routes ? isCompiledRouteArray(options.routes) ? options.routes : buildRoutes(options.routes, mergedDefaults) : null;
|
|
680
|
+
const explicitApiApp = options.routes && !isCompiledRouteArray(options.routes) ? buildHonoApiSubApp(buildApiRoutes(options.routes)) : null;
|
|
681
|
+
const explicitSpecialRoutes = options.routes && !isCompiledRouteArray(options.routes) ? extractSpecialRoutes(options.routes) : null;
|
|
682
|
+
app.use("*", (c, next) => runWithRequestContext(c, () => next()));
|
|
683
|
+
if (options.middleware) {
|
|
684
|
+
const list = Array.isArray(options.middleware) ? options.middleware : [options.middleware];
|
|
685
|
+
for (const mw of list) app.use("*", mw);
|
|
686
|
+
}
|
|
687
|
+
app.post(`${rpcBase}/:fnId`, (c) => {
|
|
688
|
+
return handleRpcRequest(c, decodeURIComponent(c.req.param("fnId")));
|
|
689
|
+
});
|
|
690
|
+
options.configure?.(app);
|
|
691
|
+
app.all("*", async (c, next) => {
|
|
692
|
+
const apiApp = explicitRoutes !== null ? explicitApiApp : defaultRegisteredApiApp;
|
|
693
|
+
if (!apiApp) return next();
|
|
694
|
+
const res = await runWithRequestContext(c, () => apiApp.fetch(c.req.raw, c.env));
|
|
695
|
+
if (res.headers.get(API_SENTINEL) === "1") return next();
|
|
696
|
+
if (c.res) {
|
|
697
|
+
const mergedHeaders = new Headers(res.headers);
|
|
698
|
+
c.res.headers.forEach((val, key) => {
|
|
699
|
+
if (key.toLowerCase() === "set-cookie") return;
|
|
700
|
+
if (!mergedHeaders.has(key)) mergedHeaders.set(key, val);
|
|
701
|
+
});
|
|
702
|
+
const setCookies = typeof c.res.headers.getSetCookie === "function" ? c.res.headers.getSetCookie() : [];
|
|
703
|
+
for (const sc of setCookies) mergedHeaders.append("Set-Cookie", sc);
|
|
704
|
+
return new Response(res.body, {
|
|
705
|
+
status: res.status,
|
|
706
|
+
statusText: res.statusText,
|
|
707
|
+
headers: mergedHeaders
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
return res;
|
|
711
|
+
});
|
|
712
|
+
app.get("*", async (c) => {
|
|
713
|
+
const compiledRoutes = explicitRoutes ?? defaultRegisteredRoutes ?? [];
|
|
714
|
+
const specialRoutes = explicitRoutes !== null ? explicitSpecialRoutes : defaultSpecialRoutes;
|
|
715
|
+
const notFoundComp = options.notFoundComponent ?? specialRoutes?.notFound;
|
|
716
|
+
const errorComp = options.errorComponent ?? specialRoutes?.error;
|
|
717
|
+
let devStyles = [];
|
|
718
|
+
if (!isProductionMode()) {
|
|
719
|
+
const devStyleHeader = c.req.header("x-c7t-dev-styles");
|
|
720
|
+
if (devStyleHeader) try {
|
|
721
|
+
const parsedStyles = JSON.parse(devStyleHeader);
|
|
722
|
+
if (Array.isArray(parsedStyles)) devStyles = parsedStyles;
|
|
723
|
+
} catch {}
|
|
724
|
+
}
|
|
725
|
+
const baseHead = renderStylesheetLinks([...options.styles ?? defaultProdStyles, ...devStyles]) + (options.document?.head ?? "");
|
|
726
|
+
const renderCustom404 = async () => {
|
|
727
|
+
const parsed = new URL(c.req.url, "http://c7t.local");
|
|
728
|
+
const leaf = _comp(notFoundComp, { pathname: parsed.pathname });
|
|
729
|
+
const view404 = !options.notFoundComponent && specialRoutes?.rootLayout ? _comp(specialRoutes.rootLayout, {
|
|
730
|
+
pathname: parsed.pathname,
|
|
731
|
+
params: {},
|
|
732
|
+
search: parsed.searchParams,
|
|
733
|
+
children: _comp(Outlet, {
|
|
734
|
+
depth: 0,
|
|
735
|
+
children: leaf
|
|
736
|
+
})
|
|
737
|
+
}) : leaf;
|
|
738
|
+
let customTitle = options.document?.title ?? "404 — Not Found";
|
|
739
|
+
let renderedMeta = "";
|
|
740
|
+
const sync404Head = () => {
|
|
741
|
+
const store = requestAls.getStore();
|
|
742
|
+
if (!store) return;
|
|
743
|
+
if (store.headState.title !== void 0) customTitle = store.headState.title;
|
|
744
|
+
renderedMeta = renderCollectedHeadTags(store.headState);
|
|
745
|
+
};
|
|
746
|
+
const bodyHtml = await runWithRequestContext(c, () => renderToStringAsync(view404, { revive: false }), void 0, sync404Head);
|
|
747
|
+
sync404Head();
|
|
748
|
+
const doc404 = `<!doctype html><html lang="${options.document?.lang ?? "en"}"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>${escapeTitleHtml(customTitle)}</title>${baseHead}${renderedMeta}</head><body><div id="app">${bodyHtml}</div></body></html>`;
|
|
749
|
+
return c.html(doc404, 404);
|
|
750
|
+
};
|
|
751
|
+
if (compiledRoutes.length === 0 && !notFoundComp) return c.text("Not Found", 404);
|
|
752
|
+
const match = matchNestedRoutes(compiledRoutes, c.req.url);
|
|
753
|
+
if (!match) {
|
|
754
|
+
if (notFoundComp) return renderCustom404();
|
|
755
|
+
return c.text("Not Found", 404);
|
|
756
|
+
}
|
|
757
|
+
const receipts = createReceiptCollector();
|
|
758
|
+
const devManifest = {
|
|
759
|
+
...DEFAULT_DEV_MANIFEST,
|
|
760
|
+
...defaultClientRevivalUrl ? { "@fierst/c7t/client-entry": defaultClientRevivalUrl } : {},
|
|
761
|
+
...defaultIslandsRevivalUrl ? { "@fierst/c7t/islands-entry": defaultIslandsRevivalUrl } : {}
|
|
762
|
+
};
|
|
763
|
+
const activeManifest = options.manifest ?? options.document?.manifest ?? defaultProdManifest ?? devManifest;
|
|
764
|
+
const extraClientScript = match.csr !== false && options.document?.clientEntryUrl ? `<script type="module" src="${options.document.clientEntryUrl}"><\/script>` : "";
|
|
765
|
+
const resolvedRevive = match.csr === false ? false : options.document?.revive !== void 0 ? options.document.revive : match.csr === true || Boolean(options.document?.clientEntryUrl) ? true : "auto";
|
|
766
|
+
const preferredLoaderKey = match.csr === "islands" ? "@fierst/c7t/islands-entry" : "@fierst/c7t/client-entry";
|
|
767
|
+
const resolvedRevivalUrl = options.document?.revivalUrl ?? (preferredLoaderKey in activeManifest ? resolveIslandSrc(preferredLoaderKey, activeManifest, options.document?.base) : resolveIslandSrc("@fierst/blokd/revive", activeManifest, options.document?.base));
|
|
768
|
+
const docOpts = {
|
|
769
|
+
...options.document,
|
|
770
|
+
revive: resolvedRevive,
|
|
771
|
+
revivalUrl: resolvedRevivalUrl,
|
|
772
|
+
head: baseHead + extraClientScript,
|
|
773
|
+
manifest: activeManifest,
|
|
774
|
+
receipts
|
|
775
|
+
};
|
|
776
|
+
const syncCollectedHead = () => {
|
|
777
|
+
const store = requestAls.getStore();
|
|
778
|
+
if (!store) return;
|
|
779
|
+
if (store.headState.title !== void 0) docOpts.title = store.headState.title;
|
|
780
|
+
const renderedMeta = renderCollectedHeadTags(store.headState);
|
|
781
|
+
docOpts.head = baseHead + renderedMeta + extraClientScript;
|
|
782
|
+
};
|
|
783
|
+
const rootView = buildMatchedRouteView(match, 0, errorComp);
|
|
784
|
+
if (ssrMode === "string") try {
|
|
785
|
+
const bodyHtml = await runWithRequestContext(c, () => renderToStringAsync(rootView, {
|
|
786
|
+
revive: docOpts.revive !== false,
|
|
787
|
+
manifest: docOpts.manifest,
|
|
788
|
+
base: docOpts.base,
|
|
789
|
+
receipts
|
|
790
|
+
}), void 0, syncCollectedHead);
|
|
791
|
+
syncCollectedHead();
|
|
792
|
+
const receiptScript = receipts.emitInitialScript?.(docOpts.nonce) ?? "";
|
|
793
|
+
const shouldEmitLoader = docOpts.revive === true || docOpts.revive === "auto" && bodyHtml.includes("<blokd-island");
|
|
794
|
+
let loaderScript = "";
|
|
795
|
+
if (shouldEmitLoader) {
|
|
796
|
+
const runtimeTarget = docOpts.runtimeUrl ?? resolveIslandSrc("@fierst/blokd", activeManifest, docOpts.base);
|
|
797
|
+
loaderScript = `<script type="module"${docOpts.nonce ? ` nonce="${escapeTitleHtml(docOpts.nonce)}"` : ""}>import{installRevival}from${JSON.stringify(resolvedRevivalUrl).replace(/</g, "\\u003c")};installRevival(${JSON.stringify(runtimeTarget).replace(/</g, "\\u003c")});<\/script>`;
|
|
798
|
+
}
|
|
799
|
+
const title = escapeTitleHtml(docOpts.title ?? "c7t");
|
|
800
|
+
const fullHtml = `<!doctype html><html lang="${docOpts.lang ?? "en"}"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>${title}</title>${docOpts.head ?? ""}</head><body><div id="app">${bodyHtml}</div>${receiptScript}${loaderScript}</body></html>`;
|
|
801
|
+
return c.html(fullHtml, 200);
|
|
802
|
+
} catch (err) {
|
|
803
|
+
if (err instanceof RedirectSignal) return c.redirect(err.location, err.status);
|
|
804
|
+
if (err instanceof HttpStatusError) {
|
|
805
|
+
if (err.status === 404 && notFoundComp) return renderCustom404();
|
|
806
|
+
return c.text(err.message, err.status);
|
|
807
|
+
}
|
|
808
|
+
throw err;
|
|
809
|
+
}
|
|
810
|
+
try {
|
|
811
|
+
const reader = runWithRequestContext(c, () => renderToStream(rootView, docOpts), void 0, syncCollectedHead).getReader();
|
|
812
|
+
const firstChunk = await reader.read();
|
|
813
|
+
const passthrough = new ReadableStream({
|
|
814
|
+
async start(controller) {
|
|
815
|
+
if (!firstChunk.done && firstChunk.value) controller.enqueue(firstChunk.value);
|
|
816
|
+
if (firstChunk.done) {
|
|
817
|
+
controller.close();
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
try {
|
|
821
|
+
while (true) {
|
|
822
|
+
const next = await reader.read();
|
|
823
|
+
if (next.done) {
|
|
824
|
+
controller.close();
|
|
825
|
+
break;
|
|
826
|
+
}
|
|
827
|
+
if (next.value) controller.enqueue(next.value);
|
|
828
|
+
}
|
|
829
|
+
} catch (streamErr) {
|
|
830
|
+
controller.error(streamErr);
|
|
831
|
+
}
|
|
832
|
+
},
|
|
833
|
+
cancel() {
|
|
834
|
+
reader.cancel();
|
|
835
|
+
}
|
|
836
|
+
});
|
|
837
|
+
c.header("Content-Type", "text/html; charset=utf-8");
|
|
838
|
+
return c.body(passthrough, 200);
|
|
839
|
+
} catch (err) {
|
|
840
|
+
if (err instanceof RedirectSignal) return c.redirect(err.location, err.status);
|
|
841
|
+
if (err instanceof HttpStatusError) {
|
|
842
|
+
if (err.status === 404 && notFoundComp) return renderCustom404();
|
|
843
|
+
return c.text(err.message, err.status);
|
|
844
|
+
}
|
|
845
|
+
throw err;
|
|
846
|
+
}
|
|
847
|
+
});
|
|
848
|
+
return app;
|
|
849
|
+
}
|
|
850
|
+
export { _setDefaultRoutes, clearRegisteredRpcs, cookies, createServer, createSession, defineDb, getRegisteredRpc, registerServerFn, req, runWithRequestContext };
|