@clarity-js/ssr 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/README.md +122 -2
- package/express.js +10 -0
- package/fastify.js +24 -0
- package/handler.js +137 -0
- package/index.d.ts +96 -0
- package/index.js +15 -0
- package/node.d.ts +15 -0
- package/node.js +138 -0
- package/package.json +23 -4
- package/render.js +184 -0
package/README.md
CHANGED
|
@@ -1,3 +1,123 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @clarity-js/ssr
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A server for [Clarity.js](https://clarity-js.com) apps, on the core's `renderToString`. One handler in the Web
|
|
4
|
+
standard — `(Request) => Promise<Response>` — that:
|
|
5
|
+
|
|
6
|
+
- renders pages with everything they ask the server for: a route's `loader`, `useServerData()` fetches,
|
|
7
|
+
`useHead()` tags, the router's path, and the state the client hydrates from;
|
|
8
|
+
- answers API routes (`GET`, `POST`, … exported from a route module) and server actions;
|
|
9
|
+
- redirects, refuses or 404s when a loader says so (`throw redirect('/login')`);
|
|
10
|
+
- streams when you ask: the head's fixed part leaves at once, the page follows when its data is ready;
|
|
11
|
+
- runs as is on Bun, Deno, Cloudflare Workers, Vercel/Netlify edge and Hono, and on Node, Express and Fastify
|
|
12
|
+
through small adapters;
|
|
13
|
+
- prerenders pages to files with the same code, so a static page is exactly the page the server sends.
|
|
14
|
+
|
|
15
|
+
No dependencies.
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npm install @clarity-js/ssr
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Routes
|
|
22
|
+
|
|
23
|
+
A route module may export a page component (`default`), a `loader`, `head` tags, and HTTP handlers. A module
|
|
24
|
+
with handlers and no component is an API route.
|
|
25
|
+
|
|
26
|
+
```js
|
|
27
|
+
// pages/blog/[slug].js
|
|
28
|
+
import { notFound, redirect } from '@clarity-js/ssr'
|
|
29
|
+
export { default } from './Post.clarity'
|
|
30
|
+
|
|
31
|
+
export async function loader(ctx) { // ctx: params, query, cookies, request, locals, setStatus, setHeader
|
|
32
|
+
if (ctx.params.slug === 'old') throw redirect('/blog/new', 301)
|
|
33
|
+
const post = await ctx.locals.db.posts.find(ctx.params.slug)
|
|
34
|
+
if (!post) throw notFound()
|
|
35
|
+
ctx.setHeader('cache-control', 'max-age=60')
|
|
36
|
+
return post // the page gets it as `data`
|
|
37
|
+
}
|
|
38
|
+
export const head = ({ data }) => ({ title: data.title, meta: [{ name: 'description', content: data.summary }] })
|
|
39
|
+
|
|
40
|
+
export async function POST(request, ctx) { // a form posted to the page
|
|
41
|
+
await ctx.locals.db.comments.add(ctx.params.slug, await request.formData())
|
|
42
|
+
throw redirect(ctx.url, 303)
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
```js
|
|
47
|
+
// pages/api/posts.js — JSON in, JSON out
|
|
48
|
+
export const GET = (request, ctx) => ctx.locals.db.posts.list({ page: Number(ctx.query.page ?? 1) })
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## The handler
|
|
52
|
+
|
|
53
|
+
```js
|
|
54
|
+
import { createHandler } from '@clarity-js/ssr'
|
|
55
|
+
import { routes } from 'virtual:clarity-pages' // the Vite plugin's route table, or scanRoutes(), or your own
|
|
56
|
+
import NotFound from './NotFound.clarity'
|
|
57
|
+
import ErrorPage from './Error.clarity'
|
|
58
|
+
import * as actions from './actions.js'
|
|
59
|
+
|
|
60
|
+
export const handler = createHandler({
|
|
61
|
+
routes,
|
|
62
|
+
notFound: NotFound, // ({ path })
|
|
63
|
+
error: ErrorPage, // ({ error }) — the error's text only outside production
|
|
64
|
+
actions, // defineServerAction() exports, at POST /_clarity/actions/:name
|
|
65
|
+
locals: async (request) => ({ db, user: await session(request) }),
|
|
66
|
+
stream: false,
|
|
67
|
+
document: {
|
|
68
|
+
title: 'Shop', titleTemplate: '%s · Shop', lang: 'en',
|
|
69
|
+
stylesheets: ['/assets/app.css'], clientScript: '/assets/app.js',
|
|
70
|
+
nonce: (request) => crypto.randomUUID(), // for a Content-Security-Policy
|
|
71
|
+
},
|
|
72
|
+
})
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
An app that routes itself with `<Router>`/`<Route>` passes `app: App` instead of `routes`; the router sees the
|
|
76
|
+
request's path.
|
|
77
|
+
|
|
78
|
+
## Where it runs
|
|
79
|
+
|
|
80
|
+
```js
|
|
81
|
+
// Bun, Deno, Cloudflare Workers, Hono
|
|
82
|
+
export default { fetch: handler }
|
|
83
|
+
Deno.serve(handler)
|
|
84
|
+
app.all('*', (c) => handler(c.req.raw)) // Hono
|
|
85
|
+
|
|
86
|
+
// Node
|
|
87
|
+
import { serve, toNodeHandler } from '@clarity-js/ssr/node'
|
|
88
|
+
serve(handler, { port: 3000 })
|
|
89
|
+
http.createServer(toNodeHandler(handler))
|
|
90
|
+
|
|
91
|
+
// Express — paths the app does not know go on to the next middleware
|
|
92
|
+
import clarity from '@clarity-js/ssr/express'
|
|
93
|
+
app.use(express.static('dist/client'))
|
|
94
|
+
app.use(clarity({ routes, document: { clientScript: '/assets/app.js' } }))
|
|
95
|
+
|
|
96
|
+
// Fastify — a catch-all route next to yours
|
|
97
|
+
import clarity from '@clarity-js/ssr/fastify'
|
|
98
|
+
await app.register(clarity, { routes })
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Prerender
|
|
102
|
+
|
|
103
|
+
```js
|
|
104
|
+
import { scanRoutes, prerender, staticPaths } from '@clarity-js/ssr/node'
|
|
105
|
+
const routes = await scanRoutes('dist/server/pages')
|
|
106
|
+
const handler = createHandler({ routes, document: { clientScript: '/assets/app.js' } })
|
|
107
|
+
const { written, failed } = await prerender({ handler, paths: [...staticPaths(routes), '/blog/hello'], outDir: 'dist/client' })
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`/` becomes `index.html`, `/about` becomes `about/index.html`, `/feed.xml` stays `feed.xml`.
|
|
111
|
+
|
|
112
|
+
## Lower level
|
|
113
|
+
|
|
114
|
+
`renderPage({ component, props, url, ctx, ...document })` gives `{ status, headers, html, state }`;
|
|
115
|
+
`streamPage(...)` gives `{ status, headers, body }` with a `ReadableStream`. Concurrent requests never see each
|
|
116
|
+
other's head tags or data: each render pass reads its head in the same synchronous step.
|
|
117
|
+
|
|
118
|
+
Streaming has one trade-off: once the start of the document has left, the status is sent. A redirect thrown
|
|
119
|
+
later becomes a meta refresh and `location.replace()`, and an error becomes an error body.
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
MIT
|
package/express.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Express (and Connect): app.use(clarity({ routes, document: { clientScript: '/assets/app.js' } }))
|
|
2
|
+
// Paths the app does not know go on to the next middleware; a parsed req.body is passed on to API routes.
|
|
3
|
+
import { createHandler } from './handler.js'
|
|
4
|
+
import { toNodeHandler } from './node.js'
|
|
5
|
+
|
|
6
|
+
export function createExpressMiddleware(options = {}) {
|
|
7
|
+
const { trustProxy = false, ...rest } = options
|
|
8
|
+
return toNodeHandler(createHandler({ passthrough: true, ...rest }), { trustProxy })
|
|
9
|
+
}
|
|
10
|
+
export default createExpressMiddleware
|
package/fastify.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Fastify: await app.register(clarity, { routes, document: { … } })
|
|
2
|
+
// Registers a catch-all route; anything Fastify already routes is not touched.
|
|
3
|
+
import { createHandler } from './handler.js'
|
|
4
|
+
import { toRequest, sendResponse } from './node.js'
|
|
5
|
+
|
|
6
|
+
export async function clarityFastify(fastify, options = {}) {
|
|
7
|
+
const { trustProxy = false, prefix: _prefix, ...rest } = options
|
|
8
|
+
const handler = createHandler(rest)
|
|
9
|
+
fastify.route({
|
|
10
|
+
method: ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
|
|
11
|
+
url: '/*',
|
|
12
|
+
async handler(request, reply) {
|
|
13
|
+
const req = request.raw
|
|
14
|
+
if (request.body !== undefined) req.body = request.body
|
|
15
|
+
const response = await handler(toRequest(req, { trustProxy, res: reply.raw }), { request, reply })
|
|
16
|
+
reply.hijack()
|
|
17
|
+
await sendResponse(reply.raw, response)
|
|
18
|
+
},
|
|
19
|
+
})
|
|
20
|
+
}
|
|
21
|
+
// Fastify reads this to skip encapsulation, so the route is added to the app that registers the plugin
|
|
22
|
+
clarityFastify[Symbol.for('skip-override')] = true
|
|
23
|
+
export const createFastifyPlugin = (options) => async (fastify) => clarityFastify(fastify, options)
|
|
24
|
+
export default clarityFastify
|
package/handler.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// One request handler for a whole Clarity app, in the Web standard: (Request) => Promise<Response>.
|
|
2
|
+
// Use it as is on Bun, Deno, Cloudflare Workers, Vercel/Netlify edge and Hono; on Node, wrap it with
|
|
3
|
+
// toNodeHandler() from '@clarity-js/ssr/node' (or the Express / Fastify adapters).
|
|
4
|
+
|
|
5
|
+
import { sortRoutes, selectRoute } from '@ozsarman/clarityjs/pages-router'
|
|
6
|
+
import { createActionRouter } from '@ozsarman/clarityjs/server-actions'
|
|
7
|
+
import { renderPage, streamPage, createContext, ServerResponse } from './render.js'
|
|
8
|
+
|
|
9
|
+
const METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']
|
|
10
|
+
const ACTIONS = '/_clarity/actions/'
|
|
11
|
+
|
|
12
|
+
function pickComponent(mod) {
|
|
13
|
+
if (typeof mod?.default === 'function') return mod.default
|
|
14
|
+
for (const [name, v] of Object.entries(mod ?? {})) if (typeof v === 'function' && /^[A-Z]/.test(name) && !METHODS.includes(name)) return v
|
|
15
|
+
return null
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** What a handler returned → a Response: a Response as is, a string as HTML, anything else as JSON. */
|
|
19
|
+
export function toResponse(value, init = {}) {
|
|
20
|
+
if (value instanceof Response) return value
|
|
21
|
+
if (value == null) return new Response(null, { status: 204, ...init })
|
|
22
|
+
if (typeof value === 'string') return new Response(value, { ...init, headers: { 'content-type': 'text/html; charset=utf-8', ...init.headers } })
|
|
23
|
+
return Response.json(value, init)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function fromSignal(err) {
|
|
27
|
+
const headers = new Headers(err.headers)
|
|
28
|
+
if (err.location) { headers.set('location', err.location); return new Response(null, { status: err.status, headers }) }
|
|
29
|
+
return new Response(err.body ?? String(err.status), { status: err.status, headers })
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* @param {object} options
|
|
34
|
+
* @param {Array<{ pattern: string, load?: () => Promise<object>, module?: object, component?: Function }>} [options.routes]
|
|
35
|
+
* the route table — `routes` from 'virtual:clarity-pages', scanRoutes() from '@clarity-js/ssr/node', or your own.
|
|
36
|
+
* A route's module may export a page component (default), `loader(ctx)` (its result is the page's `data`
|
|
37
|
+
* prop), `head` ({ title, meta, … } for useHead), and GET/POST/PUT/PATCH/DELETE handlers
|
|
38
|
+
* `(request, ctx) => Response | object | string`. A module with handlers and no component is an API route.
|
|
39
|
+
* @param {Function} [options.app] or one root component that routes itself (Router/Route); rendered for every path
|
|
40
|
+
* @param {Function} [options.notFound] the 404 page component ({ path })
|
|
41
|
+
* @param {Function} [options.error] the 500 page component ({ error }) — the error itself is never shown in production
|
|
42
|
+
* @param {object|object[]} [options.actions] modules of defineServerAction() exports, served at POST /_clarity/actions/:name
|
|
43
|
+
* @param {(request, platform) => object | Promise<object>} [options.locals] per-request values for ctx.locals (the user, the db)
|
|
44
|
+
* @param {boolean} [options.stream] stream the pages (see streamPage)
|
|
45
|
+
* @param {string} [options.basePath] the app lives under this path ('/shop')
|
|
46
|
+
* @param {boolean} [options.passthrough] answer an unmatched path with a bare 404 marked for adapters to call next()
|
|
47
|
+
* @param {(error, request) => void} [options.onError]
|
|
48
|
+
* @param {object} [options.document] what every page shares: title, titleTemplate, lang, dir, styles, stylesheets,
|
|
49
|
+
* clientScript, scripts, head, nonce (string or (request) => string), appId, bodyAttrs, htmlAttrs, document()
|
|
50
|
+
*/
|
|
51
|
+
export function createHandler(options = {}) {
|
|
52
|
+
const { app = null, notFound: NotFound = null, error: ErrorPage = null, stream = false, basePath = '', passthrough = false, onError = (e) => console.error('[@clarity-js/ssr]', e) } = options
|
|
53
|
+
const routes = sortRoutes((options.routes ?? []).map((r) => ({ ...r, pattern: r.pattern ?? r.path })))
|
|
54
|
+
const modules = new Map()
|
|
55
|
+
const actions = options.actions ? createActionRouter(...[].concat(options.actions)).fetch() : null
|
|
56
|
+
const dev = typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production'
|
|
57
|
+
|
|
58
|
+
const load = async (route) => {
|
|
59
|
+
if (route.module) return route.module
|
|
60
|
+
if (route.component) return { default: route.component }
|
|
61
|
+
if (!modules.has(route.pattern)) modules.set(route.pattern, Promise.resolve(route.load()).catch((e) => { modules.delete(route.pattern); throw e }))
|
|
62
|
+
return modules.get(route.pattern)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function page(component, request, ctx, extra = {}) {
|
|
66
|
+
const doc = options.document ?? {}
|
|
67
|
+
const nonce = typeof doc.nonce === 'function' ? doc.nonce(request) : doc.nonce
|
|
68
|
+
const o = { ...doc, ...extra, nonce, component, ctx, url: ctx.url, props: { params: ctx.params, path: ctx.path, query: ctx.query, ...extra.props } }
|
|
69
|
+
if (stream && request.method !== 'HEAD') {
|
|
70
|
+
const r = streamPage({ ...o, onError: (e) => onError(e, request) })
|
|
71
|
+
return new Response(r.body, { status: r.status, headers: r.headers })
|
|
72
|
+
}
|
|
73
|
+
const r = await renderPage({ ...o, throwSignals: true })
|
|
74
|
+
return new Response(request.method === 'HEAD' ? null : r.html, { status: r.status, headers: r.headers })
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function errorPage(err, request, ctx) {
|
|
78
|
+
onError(err, request)
|
|
79
|
+
if (ErrorPage) {
|
|
80
|
+
try {
|
|
81
|
+
ctx.setStatus(500)
|
|
82
|
+
return await page(ErrorPage, request, ctx, { props: { error: dev ? err : { message: 'Something went wrong' } } })
|
|
83
|
+
} catch (again) { onError(again, request) }
|
|
84
|
+
}
|
|
85
|
+
return new Response(dev ? `<pre>${String(err?.stack ?? err).replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' })[c])}</pre>` : '<h1>500</h1>', { status: 500, headers: { 'content-type': 'text/html; charset=utf-8' } })
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return async function handle(request, platform) {
|
|
89
|
+
const url = new URL(request.url)
|
|
90
|
+
let path = url.pathname
|
|
91
|
+
if (basePath) {
|
|
92
|
+
if (path !== basePath && !path.startsWith(basePath + '/')) return new Response('Not Found', { status: 404, headers: passthrough ? { 'x-clarity-passthrough': '1' } : {} })
|
|
93
|
+
path = path.slice(basePath.length) || '/'
|
|
94
|
+
}
|
|
95
|
+
if (actions && path.startsWith(ACTIONS)) {
|
|
96
|
+
const inner = new URL(url); inner.pathname = path
|
|
97
|
+
return actions(new Request(inner, request))
|
|
98
|
+
}
|
|
99
|
+
const method = request.method.toUpperCase()
|
|
100
|
+
let ctx
|
|
101
|
+
try {
|
|
102
|
+
const locals = (await options.locals?.(request, platform)) ?? {}
|
|
103
|
+
const match = selectRoute(routes, path)
|
|
104
|
+
ctx = createContext({ request, url: path + url.search, params: match?.params ?? {}, locals, platform })
|
|
105
|
+
if (match) {
|
|
106
|
+
const mod = await load(match.route)
|
|
107
|
+
const Page = pickComponent(mod)
|
|
108
|
+
const fn = mod[method] ?? (method === 'HEAD' ? mod.GET : null)
|
|
109
|
+
if (fn && (method !== 'GET' || !Page)) return toResponse(await fn(request, ctx), { status: ctx.response.status, headers: ctx.response.headers })
|
|
110
|
+
if (!Page) {
|
|
111
|
+
const allow = METHODS.filter((m) => typeof mod[m] === 'function')
|
|
112
|
+
return new Response('Method Not Allowed', { status: 405, headers: { allow: allow.join(', ') } })
|
|
113
|
+
}
|
|
114
|
+
if (method !== 'GET' && method !== 'HEAD') return new Response('Method Not Allowed', { status: 405, headers: { allow: ['GET', 'HEAD', ...METHODS.filter((m) => typeof mod[m] === 'function')].join(', ') } })
|
|
115
|
+
const data = typeof mod.loader === 'function' ? await mod.loader(ctx) : undefined
|
|
116
|
+
const head = typeof mod.head === 'function' ? mod.head({ data, params: ctx.params }) : mod.head ?? (mod.meta?.title ? { title: mod.meta.title } : null)
|
|
117
|
+
return await page(Page, request, ctx, { headTags: head, props: data === undefined ? {} : { data } })
|
|
118
|
+
}
|
|
119
|
+
if (app) return await page(app, request, ctx)
|
|
120
|
+
if (passthrough && !NotFound) return new Response('Not Found', { status: 404, headers: { 'x-clarity-passthrough': '1' } })
|
|
121
|
+
throw new ServerResponse(404)
|
|
122
|
+
} catch (err) {
|
|
123
|
+
if (err instanceof Response) return err
|
|
124
|
+
if (err instanceof ServerResponse) {
|
|
125
|
+
if (err.status === 404 && NotFound && !err.location && err.body == null) {
|
|
126
|
+
try {
|
|
127
|
+
ctx ??= createContext({ request, url: path + url.search, platform })
|
|
128
|
+
ctx.setStatus(404)
|
|
129
|
+
return await page(NotFound, request, ctx, { props: { path } })
|
|
130
|
+
} catch (again) { return errorPage(again, request, ctx) }
|
|
131
|
+
}
|
|
132
|
+
return fromSignal(err)
|
|
133
|
+
}
|
|
134
|
+
return errorPage(err, request, ctx ?? createContext({ request, url: path, platform }))
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
export interface ServerContext {
|
|
2
|
+
request: Request | null
|
|
3
|
+
url: string
|
|
4
|
+
path: string
|
|
5
|
+
params: Record<string, string>
|
|
6
|
+
query: Record<string, string>
|
|
7
|
+
cookies: Record<string, string>
|
|
8
|
+
locals: Record<string, any>
|
|
9
|
+
platform: unknown
|
|
10
|
+
response: { status: number; headers: Headers }
|
|
11
|
+
setStatus(code: number): void
|
|
12
|
+
setHeader(name: string, value: string): void
|
|
13
|
+
appendHeader(name: string, value: string): void
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export class ServerResponse extends Error {
|
|
17
|
+
status: number
|
|
18
|
+
location: string | null
|
|
19
|
+
headers: Record<string, string>
|
|
20
|
+
body: string | null
|
|
21
|
+
}
|
|
22
|
+
/** throw redirect('/login') */
|
|
23
|
+
export function redirect(location: string, status?: 301 | 302 | 303 | 307 | 308): ServerResponse
|
|
24
|
+
/** throw notFound() */
|
|
25
|
+
export function notFound(body?: string | null): ServerResponse
|
|
26
|
+
/** throw httpError(403, 'No entry') */
|
|
27
|
+
export function httpError(status: number, body?: string | null): ServerResponse
|
|
28
|
+
|
|
29
|
+
export interface DocumentOptions {
|
|
30
|
+
title?: string
|
|
31
|
+
titleTemplate?: string
|
|
32
|
+
lang?: string
|
|
33
|
+
dir?: 'ltr' | 'rtl'
|
|
34
|
+
styles?: string
|
|
35
|
+
stylesheets?: string | string[]
|
|
36
|
+
clientScript?: string | string[]
|
|
37
|
+
scripts?: string[]
|
|
38
|
+
head?: string
|
|
39
|
+
nonce?: string
|
|
40
|
+
appId?: string
|
|
41
|
+
bodyAttrs?: Record<string, string | boolean>
|
|
42
|
+
htmlAttrs?: Record<string, string | boolean>
|
|
43
|
+
/** Your own document: gets the rendered parts (start = up to the static head, end = the rest). */
|
|
44
|
+
document?: (parts: { html: string; state: object; head: { title: string; metas: string; links: string; scripts: string }; start: string; end: string; escapeHTML(s: string): string }) => string
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface RenderOptions extends DocumentOptions {
|
|
48
|
+
component: Function
|
|
49
|
+
props?: Record<string, any>
|
|
50
|
+
url?: string
|
|
51
|
+
ctx?: Partial<ServerContext>
|
|
52
|
+
/** Tags as useHead() takes them ({ title, meta, link }), set before the component's own. */
|
|
53
|
+
headTags?: object
|
|
54
|
+
idPrefix?: string
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function createContext(init?: { request?: Request; url?: string; params?: Record<string, string>; locals?: Record<string, any>; platform?: unknown }): ServerContext
|
|
58
|
+
export function renderPage(options: RenderOptions & { throwSignals?: boolean }): Promise<{ status: number; headers: Headers; html: string; state: object; serverData: object }>
|
|
59
|
+
export function streamPage(options: RenderOptions & { onError?: (error: unknown) => void }): { status: number; headers: Headers; body: ReadableStream<Uint8Array> }
|
|
60
|
+
|
|
61
|
+
export interface RouteModule {
|
|
62
|
+
default?: Function
|
|
63
|
+
loader?: (ctx: ServerContext) => any
|
|
64
|
+
head?: object | ((info: { data: any; params: Record<string, string> }) => object)
|
|
65
|
+
GET?: (request: Request, ctx: ServerContext) => any
|
|
66
|
+
POST?: (request: Request, ctx: ServerContext) => any
|
|
67
|
+
PUT?: (request: Request, ctx: ServerContext) => any
|
|
68
|
+
PATCH?: (request: Request, ctx: ServerContext) => any
|
|
69
|
+
DELETE?: (request: Request, ctx: ServerContext) => any
|
|
70
|
+
[k: string]: any
|
|
71
|
+
}
|
|
72
|
+
export interface Route {
|
|
73
|
+
pattern?: string
|
|
74
|
+
path?: string
|
|
75
|
+
file?: string
|
|
76
|
+
load?: () => Promise<RouteModule>
|
|
77
|
+
module?: RouteModule
|
|
78
|
+
component?: Function
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface HandlerOptions {
|
|
82
|
+
routes?: Route[]
|
|
83
|
+
app?: Function
|
|
84
|
+
notFound?: Function
|
|
85
|
+
error?: Function
|
|
86
|
+
actions?: object | object[]
|
|
87
|
+
locals?: (request: Request, platform: unknown) => object | Promise<object>
|
|
88
|
+
stream?: boolean
|
|
89
|
+
basePath?: string
|
|
90
|
+
passthrough?: boolean
|
|
91
|
+
onError?: (error: unknown, request: Request) => void
|
|
92
|
+
document?: Omit<DocumentOptions, 'nonce'> & { nonce?: string | ((request: Request) => string) }
|
|
93
|
+
}
|
|
94
|
+
export type Handler = (request: Request, platform?: unknown) => Promise<Response>
|
|
95
|
+
export function createHandler(options?: HandlerOptions): Handler
|
|
96
|
+
export function toResponse(value: unknown, init?: ResponseInit): Response
|
package/index.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @clarity-js/ssr — a server for a Clarity app, on the core's renderToString.
|
|
3
|
+
*
|
|
4
|
+
* One handler in the Web standard, (Request) => Promise<Response>, that renders pages (loaders,
|
|
5
|
+
* useServerData(), useHead(), the router's path, the state for hydration), answers API routes and server
|
|
6
|
+
* actions, streams when you ask, and redirects or 404s when a loader says so. It runs as is on Bun, Deno,
|
|
7
|
+
* Cloudflare Workers and Hono; '@clarity-js/ssr/node' puts it on node:http, Express and Fastify, and prerenders
|
|
8
|
+
* pages to files with the same code.
|
|
9
|
+
*
|
|
10
|
+
* import { createHandler } from '@clarity-js/ssr'
|
|
11
|
+
* import { routes } from 'virtual:clarity-pages'
|
|
12
|
+
* export default { fetch: createHandler({ routes, document: { title: 'Shop', clientScript: '/assets/app.js' } }) }
|
|
13
|
+
*/
|
|
14
|
+
export { createHandler, toResponse } from './handler.js'
|
|
15
|
+
export { renderPage, streamPage, createContext, redirect, notFound, httpError, ServerResponse } from './render.js'
|
package/node.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse as NodeResponse, Server } from 'node:http'
|
|
2
|
+
import type { Handler, HandlerOptions, Route } from './index.js'
|
|
3
|
+
|
|
4
|
+
export function toRequest(req: IncomingMessage & { body?: unknown; originalUrl?: string }, options?: { trustProxy?: boolean; res?: NodeResponse }): Request
|
|
5
|
+
export function sendResponse(res: NodeResponse, response: Response): Promise<void>
|
|
6
|
+
export function toNodeHandler(handler: Handler, options?: { trustProxy?: boolean }): (req: IncomingMessage, res: NodeResponse, next?: (err?: unknown) => void) => Promise<void>
|
|
7
|
+
export function serve(handler: Handler, options?: { port?: number; hostname?: string; trustProxy?: boolean; onListen?: (info: { port: number }) => void }): Server
|
|
8
|
+
export function scanRoutes(dir: string, options?: { extensions?: RegExp; ignore?: RegExp }): Promise<Route[]>
|
|
9
|
+
export function staticPaths(routes: Route[]): string[]
|
|
10
|
+
export function prerender(options: { handler: Handler; paths: string[] | (() => string[] | Promise<string[]>); outDir?: string; origin?: string; concurrency?: number; onPage?: (info: { path: string; file: string; done: number; total: number }) => void }): Promise<{ written: string[]; failed: { path: string; status?: number; error?: unknown }[] }>
|
|
11
|
+
|
|
12
|
+
export function createExpressMiddleware(options?: HandlerOptions & { trustProxy?: boolean }): (req: IncomingMessage, res: NodeResponse, next: (err?: unknown) => void) => Promise<void>
|
|
13
|
+
export function clarityFastify(fastify: any, options?: HandlerOptions & { trustProxy?: boolean }): Promise<void>
|
|
14
|
+
export function createFastifyPlugin(options?: HandlerOptions & { trustProxy?: boolean }): (fastify: any) => Promise<void>
|
|
15
|
+
export default createExpressMiddleware
|
package/node.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// Node pieces: the Web handler on node:http (and so on Express, Fastify, Koa, Connect), a small server, the
|
|
2
|
+
// route table from a pages folder, and prerendering pages to files with the same handler.
|
|
3
|
+
|
|
4
|
+
import http from 'node:http'
|
|
5
|
+
import { Readable } from 'node:stream'
|
|
6
|
+
import { readdir, mkdir, writeFile } from 'node:fs/promises'
|
|
7
|
+
import { join, relative, dirname, resolve, sep } from 'node:path'
|
|
8
|
+
import { pathToFileURL } from 'node:url'
|
|
9
|
+
import { filePathToRoutePattern, sortRoutes } from '@ozsarman/clarityjs/pages-router'
|
|
10
|
+
|
|
11
|
+
/** An IncomingMessage as a Web Request. A body a framework has already parsed (req.body) is sent on. */
|
|
12
|
+
export function toRequest(req, { trustProxy = false, res = null } = {}) {
|
|
13
|
+
const proto = (trustProxy && String(req.headers['x-forwarded-proto'] ?? '').split(',')[0].trim()) || (req.socket?.encrypted ? 'https' : 'http')
|
|
14
|
+
const host = (trustProxy && req.headers['x-forwarded-host']) || req.headers.host || 'localhost'
|
|
15
|
+
const url = new URL(req.originalUrl ?? req.url ?? '/', `${proto}://${host}`)
|
|
16
|
+
const headers = new Headers()
|
|
17
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
18
|
+
if (v == null || k.startsWith(':')) continue
|
|
19
|
+
if (Array.isArray(v)) for (const one of v) headers.append(k, one)
|
|
20
|
+
else headers.set(k, String(v))
|
|
21
|
+
}
|
|
22
|
+
const init = { method: req.method, headers }
|
|
23
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
24
|
+
if (req.body !== undefined) {
|
|
25
|
+
const b = req.body
|
|
26
|
+
const raw = typeof b === 'string' || b instanceof Uint8Array
|
|
27
|
+
init.body = raw ? b : b instanceof URLSearchParams ? b.toString() : JSON.stringify(b)
|
|
28
|
+
if (!raw && !(b instanceof URLSearchParams)) headers.set('content-type', 'application/json')
|
|
29
|
+
headers.delete('content-length')
|
|
30
|
+
} else {
|
|
31
|
+
init.body = Readable.toWeb(req)
|
|
32
|
+
init.duplex = 'half'
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
if (res) {
|
|
36
|
+
// the client went away before the answer was sent: request.signal lets loaders stop their work
|
|
37
|
+
const controller = new AbortController()
|
|
38
|
+
res.once('close', () => { if (!res.writableFinished) controller.abort() })
|
|
39
|
+
init.signal = controller.signal
|
|
40
|
+
}
|
|
41
|
+
return new Request(url, init)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Write a Web Response to a ServerResponse, streaming its body. */
|
|
45
|
+
export async function sendResponse(res, response) {
|
|
46
|
+
res.statusCode = response.status
|
|
47
|
+
const cookies = response.headers.getSetCookie?.() ?? []
|
|
48
|
+
for (const [k, v] of response.headers) if (k !== 'set-cookie') res.setHeader(k, v)
|
|
49
|
+
if (cookies.length) res.setHeader('set-cookie', cookies)
|
|
50
|
+
if (!response.body) { res.end(); return }
|
|
51
|
+
res.flushHeaders?.()
|
|
52
|
+
const reader = response.body.getReader()
|
|
53
|
+
try {
|
|
54
|
+
for (;;) {
|
|
55
|
+
const { done, value } = await reader.read()
|
|
56
|
+
if (done) break
|
|
57
|
+
if (!res.write(value)) await new Promise((r) => res.once('drain', r))
|
|
58
|
+
}
|
|
59
|
+
} finally { res.end() }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The Web handler as a Node (req, res, next?) handler. With `next` (Express, Connect), a 404 the handler marks
|
|
64
|
+
* as passthrough goes on to the next middleware.
|
|
65
|
+
*/
|
|
66
|
+
export function toNodeHandler(handler, { trustProxy = false } = {}) {
|
|
67
|
+
return async function clarity(req, res, next) {
|
|
68
|
+
try {
|
|
69
|
+
const response = await handler(toRequest(req, { trustProxy, res }), { req, res })
|
|
70
|
+
if (typeof next === 'function' && response.headers.get('x-clarity-passthrough')) return next()
|
|
71
|
+
await sendResponse(res, response)
|
|
72
|
+
} catch (err) {
|
|
73
|
+
if (typeof next === 'function') return next(err)
|
|
74
|
+
console.error('[@clarity-js/ssr]', err)
|
|
75
|
+
if (!res.headersSent) { res.statusCode = 500; res.end('Internal Server Error') } else res.end()
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A node:http server for the handler. `serve(handler, { port: 3000 })` */
|
|
81
|
+
export function serve(handler, { port = Number(process.env.PORT) || 3000, hostname, trustProxy = false, onListen } = {}) {
|
|
82
|
+
const server = http.createServer(toNodeHandler(handler, { trustProxy }))
|
|
83
|
+
server.listen(port, hostname, () => (onListen ?? (({ port: p }) => console.log(`Clarity app on http://${hostname ?? 'localhost'}:${p}`)))({ port: server.address().port }))
|
|
84
|
+
return server
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const PAGE = /\.(m?js|clarity)$/
|
|
88
|
+
/**
|
|
89
|
+
* The route table of a pages folder, for createHandler(): pages/blog/[slug].js → /blog/:slug, pages/api/users.js
|
|
90
|
+
* → /api/users. Modules load on first request. `.clarity` pages need a loader that compiles them — run Node with
|
|
91
|
+
* `--import @clarity-js/testing/register`, or build the server with Vite.
|
|
92
|
+
*/
|
|
93
|
+
export async function scanRoutes(dir, { extensions = PAGE, ignore = /(^|\/)(_|\.)/ } = {}) {
|
|
94
|
+
const root = resolve(dir)
|
|
95
|
+
const files = []
|
|
96
|
+
const walk = async (d) => {
|
|
97
|
+
for (const e of await readdir(d, { withFileTypes: true })) {
|
|
98
|
+
const full = join(d, e.name)
|
|
99
|
+
const rel = relative(root, full).split(sep).join('/')
|
|
100
|
+
if (ignore.test(rel)) continue
|
|
101
|
+
if (e.isDirectory()) await walk(full)
|
|
102
|
+
else if (extensions.test(e.name)) files.push(rel)
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
await walk(root)
|
|
106
|
+
return sortRoutes(files.map((file) => ({ pattern: filePathToRoutePattern(file), file, load: () => import(pathToFileURL(join(root, file)).href) })))
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The patterns of a route table that have no parameters: what prerender() can do without being told. */
|
|
110
|
+
export const staticPaths = (routes) => routes.map((r) => r.pattern ?? r.path).filter((p) => p && !/[:*]/.test(p))
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Render paths with the handler and write them as files: '/' → index.html, '/about' → about/index.html,
|
|
114
|
+
* '/feed.xml' → feed.xml. The same handler as the server, so a static page is the page the server sends.
|
|
115
|
+
* @returns {Promise<{ written: string[], failed: { path, status?, error? }[] }>}
|
|
116
|
+
*/
|
|
117
|
+
export async function prerender({ handler, paths, outDir = 'dist', origin = 'http://localhost', concurrency = 4, onPage } = {}) {
|
|
118
|
+
const list = typeof paths === 'function' ? await paths() : paths
|
|
119
|
+
const written = [], failed = []
|
|
120
|
+
const queue = [...new Set(list)]
|
|
121
|
+
const worker = async () => {
|
|
122
|
+
for (let p; (p = queue.shift()) !== undefined;) {
|
|
123
|
+
try {
|
|
124
|
+
const response = await handler(new Request(new URL(p, origin)), { prerender: true })
|
|
125
|
+
if (!response.ok) { failed.push({ path: p, status: response.status }); continue }
|
|
126
|
+
const clean = p.split(/[?#]/)[0]
|
|
127
|
+
const file = /\.[a-z0-9]+$/i.test(clean) ? clean : join(clean, 'index.html')
|
|
128
|
+
const out = join(outDir, file)
|
|
129
|
+
await mkdir(dirname(out), { recursive: true })
|
|
130
|
+
await writeFile(out, Buffer.from(await response.arrayBuffer()))
|
|
131
|
+
written.push(out)
|
|
132
|
+
onPage?.({ path: p, file: out, done: written.length + failed.length, total: list.length })
|
|
133
|
+
} catch (error) { failed.push({ path: p, error }) }
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
await Promise.all(Array.from({ length: Math.max(1, concurrency) }, worker))
|
|
137
|
+
return { written: written.sort(), failed }
|
|
138
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@clarity-js/ssr",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "A server for Clarity.js apps: one Web-standard handler that renders pages (loaders, server data, head, hydration state), answers API routes and server actions, streams, redirects and 404s — on Bun, Deno, Workers and Hono as is, and on Node, Express and Fastify through adapters; prerenders pages to files with the same code. No dependencies.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./index.js",
|
|
7
|
+
"module": "./index.js",
|
|
8
|
+
"types": "./index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": { "types": "./index.d.ts", "import": "./index.js", "default": "./index.js" },
|
|
11
|
+
"./node": { "types": "./node.d.ts", "import": "./node.js", "default": "./node.js" },
|
|
12
|
+
"./express": { "types": "./node.d.ts", "import": "./express.js", "default": "./express.js" },
|
|
13
|
+
"./fastify": { "types": "./node.d.ts", "import": "./fastify.js", "default": "./fastify.js" },
|
|
14
|
+
"./package.json": "./package.json"
|
|
15
|
+
},
|
|
16
|
+
"files": ["index.js", "handler.js", "render.js", "node.js", "express.js", "fastify.js", "index.d.ts", "node.d.ts", "README.md"],
|
|
17
|
+
"sideEffects": false,
|
|
18
|
+
"keywords": ["clarity", "@ozsarman/clarityjs", "ssr", "server-side-rendering", "streaming", "ssg", "prerender", "express", "fastify", "hono", "bun", "deno", "cloudflare-workers"],
|
|
19
|
+
"author": "Özdemir Şarman",
|
|
20
|
+
"license": "MIT",
|
|
21
|
+
"peerDependencies": { "@ozsarman/clarityjs": ">=1.10.0" },
|
|
22
|
+
"homepage": "https://clarity-js.com/docs/packages#ssr",
|
|
23
|
+
"repository": { "type": "git", "url": "git+https://gitlab.com/ozsarman/clarity.js.git", "directory": "packages/clarity-ssr" },
|
|
24
|
+
"engines": { "node": ">=18.0.0" }
|
|
25
|
+
}
|
package/render.js
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
// Rendering a page on the server: the component's loader, useServerData() fetches, useHead() tags, the router's
|
|
2
|
+
// path, the serialized state, and the response's status and headers — as one document or as a stream.
|
|
3
|
+
// Platform-neutral: no Node APIs, so the same code runs on Node, Bun, Deno and edge workers.
|
|
4
|
+
|
|
5
|
+
import { renderToString, escapeHTML, escapeAttr, safeJSONForScript } from '@ozsarman/clarityjs/ssr'
|
|
6
|
+
import { _beginServerData, _endServerData } from '@ozsarman/clarityjs/server-data'
|
|
7
|
+
import { createHead, renderHead } from '@ozsarman/clarityjs/head'
|
|
8
|
+
import { setServerPath } from '@ozsarman/clarityjs/router'
|
|
9
|
+
|
|
10
|
+
const SERVER_DATA_KEY = '__serverData'
|
|
11
|
+
|
|
12
|
+
/** Thrown from a loader, a page or a fetcher to answer with something else than the page. */
|
|
13
|
+
export class ServerResponse extends Error {
|
|
14
|
+
constructor(status, { location = null, headers = {}, body = null } = {}) {
|
|
15
|
+
super(location ? `redirect ${status} → ${location}` : `HTTP ${status}`)
|
|
16
|
+
this.name = 'ServerResponse'
|
|
17
|
+
this.status = status
|
|
18
|
+
this.location = location
|
|
19
|
+
this.headers = headers
|
|
20
|
+
this.body = body
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** `throw redirect('/login')` — 302 unless you say otherwise (301, 303, 307, 308). */
|
|
24
|
+
export const redirect = (location, status = 302) => new ServerResponse(status, { location })
|
|
25
|
+
/** `throw notFound()` — the 404 page (or the text) instead of this one. */
|
|
26
|
+
export const notFound = (body = null) => new ServerResponse(404, { body })
|
|
27
|
+
/** `throw httpError(403, 'No entry')` */
|
|
28
|
+
export const httpError = (status, body = null) => new ServerResponse(status, { body })
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The context a loader, a page's server block and useServerData() fetchers receive.
|
|
32
|
+
* setStatus / setHeader change the response; locals carries what your middleware put there.
|
|
33
|
+
*/
|
|
34
|
+
export function createContext({ request = null, url = '/', params = {}, locals = {}, platform = null } = {}) {
|
|
35
|
+
const u = new URL(url, 'http://localhost')
|
|
36
|
+
const response = { status: 200, headers: new Headers() }
|
|
37
|
+
return {
|
|
38
|
+
request, params, locals, platform,
|
|
39
|
+
url: u.pathname + u.search, path: u.pathname,
|
|
40
|
+
query: Object.fromEntries(u.searchParams),
|
|
41
|
+
cookies: parseCookies(request?.headers?.get?.('cookie') ?? ''),
|
|
42
|
+
response,
|
|
43
|
+
setStatus(code) { response.status = code },
|
|
44
|
+
setHeader(name, value) { response.headers.set(name, value) },
|
|
45
|
+
appendHeader(name, value) { response.headers.append(name, value) },
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function parseCookies(header) {
|
|
50
|
+
const out = {}
|
|
51
|
+
for (const part of header.split(';')) {
|
|
52
|
+
const i = part.indexOf('=')
|
|
53
|
+
if (i < 0) continue
|
|
54
|
+
const k = part.slice(0, i).trim()
|
|
55
|
+
if (!k || k in out) continue
|
|
56
|
+
try { out[k] = decodeURIComponent(part.slice(i + 1).trim()) } catch { out[k] = part.slice(i + 1).trim() }
|
|
57
|
+
}
|
|
58
|
+
return out
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Render the component with everything it asks the server for. Two synchronous passes when it uses
|
|
63
|
+
* useServerData() (collect, fetch, render again); the head is read inside the same synchronous pass, so
|
|
64
|
+
* concurrent requests never see each other's tags.
|
|
65
|
+
*/
|
|
66
|
+
async function renderApp({ component, props = {}, ctx, url, title = '', titleTemplate = null, headTags = null, idPrefix }) {
|
|
67
|
+
if (typeof component !== 'function') throw new TypeError('[@clarity-js/ssr] component must be a Clarity component (a function)')
|
|
68
|
+
let p = props
|
|
69
|
+
if (typeof component.__clarity_server__ === 'function') p = { ...props, __ssr: await component.__clarity_server__(props, ctx) }
|
|
70
|
+
const pass = (data) => {
|
|
71
|
+
_beginServerData(data)
|
|
72
|
+
let result, collected, headHtml
|
|
73
|
+
try {
|
|
74
|
+
if (url) setServerPath(url)
|
|
75
|
+
const head = createHead({ defaultTitle: title, titleTemplate })
|
|
76
|
+
if (headTags) head._register(headTags)
|
|
77
|
+
result = renderToString(component, p, idPrefix ? { idPrefix } : {})
|
|
78
|
+
headHtml = renderHead(head)
|
|
79
|
+
} finally { collected = _endServerData() }
|
|
80
|
+
return { result, collected, headHtml }
|
|
81
|
+
}
|
|
82
|
+
let { result, collected, headHtml } = pass({})
|
|
83
|
+
let serverData = {}
|
|
84
|
+
if (collected?.pending.length) {
|
|
85
|
+
serverData = {}
|
|
86
|
+
await Promise.all(collected.pending.map(async ({ key, fetcher }) => { serverData[key] = typeof fetcher === 'function' ? await fetcher(ctx) : undefined }))
|
|
87
|
+
;({ result, headHtml } = pass(serverData))
|
|
88
|
+
}
|
|
89
|
+
const state = Object.keys(serverData).length ? { ...result.state, [SERVER_DATA_KEY]: serverData } : result.state
|
|
90
|
+
return { html: result.html, state, serverData, head: headHtml, aiContracts: result.aiContracts }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const attrs = (o = {}) => Object.entries(o).filter(([, v]) => v != null && v !== false).map(([k, v]) => (v === true ? ` ${k}` : ` ${k}="${escapeAttr(v)}"`)).join('')
|
|
94
|
+
|
|
95
|
+
function documentParts(o, rendered) {
|
|
96
|
+
const nonce = o.nonce ? ` nonce="${escapeAttr(o.nonce)}"` : ''
|
|
97
|
+
const scripts = [].concat(o.clientScript ?? [], o.scripts ?? [])
|
|
98
|
+
const start = [
|
|
99
|
+
'<!DOCTYPE html>',
|
|
100
|
+
`<html${attrs({ lang: o.lang ?? 'en', dir: o.dir, ...o.htmlAttrs })}>`,
|
|
101
|
+
'<head>',
|
|
102
|
+
'<meta charset="utf-8">',
|
|
103
|
+
'<meta name="viewport" content="width=device-width,initial-scale=1">',
|
|
104
|
+
...[].concat(o.stylesheets ?? []).map((href) => `<link rel="stylesheet" href="${escapeAttr(href)}">`),
|
|
105
|
+
o.styles ? `<style${nonce}>${o.styles}</style>` : '',
|
|
106
|
+
...scripts.map((src) => `<link rel="modulepreload" href="${escapeAttr(src)}">`),
|
|
107
|
+
o.head ?? '',
|
|
108
|
+
].filter(Boolean).join('\n')
|
|
109
|
+
if (!rendered) return { start }
|
|
110
|
+
const h = rendered.head ?? {}
|
|
111
|
+
const stateScript = rendered.state && Object.keys(rendered.state).length ? `<script${nonce}>window.__CLARITY_DATA__=${safeJSONForScript(rendered.state)};</script>` : ''
|
|
112
|
+
const end = [
|
|
113
|
+
h.title, h.metas, h.links, h.scripts,
|
|
114
|
+
'</head>',
|
|
115
|
+
`<body${attrs(o.bodyAttrs)}>`,
|
|
116
|
+
`<div id="${escapeAttr(o.appId ?? 'app')}">${rendered.html}</div>`,
|
|
117
|
+
stateScript,
|
|
118
|
+
...scripts.map((src) => `<script type="module" src="${escapeAttr(src)}"${nonce}></script>`),
|
|
119
|
+
'</body>',
|
|
120
|
+
'</html>',
|
|
121
|
+
].filter(Boolean).join('\n')
|
|
122
|
+
return { start, end }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function signalResponse(err, o) {
|
|
126
|
+
const headers = new Headers({ 'content-type': 'text/html; charset=utf-8', ...err.headers })
|
|
127
|
+
if (err.location) { headers.set('location', err.location); return { status: err.status, headers, html: '' } }
|
|
128
|
+
return { status: err.status, headers, html: err.body == null ? `<!DOCTYPE html><title>${err.status}</title><h1>${err.status}</h1>` : String(err.body) }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Render a whole HTML document.
|
|
133
|
+
* @returns {Promise<{ status, headers: Headers, html, state, serverData }>}
|
|
134
|
+
*/
|
|
135
|
+
export async function renderPage(options = {}) {
|
|
136
|
+
const ctx = options.ctx?.response ? options.ctx : createContext({ url: options.url ?? '/', ...options.ctx })
|
|
137
|
+
try {
|
|
138
|
+
const rendered = await renderApp({ ...options, ctx, url: options.url ?? ctx.url })
|
|
139
|
+
const { start, end } = documentParts(options, rendered)
|
|
140
|
+
const html = typeof options.document === 'function' ? options.document({ ...rendered, start, end, escapeHTML }) : `${start}\n${end}`
|
|
141
|
+
const headers = new Headers(ctx.response.headers)
|
|
142
|
+
if (!headers.has('content-type')) headers.set('content-type', 'text/html; charset=utf-8')
|
|
143
|
+
return { status: ctx.response.status, headers, html, state: rendered.state, serverData: rendered.serverData }
|
|
144
|
+
} catch (err) {
|
|
145
|
+
if (err instanceof ServerResponse && !options.throwSignals) return signalResponse(err, options)
|
|
146
|
+
throw err
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Stream the document: the head's fixed part (charset, styles, preloads of the client script) leaves at once,
|
|
152
|
+
* so the browser starts on the assets while loaders and fetches run; the rest follows when the page is ready.
|
|
153
|
+
* A redirect thrown after the start has left becomes a meta refresh plus location.replace().
|
|
154
|
+
* @returns {{ status, headers: Headers, body: ReadableStream<Uint8Array> }}
|
|
155
|
+
*/
|
|
156
|
+
export function streamPage(options = {}) {
|
|
157
|
+
const ctx = options.ctx?.response ? options.ctx : createContext({ url: options.url ?? '/', ...options.ctx })
|
|
158
|
+
const enc = new TextEncoder()
|
|
159
|
+
const { start } = documentParts(options)
|
|
160
|
+
const body = new ReadableStream({
|
|
161
|
+
async start(controller) {
|
|
162
|
+
controller.enqueue(enc.encode(start + '\n'))
|
|
163
|
+
try {
|
|
164
|
+
const rendered = await renderApp({ ...options, ctx, url: options.url ?? ctx.url })
|
|
165
|
+
controller.enqueue(enc.encode(documentParts(options, rendered).end))
|
|
166
|
+
} catch (err) {
|
|
167
|
+
let tail
|
|
168
|
+
if (err instanceof ServerResponse && err.location) {
|
|
169
|
+
const to = escapeAttr(err.location)
|
|
170
|
+
tail = `<meta http-equiv="refresh" content="0;url=${to}">\n<script${options.nonce ? ` nonce="${escapeAttr(options.nonce)}"` : ''}>location.replace(${safeJSONForScript(err.location)})</script>\n</head><body></body></html>`
|
|
171
|
+
} else {
|
|
172
|
+
if (!(err instanceof ServerResponse)) options.onError?.(err)
|
|
173
|
+
const status = err instanceof ServerResponse ? err.status : 500
|
|
174
|
+
tail = `<title>${status}</title>\n</head><body>${err instanceof ServerResponse && err.body != null ? String(err.body) : `<h1>${status}</h1>`}</body></html>`
|
|
175
|
+
}
|
|
176
|
+
controller.enqueue(enc.encode(tail))
|
|
177
|
+
}
|
|
178
|
+
controller.close()
|
|
179
|
+
},
|
|
180
|
+
})
|
|
181
|
+
const headers = new Headers(ctx.response.headers)
|
|
182
|
+
if (!headers.has('content-type')) headers.set('content-type', 'text/html; charset=utf-8')
|
|
183
|
+
return { status: ctx.response.status, headers, body }
|
|
184
|
+
}
|