@crombolo/render 0.36.2 → 0.37.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/package.json +5 -2
- package/src/bundle-script.ts +4 -7
- package/src/context.ts +63 -7
- package/src/headers.ts +86 -0
- package/src/index.ts +3 -0
- package/src/islands-loader.ts +152 -0
- package/src/islands.ts +220 -0
- package/src/jsx-runtime.ts +26 -1
- package/src/model.ts +28 -2
- package/src/navigation.ts +70 -0
- package/src/renderer.ts +163 -36
- package/src/seo.ts +63 -1
- package/src/site.ts +48 -0
- package/src/snapshots.ts +32 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crombolo/render",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.37.0",
|
|
4
4
|
"description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. TSX server rendering and the published-content model for crombolo.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Crombolo",
|
|
@@ -19,6 +19,8 @@
|
|
|
19
19
|
"type": "module",
|
|
20
20
|
"exports": {
|
|
21
21
|
".": "./src/index.ts",
|
|
22
|
+
"./navigation": "./src/navigation.ts",
|
|
23
|
+
"./headers": "./src/headers.ts",
|
|
22
24
|
"./jsx-runtime": "./src/jsx-runtime.ts",
|
|
23
25
|
"./jsx-dev-runtime": "./src/jsx-runtime.ts",
|
|
24
26
|
"./loose/jsx-runtime": "./src/loose/jsx-runtime.ts",
|
|
@@ -32,7 +34,8 @@
|
|
|
32
34
|
"access": "public"
|
|
33
35
|
},
|
|
34
36
|
"dependencies": {
|
|
35
|
-
"@crombolo/
|
|
37
|
+
"@crombolo/common": "0.37.0",
|
|
38
|
+
"@crombolo/core": "0.37.0",
|
|
36
39
|
"@types/react": "^19.3.0"
|
|
37
40
|
}
|
|
38
41
|
}
|
package/src/bundle-script.ts
CHANGED
|
@@ -1,15 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* What a page needs to call
|
|
3
|
-
* the anti-forgery meta tag, and the script that sends
|
|
4
|
-
*
|
|
2
|
+
* What a page needs to call the site's route handlers as a signed-in member
|
|
3
|
+
* (stories 186 and 211): the anti-forgery meta tag, and the script that sends
|
|
4
|
+
* it back. docs/rendering.md, "Route handlers".
|
|
5
5
|
*/
|
|
6
6
|
import { currentAntiforgery } from './context.ts'
|
|
7
7
|
import { RawHtml } from './html.ts'
|
|
8
8
|
import { element } from './jsx-runtime.ts'
|
|
9
9
|
|
|
10
|
-
/** Where a bundle's member and public routes answer: `/crombolo/bundle/<id>/<path>`. */
|
|
11
|
-
export const BUNDLE_SITE_PATH = '/crombolo/bundle'
|
|
12
|
-
|
|
13
10
|
/** The header a cookie-authenticated member write carries. */
|
|
14
11
|
export const ANTIFORGERY_HEADER = 'Crombolo-Antiforgery'
|
|
15
12
|
|
|
@@ -31,7 +28,7 @@ export function AntiforgeryMeta(): RawHtml {
|
|
|
31
28
|
* `crombolo.fetch(input, init)`: `fetch`, with the page's anti-forgery token
|
|
32
29
|
* on requests to this site. Never sent to another origin.
|
|
33
30
|
*/
|
|
34
|
-
export const BUNDLE_SCRIPT = `/* crombolo
|
|
31
|
+
export const BUNDLE_SCRIPT = `/* crombolo: fetch with the member's anti-forgery token, for the site's routes */
|
|
35
32
|
(function () {
|
|
36
33
|
var crombolo = (window.crombolo = window.crombolo || {})
|
|
37
34
|
if (crombolo.fetch) return
|
package/src/context.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { AsyncLocalStorage } from 'node:async_hooks'
|
|
|
13
13
|
import type { Child } from './jsx-runtime.ts'
|
|
14
14
|
import type { PageProps } from './model.ts'
|
|
15
15
|
import type { SiteSearchPort } from './search.ts'
|
|
16
|
+
import type { Metadata } from './seo.ts'
|
|
16
17
|
|
|
17
18
|
interface RenderScope {
|
|
18
19
|
page: PageProps | undefined
|
|
@@ -29,6 +30,21 @@ interface RenderScope {
|
|
|
29
30
|
preview?: boolean
|
|
30
31
|
/** The signed-in member's anti-forgery token, for `<AntiforgeryMeta />`. */
|
|
31
32
|
antiforgery?: string
|
|
33
|
+
/** The request's own values, for `cookies()` and `headers()`; empty for a static page. */
|
|
34
|
+
request?: RequestValues
|
|
35
|
+
/** The site's services as the visitor, for `site()`. */
|
|
36
|
+
site?: () => unknown
|
|
37
|
+
/** Set once the page reads anything that depends on who is asking (story 206). */
|
|
38
|
+
personal?: { value: boolean }
|
|
39
|
+
/** What the page's `generateMetadata` returned, for `<SeoHead>`. */
|
|
40
|
+
metadata?: { value?: Metadata }
|
|
41
|
+
/** Set once anything on the page renders an island, so the loader is linked (story 209). */
|
|
42
|
+
islands?: { used: boolean }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** What `cookies()` and `headers()` read: the request's, or nothing for a static page. */
|
|
46
|
+
export interface RequestValues {
|
|
47
|
+
headers: Headers
|
|
32
48
|
}
|
|
33
49
|
|
|
34
50
|
/** Loads `components/blocks/<alias>.tsx`'s default export, or nothing when there is none. */
|
|
@@ -42,6 +58,11 @@ export interface RenderScopeOptions {
|
|
|
42
58
|
blockComponent?: BlockComponentLoader
|
|
43
59
|
preview?: boolean
|
|
44
60
|
antiforgery?: string
|
|
61
|
+
request?: RequestValues
|
|
62
|
+
site?: () => unknown
|
|
63
|
+
personal?: { value: boolean }
|
|
64
|
+
metadata?: { value?: Metadata }
|
|
65
|
+
islands?: { used: boolean }
|
|
45
66
|
}
|
|
46
67
|
|
|
47
68
|
/**
|
|
@@ -62,6 +83,14 @@ export function renderScope<T>(
|
|
|
62
83
|
return store.run({ page, ...options, contexts: new Map(), ids: { next: 0 } }, render)
|
|
63
84
|
}
|
|
64
85
|
|
|
86
|
+
/**
|
|
87
|
+
* Runs a route handler (story 211): 206's `cookies()`, `headers()` and `site()`
|
|
88
|
+
* read this request, and there is no page.
|
|
89
|
+
*/
|
|
90
|
+
export function requestScope<T>(request: RequestValues, site: () => unknown, run: () => T): T {
|
|
91
|
+
return store.run({ page: undefined, request, site, contexts: new Map(), ids: { next: 0 } }, run)
|
|
92
|
+
}
|
|
93
|
+
|
|
65
94
|
/** Runs an e-mail template's render: ids and context work, and there is no page. */
|
|
66
95
|
export function emailScope<T>(render: () => T): T {
|
|
67
96
|
return store.run({ page: undefined, email: true, contexts: new Map(), ids: { next: 0 } }, render)
|
|
@@ -152,13 +181,7 @@ export function createContext<T>(defaultValue: T): Context<T> {
|
|
|
152
181
|
const contexts = new Map(outer?.contexts)
|
|
153
182
|
contexts.set(key, value)
|
|
154
183
|
return store.run(
|
|
155
|
-
{
|
|
156
|
-
page: outer?.page,
|
|
157
|
-
email: outer?.email,
|
|
158
|
-
search: outer?.search,
|
|
159
|
-
contexts,
|
|
160
|
-
ids: outer?.ids ?? { next: 0 },
|
|
161
|
-
},
|
|
184
|
+
{ ...outer, page: outer?.page, contexts, ids: outer?.ids ?? { next: 0 } },
|
|
162
185
|
children,
|
|
163
186
|
)
|
|
164
187
|
}
|
|
@@ -180,3 +203,36 @@ export function blockComponentLoader(): BlockComponentLoader | undefined {
|
|
|
180
203
|
export function isPreview(): boolean {
|
|
181
204
|
return store.getStore()?.preview === true
|
|
182
205
|
}
|
|
206
|
+
|
|
207
|
+
/** Records that the page depends on who is asking, so it is never shared. */
|
|
208
|
+
export function markPersonal(): void {
|
|
209
|
+
const personal = store.getStore()?.personal
|
|
210
|
+
if (personal) personal.value = true
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** The request's values for `cookies()` and `headers()`, which name themselves as `caller`. */
|
|
214
|
+
export function currentRequest(caller: string): RequestValues {
|
|
215
|
+
const scope = within(caller)
|
|
216
|
+
if (scope.email) throw new Error(`${caller} was called while ${NO_PAGE_IN_EMAIL}`)
|
|
217
|
+
markPersonal()
|
|
218
|
+
return scope.request ?? { headers: new Headers() }
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** The site's services for this render, built by the server for whoever is asking. */
|
|
222
|
+
export function currentSite(caller: string): unknown {
|
|
223
|
+
const scope = within(caller)
|
|
224
|
+
if (scope.email) throw new Error(`${caller} was called while ${NO_PAGE_IN_EMAIL}`)
|
|
225
|
+
if (!scope.site) throw new Error(`${caller} has no site services in this render.`)
|
|
226
|
+
return scope.site()
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** What the page's `generateMetadata` returned, when it has one. */
|
|
230
|
+
export function currentMetadata(): Metadata | undefined {
|
|
231
|
+
return store.getStore()?.metadata?.value
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Records that the page holds an island, so it links the island loader. */
|
|
235
|
+
export function markIslands(): void {
|
|
236
|
+
const islands = store.getStore()?.islands
|
|
237
|
+
if (islands) islands.used = true
|
|
238
|
+
}
|
package/src/headers.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The request a page is rendering for, as `next/headers` offers it: `cookies()`
|
|
3
|
+
* and `headers()`, both read-only. Reading either makes the page personal, so
|
|
4
|
+
* it is never shared (story 206).
|
|
5
|
+
*/
|
|
6
|
+
import type { ReadonlyRequestCookies, RequestCookie } from '@crombolo/common'
|
|
7
|
+
import { currentRequest } from './context.ts'
|
|
8
|
+
|
|
9
|
+
export type { ReadonlyRequestCookies, RequestCookie } from '@crombolo/common'
|
|
10
|
+
|
|
11
|
+
/** The request's headers, read-only: `get`, `has` and iteration. */
|
|
12
|
+
export interface ReadonlyHeaders extends Iterable<[string, string]> {
|
|
13
|
+
get(name: string): string | null
|
|
14
|
+
has(name: string): boolean
|
|
15
|
+
entries(): IterableIterator<[string, string]>
|
|
16
|
+
keys(): IterableIterator<string>
|
|
17
|
+
values(): IterableIterator<string>
|
|
18
|
+
forEach(callback: (value: string, name: string) => void): void
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function parseCookies(header: string | null): RequestCookie[] {
|
|
22
|
+
if (!header) return []
|
|
23
|
+
const found: RequestCookie[] = []
|
|
24
|
+
for (const part of header.split(';')) {
|
|
25
|
+
const at = part.indexOf('=')
|
|
26
|
+
if (at <= 0) continue
|
|
27
|
+
const name = part.slice(0, at).trim()
|
|
28
|
+
const raw = part
|
|
29
|
+
.slice(at + 1)
|
|
30
|
+
.trim()
|
|
31
|
+
.replace(/^"(.*)"$/, '$1')
|
|
32
|
+
let value = raw
|
|
33
|
+
try {
|
|
34
|
+
value = decodeURIComponent(raw)
|
|
35
|
+
} catch {}
|
|
36
|
+
if (name) found.push({ name, value })
|
|
37
|
+
}
|
|
38
|
+
return found
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function readonlyCookies(header: string | null): ReadonlyRequestCookies {
|
|
42
|
+
const all = parseCookies(header)
|
|
43
|
+
const first = new Map<string, RequestCookie>()
|
|
44
|
+
for (const cookie of all) if (!first.has(cookie.name)) first.set(cookie.name, cookie)
|
|
45
|
+
return Object.freeze({
|
|
46
|
+
get: (name: string) => first.get(name),
|
|
47
|
+
getAll: (name?: string) => (name === undefined ? [...all] : all.filter((c) => c.name === name)),
|
|
48
|
+
has: (name: string) => first.has(name),
|
|
49
|
+
size: first.size,
|
|
50
|
+
[Symbol.iterator]: () => first.entries(),
|
|
51
|
+
})
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function readonlyHeaders(source: Headers): ReadonlyHeaders {
|
|
55
|
+
const copy = new Headers(source)
|
|
56
|
+
return Object.freeze({
|
|
57
|
+
get: (name: string) => copy.get(name),
|
|
58
|
+
has: (name: string) => copy.has(name),
|
|
59
|
+
entries: () => copy.entries(),
|
|
60
|
+
keys: () => copy.keys(),
|
|
61
|
+
values: () => copy.values(),
|
|
62
|
+
forEach: (callback: (value: string, name: string) => void) =>
|
|
63
|
+
copy.forEach((value, name) => {
|
|
64
|
+
callback(value, name)
|
|
65
|
+
}),
|
|
66
|
+
[Symbol.iterator]: () => copy.entries(),
|
|
67
|
+
})
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The request's cookies; empty on a page that exports `dynamic = 'force-static'`. */
|
|
71
|
+
export function cookies(): Promise<ReadonlyRequestCookies> {
|
|
72
|
+
try {
|
|
73
|
+
return Promise.resolve(readonlyCookies(currentRequest('cookies()').headers.get('cookie')))
|
|
74
|
+
} catch (error) {
|
|
75
|
+
return Promise.reject(error)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The request's headers; empty on a page that exports `dynamic = 'force-static'`. */
|
|
80
|
+
export function headers(): Promise<ReadonlyHeaders> {
|
|
81
|
+
try {
|
|
82
|
+
return Promise.resolve(readonlyHeaders(currentRequest('headers()').headers))
|
|
83
|
+
} catch (error) {
|
|
84
|
+
return Promise.reject(error)
|
|
85
|
+
}
|
|
86
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -7,6 +7,8 @@ export * from './excerpt.ts'
|
|
|
7
7
|
export * from './form-script.ts'
|
|
8
8
|
export * from './forms.ts'
|
|
9
9
|
export * from './html.ts'
|
|
10
|
+
export * from './islands.ts'
|
|
11
|
+
export * from './islands-loader.ts'
|
|
10
12
|
export * from './jsx-attributes.ts'
|
|
11
13
|
export * from './jsx-runtime.ts'
|
|
12
14
|
export * from './media.ts'
|
|
@@ -19,6 +21,7 @@ export * from './renderer.ts'
|
|
|
19
21
|
export * from './search.ts'
|
|
20
22
|
export * from './seo.ts'
|
|
21
23
|
export * from './sign-in.ts'
|
|
24
|
+
export * from './site.ts'
|
|
22
25
|
export * from './sitemap.ts'
|
|
23
26
|
export * from './snapshots.ts'
|
|
24
27
|
export * from './url-segment.ts'
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The island loader, served at `/crombolo/islands.js` (story 209). It finds
|
|
3
|
+
* every `<crombolo-island>`, waits for its `data-load` condition, imports its
|
|
4
|
+
* module through the generation's manifest, and mounts it: a client
|
|
5
|
+
* component with React, an `<Island>` module through its `mount` function.
|
|
6
|
+
*
|
|
7
|
+
* Written as a function and served as its source, so a test can run it with
|
|
8
|
+
* stand-ins for the browser. A file, never inline, so a page with islands
|
|
9
|
+
* works under `script-src 'self'`.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** What the loader needs from the browser. */
|
|
13
|
+
export interface LoaderEnvironment {
|
|
14
|
+
document: {
|
|
15
|
+
querySelector(selector: string): { getAttribute(name: string): string | null } | null
|
|
16
|
+
querySelectorAll(selector: string): ArrayLike<IslandElement>
|
|
17
|
+
}
|
|
18
|
+
importModule(url: string): Promise<Record<string, unknown>>
|
|
19
|
+
fetchJson(url: string): Promise<IslandManifest>
|
|
20
|
+
IntersectionObserver?: new (
|
|
21
|
+
callback: (entries: Array<{ isIntersecting: boolean; target: unknown }>) => void,
|
|
22
|
+
options?: { rootMargin?: string },
|
|
23
|
+
) => { observe(target: unknown): void; unobserve(target: unknown): void }
|
|
24
|
+
requestIdleCallback?: (callback: () => void) => void
|
|
25
|
+
setTimeout(callback: () => void, ms: number): unknown
|
|
26
|
+
console: { error(...values: unknown[]): void }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The element an island renders as, as far as the loader touches it. */
|
|
30
|
+
export interface IslandElement {
|
|
31
|
+
dataset: Record<string, string | undefined>
|
|
32
|
+
querySelector(selector: string): { textContent: string | null; innerHTML: string } | null
|
|
33
|
+
cloneNode(deep: boolean): {
|
|
34
|
+
querySelectorAll(selector: string): ArrayLike<{ remove(): void }>
|
|
35
|
+
innerHTML: string
|
|
36
|
+
}
|
|
37
|
+
replaceChildren(): void
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** What a generation's build, or a Vite manifest made over, says: where each island's code is. */
|
|
41
|
+
export interface IslandManifest {
|
|
42
|
+
/** The module that mounts a React component: `mount(Component, element, props, childrenHtml)`. */
|
|
43
|
+
react?: string
|
|
44
|
+
modules: Record<string, string>
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function islandLoader(env: LoaderEnvironment): void {
|
|
48
|
+
const meta = env.document.querySelector('meta[name="crombolo-islands"]')
|
|
49
|
+
const manifestUrl = meta?.getAttribute('content')
|
|
50
|
+
if (!manifestUrl) return
|
|
51
|
+
let manifest: Promise<IslandManifest> | undefined
|
|
52
|
+
const modules = new Map<string, Promise<Record<string, unknown>>>()
|
|
53
|
+
const load = (url: string) => {
|
|
54
|
+
let pending = modules.get(url)
|
|
55
|
+
if (!pending) {
|
|
56
|
+
pending = env.importModule(url)
|
|
57
|
+
modules.set(url, pending)
|
|
58
|
+
}
|
|
59
|
+
return pending
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** What the server rendered as the island's content, less its props and carried children. */
|
|
63
|
+
const shownHtml = (element: IslandElement): string => {
|
|
64
|
+
const copy = element.cloneNode(true)
|
|
65
|
+
const extras = copy.querySelectorAll(
|
|
66
|
+
':scope > script[type="application/json"], :scope > template[data-children]',
|
|
67
|
+
)
|
|
68
|
+
for (let i = 0; i < extras.length; i++) extras[i]?.remove()
|
|
69
|
+
return copy.innerHTML
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const mount = async (element: IslandElement): Promise<void> => {
|
|
73
|
+
if (element.dataset.mounted) return
|
|
74
|
+
element.dataset.mounted = 'true'
|
|
75
|
+
const name = element.dataset.module ?? '?'
|
|
76
|
+
try {
|
|
77
|
+
manifest ??= env.fetchJson(manifestUrl)
|
|
78
|
+
const built = await manifest
|
|
79
|
+
const url = built.modules[name]
|
|
80
|
+
if (!url) throw new Error(`no browser code was built for it`)
|
|
81
|
+
const props = JSON.parse(
|
|
82
|
+
element.querySelector(':scope > script[type="application/json"]')?.textContent || '{}',
|
|
83
|
+
) as Record<string, unknown>
|
|
84
|
+
const mode = element.dataset.children
|
|
85
|
+
const childrenHtml =
|
|
86
|
+
mode === 'template'
|
|
87
|
+
? (element.querySelector(':scope > template[data-children]')?.innerHTML ?? null)
|
|
88
|
+
: mode === 'inline'
|
|
89
|
+
? shownHtml(element)
|
|
90
|
+
: null
|
|
91
|
+
const module = await load(url)
|
|
92
|
+
if (element.dataset.kind === 'mount') {
|
|
93
|
+
const mountIt = module.default as (target: unknown, props: unknown) => unknown
|
|
94
|
+
element.replaceChildren()
|
|
95
|
+
await mountIt(element, props)
|
|
96
|
+
return
|
|
97
|
+
}
|
|
98
|
+
if (!built.react) throw new Error('the React mount module was not built')
|
|
99
|
+
const react = await load(built.react)
|
|
100
|
+
const component = module[element.dataset.export ?? 'default']
|
|
101
|
+
if (typeof component !== 'function')
|
|
102
|
+
throw new Error(`it has no export "${element.dataset.export}"`)
|
|
103
|
+
;(react.mount as (c: unknown, e: unknown, p: unknown, h: string | null) => void)(
|
|
104
|
+
component,
|
|
105
|
+
element,
|
|
106
|
+
props,
|
|
107
|
+
childrenHtml,
|
|
108
|
+
)
|
|
109
|
+
} catch (error) {
|
|
110
|
+
// Its fallback stays; nothing else on the page is touched.
|
|
111
|
+
env.console.error(`The island ${name} could not load:`, error)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const islands = env.document.querySelectorAll('crombolo-island')
|
|
116
|
+
let observer: InstanceType<NonNullable<LoaderEnvironment['IntersectionObserver']>> | undefined
|
|
117
|
+
for (let i = 0; i < islands.length; i++) {
|
|
118
|
+
const element = islands[i] as IslandElement
|
|
119
|
+
const when = element.dataset.load
|
|
120
|
+
if (when === 'load') void mount(element)
|
|
121
|
+
else if (when === 'idle') {
|
|
122
|
+
const later = () => void mount(element)
|
|
123
|
+
if (env.requestIdleCallback) env.requestIdleCallback(later)
|
|
124
|
+
else env.setTimeout(later, 200)
|
|
125
|
+
} else if (env.IntersectionObserver) {
|
|
126
|
+
observer ??= new env.IntersectionObserver(
|
|
127
|
+
(entries) => {
|
|
128
|
+
for (const entry of entries)
|
|
129
|
+
if (entry.isIntersecting) {
|
|
130
|
+
observer?.unobserve(entry.target)
|
|
131
|
+
void mount(entry.target as IslandElement)
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
{ rootMargin: '200px' },
|
|
135
|
+
)
|
|
136
|
+
observer.observe(element)
|
|
137
|
+
} else void mount(element)
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The script `/crombolo/islands.js` serves. */
|
|
142
|
+
export const ISLAND_LOADER_SCRIPT = `/* crombolo islands (story 209) */
|
|
143
|
+
(${islandLoader.toString()})({
|
|
144
|
+
document,
|
|
145
|
+
importModule: (url) => import(url),
|
|
146
|
+
fetchJson: (url) => fetch(url).then((r) => { if (!r.ok) throw new Error(r.status + ' for ' + url); return r.json() }),
|
|
147
|
+
IntersectionObserver: window.IntersectionObserver,
|
|
148
|
+
requestIdleCallback: window.requestIdleCallback ? window.requestIdleCallback.bind(window) : undefined,
|
|
149
|
+
setTimeout: window.setTimeout.bind(window),
|
|
150
|
+
console,
|
|
151
|
+
})
|
|
152
|
+
`
|
package/src/islands.ts
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Interactive islands (story 209). A view module whose first statement is
|
|
3
|
+
* `'use client'` runs in the browser: while views are copied into a snapshot it
|
|
4
|
+
* is written as a stub, whose exports render a `<crombolo-island>` placeholder
|
|
5
|
+
* carrying the props as JSON. The browser code is built per snapshot
|
|
6
|
+
* generation, and `/crombolo/islands.js` mounts each island when it is needed.
|
|
7
|
+
* docs/rendering.md, "Islands".
|
|
8
|
+
*/
|
|
9
|
+
import { markIslands } from './context.ts'
|
|
10
|
+
import { escapeHtml, RawHtml } from './html.ts'
|
|
11
|
+
import { type Child, renderToString } from './jsx-runtime.ts'
|
|
12
|
+
|
|
13
|
+
/** The loader every page with an island links to; a file, so no inline script is written. */
|
|
14
|
+
export const ISLAND_LOADER_PATH = '/crombolo/islands.js'
|
|
15
|
+
/** Where a generation's built browser code is served from. */
|
|
16
|
+
export const ISLANDS_PATH = '/crombolo/islands'
|
|
17
|
+
|
|
18
|
+
/** When an island loads: as it scrolls into view, when the browser is idle, or at once. */
|
|
19
|
+
export type IslandLoad = 'visible' | 'idle' | 'load'
|
|
20
|
+
const LOADS: readonly IslandLoad[] = ['visible', 'idle', 'load']
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Whether a module's first statement is `'use client'`. Comments may come
|
|
24
|
+
* before it; the words anywhere else, in a string or later on, do not count.
|
|
25
|
+
*/
|
|
26
|
+
export function isClientModule(source: string): boolean {
|
|
27
|
+
let rest = source.replace(/^/, '')
|
|
28
|
+
for (;;) {
|
|
29
|
+
rest = rest.replace(/^\s+/, '')
|
|
30
|
+
if (rest.startsWith('//')) {
|
|
31
|
+
const end = rest.indexOf('\n')
|
|
32
|
+
rest = end < 0 ? '' : rest.slice(end + 1)
|
|
33
|
+
} else if (rest.startsWith('/*')) {
|
|
34
|
+
const end = rest.indexOf('*/')
|
|
35
|
+
if (end < 0) return false
|
|
36
|
+
rest = rest.slice(end + 2)
|
|
37
|
+
} else break
|
|
38
|
+
}
|
|
39
|
+
return /^(['"])use client\1\s*(;|\n|$)/.test(rest)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** A prop an island cannot carry to the browser, named by where it is. */
|
|
43
|
+
export class IslandPropsError extends Error {}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The props as JSON a `<script type="application/json">` can hold: refused
|
|
47
|
+
* when anything would not survive the trip, escaped so nothing in it can close
|
|
48
|
+
* the script or read as markup.
|
|
49
|
+
*/
|
|
50
|
+
export function serializeProps(props: Record<string, unknown>, island: string): string {
|
|
51
|
+
const seen = new Set<object>()
|
|
52
|
+
const check = (value: unknown, path: string): void => {
|
|
53
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean') return
|
|
54
|
+
if (typeof value === 'number') {
|
|
55
|
+
if (!Number.isFinite(value))
|
|
56
|
+
throw new IslandPropsError(`${island}: ${path} is ${value}, which JSON cannot carry.`)
|
|
57
|
+
return
|
|
58
|
+
}
|
|
59
|
+
if (typeof value !== 'object') {
|
|
60
|
+
const what = value === undefined ? 'undefined' : `a ${typeof value}`
|
|
61
|
+
throw new IslandPropsError(
|
|
62
|
+
`${island}: ${path} is ${what}; an island's props travel to the browser as JSON, so only data can be passed.`,
|
|
63
|
+
)
|
|
64
|
+
}
|
|
65
|
+
if (seen.has(value))
|
|
66
|
+
throw new IslandPropsError(
|
|
67
|
+
`${island}: ${path} refers back to itself, which JSON cannot carry.`,
|
|
68
|
+
)
|
|
69
|
+
const proto = Object.getPrototypeOf(value)
|
|
70
|
+
if (!Array.isArray(value) && proto !== Object.prototype && proto !== null)
|
|
71
|
+
throw new IslandPropsError(
|
|
72
|
+
`${island}: ${path} is ${value instanceof Date ? 'a Date' : `a ${proto?.constructor?.name ?? 'class'} instance`}; pass plain data, such as a string or a number.`,
|
|
73
|
+
)
|
|
74
|
+
seen.add(value)
|
|
75
|
+
if (Array.isArray(value))
|
|
76
|
+
for (const [index, item] of value.entries()) check(item, `${path}[${index}]`)
|
|
77
|
+
else
|
|
78
|
+
for (const [key, item] of Object.entries(value))
|
|
79
|
+
if (item !== undefined) check(item, `${path}.${key}`)
|
|
80
|
+
seen.delete(value)
|
|
81
|
+
}
|
|
82
|
+
check(props, 'props')
|
|
83
|
+
return JSON.stringify(props)
|
|
84
|
+
.replaceAll('<', '\\u003c')
|
|
85
|
+
.replaceAll('>', '\\u003e')
|
|
86
|
+
.replaceAll('&', '\\u0026')
|
|
87
|
+
.replaceAll('
', '\\u2028')
|
|
88
|
+
.replaceAll('
', '\\u2029')
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const transpiler = new Bun.Transpiler({ loader: 'tsx' })
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* What a client module is written as in a snapshot: each of its exports a
|
|
95
|
+
* server component rendering the island. It imports nothing; the island
|
|
96
|
+
* renderer is reached through a global this module sets, so the stub works
|
|
97
|
+
* wherever the snapshot sits.
|
|
98
|
+
*/
|
|
99
|
+
export function islandStub(module: string, source: string): string {
|
|
100
|
+
const { exports } = transpiler.scan(source)
|
|
101
|
+
const island = 'globalThis[Symbol.for("crombolo.island")]'
|
|
102
|
+
const lines = [`// The browser half of ${module} ('use client', story 209).`]
|
|
103
|
+
for (const name of exports) {
|
|
104
|
+
const call = `(props) => ${island}(${JSON.stringify(module)}, ${JSON.stringify(name)}, props)`
|
|
105
|
+
lines.push(name === 'default' ? `export default ${call}` : `export const ${name} = ${call}`)
|
|
106
|
+
}
|
|
107
|
+
return `${lines.join('\n')}\n`
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const encoder = new TextEncoder()
|
|
111
|
+
const decoder = new TextDecoder()
|
|
112
|
+
|
|
113
|
+
/** The snapshot transform: a client module's stub, or undefined to copy the file as it is. */
|
|
114
|
+
export function islandTransform(key: string, bytes: Uint8Array): Uint8Array | undefined {
|
|
115
|
+
if (!/\.[jt]sx?$/.test(key)) return undefined
|
|
116
|
+
const source = decoder.decode(bytes)
|
|
117
|
+
return isClientModule(source) ? encoder.encode(islandStub(key, source)) : undefined
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const htmlOf = async (child: unknown): Promise<string> =>
|
|
121
|
+
child === undefined || child === null ? '' : renderToString(child as Child)
|
|
122
|
+
|
|
123
|
+
interface IslandOptions {
|
|
124
|
+
kind: 'react' | 'mount'
|
|
125
|
+
module: string
|
|
126
|
+
exportName: string
|
|
127
|
+
props: Record<string, unknown>
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function renderIsland(options: IslandOptions): Promise<RawHtml> {
|
|
131
|
+
const { load = 'visible', fallback, children, ...rest } = options.props
|
|
132
|
+
const where =
|
|
133
|
+
options.kind === 'mount'
|
|
134
|
+
? `<Island name="${options.module.slice('client/'.length)}">`
|
|
135
|
+
: options.module
|
|
136
|
+
if (!LOADS.includes(load as IslandLoad))
|
|
137
|
+
throw new IslandPropsError(
|
|
138
|
+
`${where}: load must be visible, idle or load, not ${JSON.stringify(load)}.`,
|
|
139
|
+
)
|
|
140
|
+
const json = serializeProps(rest, where)
|
|
141
|
+
const [fallbackHtml, childrenHtml] = await Promise.all([htmlOf(fallback), htmlOf(children)])
|
|
142
|
+
markIslands()
|
|
143
|
+
let shown = fallbackHtml
|
|
144
|
+
let carried = ''
|
|
145
|
+
let childrenMode = 'none'
|
|
146
|
+
if (options.kind === 'react') {
|
|
147
|
+
if (fallback === undefined || fallback === null) {
|
|
148
|
+
shown = childrenHtml
|
|
149
|
+
if (childrenHtml) childrenMode = 'inline'
|
|
150
|
+
} else if (childrenHtml) {
|
|
151
|
+
carried = `<template data-children>${childrenHtml}</template>`
|
|
152
|
+
childrenMode = 'template'
|
|
153
|
+
}
|
|
154
|
+
} else if (fallback === undefined || fallback === null) shown = childrenHtml
|
|
155
|
+
const attributes = [
|
|
156
|
+
`data-kind="${options.kind}"`,
|
|
157
|
+
`data-module="${escapeHtml(options.module)}"`,
|
|
158
|
+
`data-export="${escapeHtml(options.exportName)}"`,
|
|
159
|
+
`data-load="${load}"`,
|
|
160
|
+
`data-children="${childrenMode}"`,
|
|
161
|
+
].join(' ')
|
|
162
|
+
return new RawHtml(
|
|
163
|
+
`<crombolo-island ${attributes}><script type="application/json">${json}</script>${shown}${carried}</crombolo-island>`,
|
|
164
|
+
)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** What a client component's stub calls. */
|
|
168
|
+
function clientIsland(module: string, exportName: string, props: Record<string, unknown> = {}) {
|
|
169
|
+
return renderIsland({ kind: 'react', module, exportName, props })
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Kept on `globalThis`, so a stub reaches it whichever copy of this module loaded first. */
|
|
173
|
+
const KEY = Symbol.for('crombolo.island')
|
|
174
|
+
;(globalThis as Record<symbol, unknown>)[KEY] ??= clientIsland
|
|
175
|
+
|
|
176
|
+
export interface IslandProps {
|
|
177
|
+
/** `components/client/<name>`, whose default export is `mount(element, props)`. */
|
|
178
|
+
name: string
|
|
179
|
+
props?: Record<string, unknown>
|
|
180
|
+
load?: IslandLoad
|
|
181
|
+
/** Shown until it mounts; the children when there is none. */
|
|
182
|
+
fallback?: Child
|
|
183
|
+
children?: Child
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* An island in another framework — Vue, Lit or plain TypeScript: the module
|
|
188
|
+
* `components/client/<name>` exports `mount(element, props)`, returning an
|
|
189
|
+
* optional unmount.
|
|
190
|
+
*/
|
|
191
|
+
export function Island({
|
|
192
|
+
name,
|
|
193
|
+
props = {},
|
|
194
|
+
load,
|
|
195
|
+
fallback,
|
|
196
|
+
children,
|
|
197
|
+
}: IslandProps): Promise<RawHtml> {
|
|
198
|
+
if (!/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/.test(name))
|
|
199
|
+
throw new IslandPropsError(
|
|
200
|
+
`<Island name="${name}">: the name is a path under components/client/.`,
|
|
201
|
+
)
|
|
202
|
+
return renderIsland({
|
|
203
|
+
kind: 'mount',
|
|
204
|
+
module: `client/${name}`,
|
|
205
|
+
exportName: 'default',
|
|
206
|
+
props: { ...props, load, fallback, children },
|
|
207
|
+
})
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** The tags a page with islands ends with: where its browser code is, and the loader. */
|
|
211
|
+
export function islandTags(manifestUrl: string): string {
|
|
212
|
+
return `<meta name="crombolo-islands" content="${escapeHtml(manifestUrl)}"><script type="module" src="${ISLAND_LOADER_PATH}"></script>`
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** A page's HTML with the island tags before `</body>`, or at the end when it has none. */
|
|
216
|
+
export function withIslandTags(html: string, manifestUrl: string): string {
|
|
217
|
+
const tags = islandTags(manifestUrl)
|
|
218
|
+
const at = html.toLowerCase().lastIndexOf('</body>')
|
|
219
|
+
return at < 0 ? `${html}${tags}` : `${html.slice(0, at)}${tags}${html.slice(at)}`
|
|
220
|
+
}
|
package/src/jsx-runtime.ts
CHANGED
|
@@ -285,6 +285,23 @@ export const jsxDEV = jsx
|
|
|
285
285
|
* `jsx-attributes.ts`), and markup out. `@crombolo/crombolo/loose` is the same runtime
|
|
286
286
|
* with any attribute on any tag, for a site not ready to be checked.
|
|
287
287
|
*/
|
|
288
|
+
/** What a React component returns, which is how a `'use client'` component is recognised. */
|
|
289
|
+
interface ClientElement {
|
|
290
|
+
type: unknown
|
|
291
|
+
props: unknown
|
|
292
|
+
key: unknown
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** What a template may give a `'use client'` component besides its own props. */
|
|
296
|
+
interface IslandAttributes {
|
|
297
|
+
/** Content it wraps, rendered here; shown until it mounts. */
|
|
298
|
+
children?: Child
|
|
299
|
+
/** When it loads: as it scrolls into view (the default), when the browser is idle, or at once. */
|
|
300
|
+
load?: 'visible' | 'idle' | 'load'
|
|
301
|
+
/** Shown until it mounts, instead of its children; never passed to it. */
|
|
302
|
+
fallback?: Child
|
|
303
|
+
}
|
|
304
|
+
|
|
288
305
|
export declare namespace JSX {
|
|
289
306
|
/** What a JSX expression is: markup, or a promise of it once anything in it is async. */
|
|
290
307
|
type Element = Html
|
|
@@ -300,7 +317,15 @@ export declare namespace JSX {
|
|
|
300
317
|
* against the component's own signature regardless; this constrains only what
|
|
301
318
|
* may stand in the tag position.
|
|
302
319
|
*/
|
|
303
|
-
type ElementType = string | ((props: never) => Child)
|
|
320
|
+
type ElementType = string | ((props: never) => Child) | ((props: never) => ClientElement)
|
|
321
|
+
/**
|
|
322
|
+
* A `'use client'` component (story 209) is typed with React's JSX but renders
|
|
323
|
+
* here as an island: it takes server-rendered children, and `load` and
|
|
324
|
+
* `fallback`, which never reach it.
|
|
325
|
+
*/
|
|
326
|
+
type LibraryManagedAttributes<C, P> = C extends (props: never) => ClientElement
|
|
327
|
+
? Omit<P, 'children'> & IslandAttributes
|
|
328
|
+
: P
|
|
304
329
|
interface IntrinsicElements extends KnownElements {
|
|
305
330
|
[custom: `${string}-${string}`]: CustomElementAttributes
|
|
306
331
|
}
|
package/src/model.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* ambient, so `model.value('title')` returns the current request's culture.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
import type { FormSubmissionState } from '@crombolo/core'
|
|
10
|
+
import type { FieldError, FormSubmissionState } from '@crombolo/core'
|
|
11
11
|
import type { RawHtml } from './html.ts'
|
|
12
12
|
import type { MediaWithCrops } from './media.ts'
|
|
13
13
|
import type { MenuItem } from './menus.ts'
|
|
@@ -263,7 +263,26 @@ export interface RequestMember {
|
|
|
263
263
|
roles: string[]
|
|
264
264
|
}
|
|
265
265
|
|
|
266
|
-
/**
|
|
266
|
+
/** The query string, as Next.js hands it to a page: repeated names become arrays. */
|
|
267
|
+
export type SearchParams = Record<string, string | string[] | undefined>
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* What a status page is told about the outcome it is answering (story 206):
|
|
271
|
+
* the status, the words the code gave, any field errors, and for a server
|
|
272
|
+
* error its reference, with the details only where they may be shown.
|
|
273
|
+
*/
|
|
274
|
+
export interface PageOutcome {
|
|
275
|
+
status: number
|
|
276
|
+
/** The helper's name, `notFound`; `serverError` for a 500. */
|
|
277
|
+
name: string
|
|
278
|
+
message?: string
|
|
279
|
+
errors: readonly FieldError[]
|
|
280
|
+
/** A 500's reference, which the log line carries too. */
|
|
281
|
+
reference?: string
|
|
282
|
+
/** A 500's message, source and stack, when `errors.showDetails` allows. */
|
|
283
|
+
details?: { message: string; location?: string; stack?: string }
|
|
284
|
+
}
|
|
285
|
+
|
|
267
286
|
/**
|
|
268
287
|
* What a template receives. Name the page's interface from `crombolo generate`
|
|
269
288
|
* to have its properties checked: `PageProps<HomePage>`.
|
|
@@ -292,6 +311,13 @@ export interface PageProps<Properties = any> {
|
|
|
292
311
|
submission: FormSubmissionState | undefined
|
|
293
312
|
/** The address requested, and the scheme and host it came in on. */
|
|
294
313
|
request: { origin: string; url: string }
|
|
314
|
+
/**
|
|
315
|
+
* The query string, as a promise as in Next.js 15. Awaiting it makes the page
|
|
316
|
+
* personal; empty on a page that exports `dynamic = 'force-static'`.
|
|
317
|
+
*/
|
|
318
|
+
searchParams: Promise<SearchParams>
|
|
319
|
+
/** On a status page, what it is answering; undefined on any other page. */
|
|
320
|
+
outcome?: PageOutcome
|
|
295
321
|
urls: {
|
|
296
322
|
/** A page's address with scheme and host; undefined for one with no address here. */
|
|
297
323
|
absolute(content: PublishedContent): string | undefined
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ending a page early, as `next/navigation` does: each function throws an
|
|
3
|
+
* outcome from any component, layout or block, and the page answers its status
|
|
4
|
+
* (story 206). The page renders whole before it answers, so a throw at any
|
|
5
|
+
* depth never meets a half-sent response.
|
|
6
|
+
*/
|
|
7
|
+
import { type FieldError, isOutcome, Outcome } from '@crombolo/core'
|
|
8
|
+
|
|
9
|
+
/** 307: sends the visitor on, keeping the request's method. */
|
|
10
|
+
export function redirect(url: string): never {
|
|
11
|
+
throw Outcome.redirect(url)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** 308: the page has moved for good. */
|
|
15
|
+
export function permanentRedirect(url: string): never {
|
|
16
|
+
throw Outcome.permanentRedirect(url)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** 404, rendered by the site's not-found page with `message` in `usePage().outcome`. */
|
|
20
|
+
export function notFound(message?: string): never {
|
|
21
|
+
throw Outcome.notFound(message)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** 403, rendered by the site's error page. */
|
|
25
|
+
export function forbidden(message?: string): never {
|
|
26
|
+
throw Outcome.forbidden(message)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** 401, rendered by the site's unauthorized page. */
|
|
30
|
+
export function unauthorized(message?: string): never {
|
|
31
|
+
throw Outcome.unauthorized(message)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 302: the everyday redirect, as `umbracoRedirect` answers. */
|
|
35
|
+
export function foundAt(url: string): never {
|
|
36
|
+
throw Outcome.foundAt(url)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 301: the page has moved for good. */
|
|
40
|
+
export function movedPermanentlyTo(url: string): never {
|
|
41
|
+
throw Outcome.movedPermanentlyTo(url)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 303: after a POST, look at this address. */
|
|
45
|
+
export function seeOther(url: string): never {
|
|
46
|
+
throw Outcome.seeOther(url)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 400: a request the page cannot use. */
|
|
50
|
+
export function badRequest(message?: string, errors?: readonly FieldError[]): never {
|
|
51
|
+
throw Outcome.badRequest(message, errors)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 410: the page is gone for good. */
|
|
55
|
+
export function gone(message?: string): never {
|
|
56
|
+
throw Outcome.gone(message)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 422: well-formed input that failed validation. */
|
|
60
|
+
export function unprocessableContent(errors: readonly FieldError[], message?: string): never {
|
|
61
|
+
throw Outcome.unprocessableContent(errors, message)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* For code that catches errors for its own reasons: rethrows an outcome so the
|
|
66
|
+
* page still answers it, and returns for anything else.
|
|
67
|
+
*/
|
|
68
|
+
export function rethrow(error: unknown): void {
|
|
69
|
+
if (isOutcome(error)) throw error
|
|
70
|
+
}
|
package/src/renderer.ts
CHANGED
|
@@ -9,21 +9,37 @@
|
|
|
9
9
|
import { existsSync } from 'node:fs'
|
|
10
10
|
import { basename, join, resolve, sep } from 'node:path'
|
|
11
11
|
import { pathToFileURL } from 'node:url'
|
|
12
|
-
import type
|
|
13
|
-
import { emailScope, renderScope } from './context.ts'
|
|
12
|
+
import { type FormSubmissionState, isOutcome, type Outcome } from '@crombolo/core'
|
|
13
|
+
import { emailScope, markPersonal, renderScope } from './context.ts'
|
|
14
14
|
import type { EmailProps, EmailRenderResult } from './email.ts'
|
|
15
15
|
import { RawHtml } from './html.ts'
|
|
16
|
+
import { ISLANDS_PATH, withIslandTags } from './islands.ts'
|
|
16
17
|
import { type Child, renderToString } from './jsx-runtime.ts'
|
|
17
|
-
import type {
|
|
18
|
+
import type {
|
|
19
|
+
PageOutcome,
|
|
20
|
+
PageProps,
|
|
21
|
+
PublishedContent,
|
|
22
|
+
RequestMember,
|
|
23
|
+
SearchParams,
|
|
24
|
+
} from './model.ts'
|
|
18
25
|
import { type PublishedCache, translate, urlsIn } from './published-cache.ts'
|
|
19
26
|
import type { SiteSearchPort } from './search.ts'
|
|
20
|
-
import { absoluteUrl, type SeoSiteDefaults } from './seo.ts'
|
|
27
|
+
import { absoluteUrl, type Metadata, type SeoSiteDefaults } from './seo.ts'
|
|
21
28
|
import type { ViewSnapshots } from './snapshots.ts'
|
|
22
29
|
|
|
23
30
|
export interface ComponentModule {
|
|
24
31
|
default: (props: PageProps) => Child | Promise<Child>
|
|
25
32
|
/** Alias of the layout template to wrap this one in. */
|
|
26
33
|
layout?: string
|
|
34
|
+
/**
|
|
35
|
+
* As Next.js's route segment config: `force-dynamic` is always personal;
|
|
36
|
+
* `force-static` empties the request's values so the page can be shared.
|
|
37
|
+
*/
|
|
38
|
+
dynamic?: 'auto' | 'force-dynamic' | 'force-static'
|
|
39
|
+
/** Seconds copies of the page may be kept, or false for as long as it is unchanged. */
|
|
40
|
+
revalidate?: number | false
|
|
41
|
+
/** Search and sharing values worked out per request, laid over the page's own. */
|
|
42
|
+
generateMetadata?: (props: PageProps) => Metadata | Promise<Metadata>
|
|
27
43
|
}
|
|
28
44
|
|
|
29
45
|
// biome-ignore lint/suspicious/noExplicitAny: an untyped page, as `PageProps` defaults to.
|
|
@@ -44,12 +60,27 @@ export interface RenderOptions {
|
|
|
44
60
|
snapshots?: ViewSnapshots
|
|
45
61
|
/** How long a page may take to render, layouts included; 0 for no limit. */
|
|
46
62
|
renderTimeoutMs?: number
|
|
63
|
+
/**
|
|
64
|
+
* Where a page's island code is described, for the generation it rendered
|
|
65
|
+
* with (story 209); by default the generation's own build.
|
|
66
|
+
*/
|
|
67
|
+
islandsManifest?: (generation: string | undefined) => string | undefined
|
|
47
68
|
}
|
|
48
69
|
|
|
49
70
|
export const DEFAULT_RENDER_TIMEOUT_MS = 10_000
|
|
50
71
|
|
|
72
|
+
/** What a rendered page says about how its answer may be kept. */
|
|
73
|
+
export interface RenderedCaching {
|
|
74
|
+
/** It read something that depends on who is asking, so it is never shared. */
|
|
75
|
+
personal: boolean
|
|
76
|
+
/** The template's own `revalidate`, overriding its type's and the site's lifetime. */
|
|
77
|
+
revalidate?: number | false
|
|
78
|
+
}
|
|
79
|
+
|
|
51
80
|
export type RenderResult =
|
|
52
|
-
| { status: 'ok'; html: string; content: PublishedContent }
|
|
81
|
+
| ({ status: 'ok'; html: string; content: PublishedContent } & RenderedCaching)
|
|
82
|
+
/** A component threw a redirect or a refusal (story 206). */
|
|
83
|
+
| ({ status: 'outcome'; outcome: Outcome; content: PublishedContent } & RenderedCaching)
|
|
53
84
|
| { status: 'notFound' }
|
|
54
85
|
/** The page names another to send its visitors to (`umbracoRedirect`). */
|
|
55
86
|
| { status: 'redirect'; location: string; content: PublishedContent }
|
|
@@ -103,6 +134,52 @@ export interface RenderRequest {
|
|
|
103
134
|
preview?: boolean
|
|
104
135
|
/** The signed-in member's anti-forgery token, written by `<AntiforgeryMeta />` (story 186). */
|
|
105
136
|
antiforgery?: string
|
|
137
|
+
/** The request's headers, cookies among them, for `cookies()` and `headers()` (story 206). */
|
|
138
|
+
headers?: Headers
|
|
139
|
+
/** The site's services as whoever is asking, for `site()`. */
|
|
140
|
+
site?: () => unknown
|
|
141
|
+
/** On a status page, the outcome it is answering, for `usePage().outcome`. */
|
|
142
|
+
outcome?: PageOutcome
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** The query string as Next.js hands it to a page: a name given twice becomes an array. */
|
|
146
|
+
function queryOf(url: string): SearchParams {
|
|
147
|
+
const query: SearchParams = {}
|
|
148
|
+
let params: URLSearchParams
|
|
149
|
+
try {
|
|
150
|
+
params = new URL(url).searchParams
|
|
151
|
+
} catch {
|
|
152
|
+
return query
|
|
153
|
+
}
|
|
154
|
+
for (const [name, value] of params) {
|
|
155
|
+
const seen = query[name]
|
|
156
|
+
query[name] =
|
|
157
|
+
seen === undefined ? value : Array.isArray(seen) ? [...seen, value] : [seen, value]
|
|
158
|
+
}
|
|
159
|
+
return query
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* The query as a promise that marks the page personal once anything awaits it.
|
|
164
|
+
* Handing the promise on, as spreading a page's props does, marks nothing. A
|
|
165
|
+
* subclass, because `await` on a plain promise never calls its own `then`.
|
|
166
|
+
*/
|
|
167
|
+
class PersonalPromise<T> extends Promise<T> {
|
|
168
|
+
static override get [Symbol.species]() {
|
|
169
|
+
return Promise
|
|
170
|
+
}
|
|
171
|
+
// biome-ignore lint/suspicious/noThenProperty: marking the read is the point of it.
|
|
172
|
+
override then<A = T, B = never>(
|
|
173
|
+
onFulfilled?: ((value: T) => A | PromiseLike<A>) | null,
|
|
174
|
+
onRejected?: ((reason: unknown) => B | PromiseLike<B>) | null,
|
|
175
|
+
): Promise<A | B> {
|
|
176
|
+
markPersonal()
|
|
177
|
+
return super.then(onFulfilled, onRejected)
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function personalPromise(query: SearchParams): Promise<SearchParams> {
|
|
182
|
+
return new PersonalPromise<SearchParams>((resolve) => resolve(query))
|
|
106
183
|
}
|
|
107
184
|
|
|
108
185
|
/**
|
|
@@ -126,6 +203,7 @@ export class Renderer {
|
|
|
126
203
|
#modules = new Map<string, ComponentModule>()
|
|
127
204
|
#importedFrom: string | undefined
|
|
128
205
|
#renderTimeoutMs: number
|
|
206
|
+
#islandsManifest: (generation: string | undefined) => string | undefined
|
|
129
207
|
|
|
130
208
|
constructor(options: RenderOptions) {
|
|
131
209
|
this.#cache = options.cache
|
|
@@ -134,6 +212,9 @@ export class Renderer {
|
|
|
134
212
|
this.#componentsDir = resolve(options.componentsDir)
|
|
135
213
|
this.#snapshots = options.snapshots
|
|
136
214
|
this.#renderTimeoutMs = options.renderTimeoutMs ?? DEFAULT_RENDER_TIMEOUT_MS
|
|
215
|
+
this.#islandsManifest =
|
|
216
|
+
options.islandsManifest ??
|
|
217
|
+
((generation) => (generation ? `${ISLANDS_PATH}/${generation}/manifest.json` : undefined))
|
|
137
218
|
}
|
|
138
219
|
|
|
139
220
|
/**
|
|
@@ -177,8 +258,11 @@ export class Renderer {
|
|
|
177
258
|
// `..`, an absolute path and a drive letter are all refused while
|
|
178
259
|
// `pages/homePage` resolves.
|
|
179
260
|
if (!isSafeComponentAlias(alias)) return undefined
|
|
180
|
-
const
|
|
181
|
-
|
|
261
|
+
const dir = this.#importDir()
|
|
262
|
+
// A template may be a folder, as a Next.js route is, so its partials sit beside it.
|
|
263
|
+
for (const file of [join(dir, `${alias}.tsx`), join(dir, alias, 'page.tsx')])
|
|
264
|
+
if (existsSync(file)) return file
|
|
265
|
+
return undefined
|
|
182
266
|
}
|
|
183
267
|
|
|
184
268
|
/**
|
|
@@ -209,14 +293,7 @@ export class Renderer {
|
|
|
209
293
|
const content = permitted
|
|
210
294
|
if (!content.componentAlias) return { status: 'noTemplate', content }
|
|
211
295
|
|
|
212
|
-
|
|
213
|
-
const html = await this.#renderContent(content, content.componentAlias, culture, request)
|
|
214
|
-
return html === undefined
|
|
215
|
-
? { status: 'noTemplate', content }
|
|
216
|
-
: { status: 'ok', html, content }
|
|
217
|
-
} catch (error) {
|
|
218
|
-
return { status: 'error', error: error as Error, content }
|
|
219
|
-
}
|
|
296
|
+
return this.#renderPage(content, content.componentAlias, culture, request)
|
|
220
297
|
}
|
|
221
298
|
|
|
222
299
|
/**
|
|
@@ -252,12 +329,25 @@ export class Renderer {
|
|
|
252
329
|
request: RenderRequest = {},
|
|
253
330
|
): Promise<RenderResult> {
|
|
254
331
|
if (!content.componentAlias) return { status: 'noTemplate', content }
|
|
332
|
+
return this.#renderPage(content, content.componentAlias, culture, request)
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
async #renderPage(
|
|
336
|
+
content: PublishedContent,
|
|
337
|
+
alias: string,
|
|
338
|
+
culture: string | null,
|
|
339
|
+
request: RenderRequest,
|
|
340
|
+
): Promise<RenderResult> {
|
|
341
|
+
const caching: RenderedCaching = { personal: false }
|
|
255
342
|
try {
|
|
256
|
-
const html = await this.#
|
|
343
|
+
const html = await this.#withDeadline(alias, request.signal, (signal, rendering) =>
|
|
344
|
+
this.#renderChain(content, alias, culture, request, signal, rendering, caching),
|
|
345
|
+
)
|
|
257
346
|
return html === undefined
|
|
258
347
|
? { status: 'noTemplate', content }
|
|
259
|
-
: { status: 'ok', html, content }
|
|
348
|
+
: { status: 'ok', html, content, ...caching }
|
|
260
349
|
} catch (error) {
|
|
350
|
+
if (isOutcome(error)) return { status: 'outcome', outcome: error, content, ...caching }
|
|
261
351
|
return { status: 'error', error: error as Error, content }
|
|
262
352
|
}
|
|
263
353
|
}
|
|
@@ -283,6 +373,16 @@ export class Renderer {
|
|
|
283
373
|
|
|
284
374
|
/** `The e-mail template 'x' failed at components/x.tsx:12: <what it threw>`. */
|
|
285
375
|
#emailFailure(alias: string, error: unknown): string {
|
|
376
|
+
const { message, location } = this.describeError(error)
|
|
377
|
+
return `The e-mail template '${alias}' failed${location ? ` at ${location}` : ''}: ${message}`
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* What a template threw, for a person to act on: its message, the first line
|
|
382
|
+
* under `components/` it failed on, and the stack, all naming files somebody
|
|
383
|
+
* can open.
|
|
384
|
+
*/
|
|
385
|
+
describeError(error: unknown): { message: string; location?: string; stack: string } {
|
|
286
386
|
const root = `${this.#componentsDir}${sep}`
|
|
287
387
|
const shown = `${basename(this.#componentsDir)}/`
|
|
288
388
|
const readable = (text: string) => this.inSource(text).replaceAll(root, shown)
|
|
@@ -290,18 +390,7 @@ export class Renderer {
|
|
|
290
390
|
const stack = error instanceof Error ? readable(error.stack ?? '') : ''
|
|
291
391
|
const escaped = shown.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
292
392
|
const frame = new RegExp(`${escaped}[^\\s:()]+\\.[jt]sx?:\\d+`).exec(stack)
|
|
293
|
-
return
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
async #renderContent(
|
|
297
|
-
content: PublishedContent,
|
|
298
|
-
alias: string,
|
|
299
|
-
culture: string | null,
|
|
300
|
-
request: RenderRequest = {},
|
|
301
|
-
): Promise<string | undefined> {
|
|
302
|
-
return this.#withDeadline(alias, request.signal, (signal, rendering) =>
|
|
303
|
-
this.#renderChain(content, alias, culture, request, signal, rendering),
|
|
304
|
-
)
|
|
393
|
+
return frame ? { message, location: frame[0], stack } : { message, stack }
|
|
305
394
|
}
|
|
306
395
|
|
|
307
396
|
/** Runs a render under the time limit; the signal it hands on aborts when that runs out. */
|
|
@@ -348,7 +437,17 @@ export class Renderer {
|
|
|
348
437
|
request: RenderRequest,
|
|
349
438
|
signal: AbortSignal,
|
|
350
439
|
rendering: { alias: string },
|
|
440
|
+
caching: RenderedCaching,
|
|
351
441
|
): Promise<string | undefined> {
|
|
442
|
+
const page = await this.#load(alias)
|
|
443
|
+
if (!page) return undefined
|
|
444
|
+
const dynamic = page.dynamic ?? 'auto'
|
|
445
|
+
const shared = dynamic === 'force-static'
|
|
446
|
+
if (typeof page.revalidate === 'number' || page.revalidate === false)
|
|
447
|
+
caching.revalidate = page.revalidate
|
|
448
|
+
// A static page reads nothing of the request, so what it marks is thrown away.
|
|
449
|
+
const personal = { value: dynamic === 'force-dynamic' }
|
|
450
|
+
const member = shared ? undefined : request.member
|
|
352
451
|
const nav = await this.#cache.navigation(culture)
|
|
353
452
|
const snapshot = await this.#cache.snapshot()
|
|
354
453
|
const dictionary = (key: string) => translate(snapshot, key, culture)
|
|
@@ -363,9 +462,13 @@ export class Renderer {
|
|
|
363
462
|
culture,
|
|
364
463
|
dictionary,
|
|
365
464
|
menu,
|
|
366
|
-
member
|
|
465
|
+
member,
|
|
367
466
|
submission: request.submission,
|
|
368
467
|
request: { origin, url: request.url ?? `${origin}/` },
|
|
468
|
+
searchParams: shared
|
|
469
|
+
? Promise.resolve({})
|
|
470
|
+
: personalPromise(queryOf(request.url ?? `${origin}/`)),
|
|
471
|
+
outcome: request.outcome,
|
|
369
472
|
urls: {
|
|
370
473
|
absolute: (target) => absoluteUrl(target.url, origin),
|
|
371
474
|
alternates: (target) => urlsIn(snapshot, target.key),
|
|
@@ -374,13 +477,37 @@ export class Renderer {
|
|
|
374
477
|
signal,
|
|
375
478
|
}
|
|
376
479
|
|
|
480
|
+
const metadata: { value?: Metadata } = {}
|
|
481
|
+
const islands = { used: false }
|
|
377
482
|
// Inside the page's scope, so any component can ask for it with `usePage()`.
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
483
|
+
try {
|
|
484
|
+
const html = await renderScope(
|
|
485
|
+
props,
|
|
486
|
+
async () => {
|
|
487
|
+
if (page.generateMetadata) metadata.value = await page.generateMetadata(props)
|
|
488
|
+
return this.#renderLayouts(alias, props, rendering)
|
|
489
|
+
},
|
|
490
|
+
{
|
|
491
|
+
search: request.search,
|
|
492
|
+
preview: request.preview,
|
|
493
|
+
antiforgery: request.antiforgery,
|
|
494
|
+
blockComponent: (blockAlias) => this.blockComponent(blockAlias),
|
|
495
|
+
request: { headers: shared ? new Headers() : (request.headers ?? new Headers()) },
|
|
496
|
+
site: request.site,
|
|
497
|
+
personal: shared ? { value: false } : personal,
|
|
498
|
+
metadata,
|
|
499
|
+
islands,
|
|
500
|
+
},
|
|
501
|
+
)
|
|
502
|
+
if (html === undefined || !islands.used) return html
|
|
503
|
+
// The generation the views were imported from, so the page loads the code built with them.
|
|
504
|
+
const manifest = this.#islandsManifest(
|
|
505
|
+
this.#importedFrom && this.#snapshots ? basename(this.#importedFrom) : undefined,
|
|
506
|
+
)
|
|
507
|
+
return manifest ? withIslandTags(html, manifest) : html
|
|
508
|
+
} finally {
|
|
509
|
+
caching.personal = !shared && (personal.value || member !== undefined)
|
|
510
|
+
}
|
|
384
511
|
}
|
|
385
512
|
|
|
386
513
|
/** Generic over its props: a page's, or an e-mail's. */
|
package/src/seo.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* editor's preview both call it, so what an editor is shown is what is served.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
+
import { currentMetadata } from './context.ts'
|
|
9
10
|
import { RawHtml } from './html.ts'
|
|
10
11
|
import { element } from './jsx-runtime.ts'
|
|
11
12
|
import type { PublishedContent } from './model.ts'
|
|
@@ -43,8 +44,24 @@ export interface SeoOverrides {
|
|
|
43
44
|
noindex?: boolean
|
|
44
45
|
}
|
|
45
46
|
|
|
47
|
+
/**
|
|
48
|
+
* What a page's `generateMetadata` returns (story 206): the part of Next.js's
|
|
49
|
+
* `Metadata` that `<SeoHead>` writes. Each value given wins over the page's own.
|
|
50
|
+
*/
|
|
51
|
+
export interface Metadata {
|
|
52
|
+
title?: string
|
|
53
|
+
description?: string
|
|
54
|
+
alternates?: {
|
|
55
|
+
canonical?: string
|
|
56
|
+
/** Addresses by culture, replacing the page's language versions. */
|
|
57
|
+
languages?: Record<string, string>
|
|
58
|
+
}
|
|
59
|
+
robots?: string | { index?: boolean }
|
|
60
|
+
openGraph?: { images?: string | { url: string } | Array<string | { url: string }> }
|
|
61
|
+
}
|
|
62
|
+
|
|
46
63
|
/** Where a value came from: the page's own field, the template, the site, or the page name. */
|
|
47
|
-
export type MetaSource = 'page' | 'template' | 'site' | 'name' | 'none'
|
|
64
|
+
export type MetaSource = 'page' | 'metadata' | 'template' | 'site' | 'name' | 'none'
|
|
48
65
|
|
|
49
66
|
export interface MetaValue<T> {
|
|
50
67
|
value: T
|
|
@@ -103,6 +120,50 @@ export async function effectiveMeta(
|
|
|
103
120
|
content: PublishedContent,
|
|
104
121
|
context: MetaContext,
|
|
105
122
|
overrides: SeoOverrides = {},
|
|
123
|
+
metadata: Metadata = {},
|
|
124
|
+
): Promise<EffectiveMeta> {
|
|
125
|
+
const meta = await pageMeta(content, context, overrides)
|
|
126
|
+
return withMetadata(meta, metadata, context.origin)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function firstImage(images: NonNullable<Metadata['openGraph']>['images']): string | undefined {
|
|
130
|
+
const first = Array.isArray(images) ? images[0] : images
|
|
131
|
+
return typeof first === 'string' ? first : first?.url
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** A page's values with what its `generateMetadata` returned laid over them. Pure. */
|
|
135
|
+
function withMetadata(meta: EffectiveMeta, metadata: Metadata, origin: string): EffectiveMeta {
|
|
136
|
+
const out = { ...meta }
|
|
137
|
+
if (filled(metadata.title)) {
|
|
138
|
+
const suffix = meta.fullTitle.slice(meta.title.value.length)
|
|
139
|
+
out.title = { value: metadata.title, source: 'metadata' }
|
|
140
|
+
out.fullTitle = `${metadata.title}${suffix}`
|
|
141
|
+
}
|
|
142
|
+
if (filled(metadata.description))
|
|
143
|
+
out.description = { value: metadata.description, source: 'metadata' }
|
|
144
|
+
const canonical = metadata.alternates?.canonical
|
|
145
|
+
if (filled(canonical))
|
|
146
|
+
out.canonical = { value: absoluteUrl(canonical, origin), source: 'metadata' }
|
|
147
|
+
const image = firstImage(metadata.openGraph?.images)
|
|
148
|
+
if (filled(image)) out.image = { value: absoluteUrl(image, origin), source: 'metadata' }
|
|
149
|
+
const robots = metadata.robots
|
|
150
|
+
const noindex = typeof robots === 'string' ? /\bnoindex\b/i.test(robots) : robots?.index === false
|
|
151
|
+
if (noindex && !meta.noindex.value) out.noindex = { value: true, source: 'metadata' }
|
|
152
|
+
const languages = metadata.alternates?.languages
|
|
153
|
+
if (languages) {
|
|
154
|
+
out.alternates = Object.entries(languages).flatMap(([culture, url]) => {
|
|
155
|
+
const absolute = absoluteUrl(url, origin)
|
|
156
|
+
return absolute && culture !== 'x-default' ? [{ culture, url: absolute }] : []
|
|
157
|
+
})
|
|
158
|
+
out.xDefault = languages['x-default'] ? absoluteUrl(languages['x-default'], origin) : undefined
|
|
159
|
+
}
|
|
160
|
+
return out
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function pageMeta(
|
|
164
|
+
content: PublishedContent,
|
|
165
|
+
context: MetaContext,
|
|
166
|
+
overrides: SeoOverrides,
|
|
106
167
|
): Promise<EffectiveMeta> {
|
|
107
168
|
const { origin, site } = context
|
|
108
169
|
const own = (alias: string) => content.text(alias).trim()
|
|
@@ -181,6 +242,7 @@ export async function SeoHead(props: SeoHeadProps): Promise<RawHtml> {
|
|
|
181
242
|
model,
|
|
182
243
|
{ origin: request.origin, alternates: urls.alternates(model), site: seo },
|
|
183
244
|
overrides,
|
|
245
|
+
currentMetadata(),
|
|
184
246
|
)
|
|
185
247
|
const tag = (name: string, attributes: Record<string, string | undefined>) =>
|
|
186
248
|
Object.values(attributes).some((v) => v === undefined) ? '' : element(name, attributes).value
|
package/src/site.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The site's own services, acting as whoever the page is rendering for
|
|
3
|
+
* (story 206). Each returns a `Result`; a component ends the chain with
|
|
4
|
+
* `unwrap()`. Reading anything personal makes the page personal.
|
|
5
|
+
*/
|
|
6
|
+
import { Outcome, type Result } from '@crombolo/core'
|
|
7
|
+
import { currentSite } from './context.ts'
|
|
8
|
+
import type { PublishedMedia } from './media.ts'
|
|
9
|
+
|
|
10
|
+
/** Media this visitor may read; anything else answers `notFound`, as `/media/` does. */
|
|
11
|
+
export interface SiteMedia {
|
|
12
|
+
get(key: string): Promise<Result<PublishedMedia, 404>>
|
|
13
|
+
/** A folder's items this visitor may read, in their order. */
|
|
14
|
+
children(folderKey: string): Promise<Result<PublishedMedia[], 404>>
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The site's own schema; filled by story 189. */
|
|
18
|
+
export interface SiteSql {
|
|
19
|
+
// biome-ignore lint/suspicious/noExplicitAny: a slot each site's own queries will type.
|
|
20
|
+
[query: string]: (...args: any[]) => Promise<Result<any>>
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Members, acting as the caller; filled by story 207. */
|
|
24
|
+
export interface SiteMembers {
|
|
25
|
+
// biome-ignore lint/suspicious/noExplicitAny: a slot story 207 will type.
|
|
26
|
+
[operation: string]: (...args: any[]) => Promise<Result<any>>
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface SiteServices {
|
|
30
|
+
media: SiteMedia
|
|
31
|
+
sql: SiteSql
|
|
32
|
+
members: SiteMembers
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The site's services as the visitor; only while a page renders. */
|
|
36
|
+
export function site(): SiteServices {
|
|
37
|
+
return currentSite('site()') as SiteServices
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A slot not filled yet: every call answers `notFound`, saying what is missing. */
|
|
41
|
+
export function unavailableServices<T extends object>(name: string): T {
|
|
42
|
+
return new Proxy({} as T, {
|
|
43
|
+
get: (_target, property) =>
|
|
44
|
+
typeof property === 'string' && property !== 'then'
|
|
45
|
+
? async () => Outcome.notFound(`site().${name}.${property} is not available on this site.`)
|
|
46
|
+
: undefined,
|
|
47
|
+
})
|
|
48
|
+
}
|
package/src/snapshots.ts
CHANGED
|
@@ -98,9 +98,24 @@ export interface SnapshotOptions {
|
|
|
98
98
|
* which is every boot and not an event worth reporting.
|
|
99
99
|
*/
|
|
100
100
|
onSwap?: (hash: string, previous: string | undefined) => void
|
|
101
|
+
/**
|
|
102
|
+
* What a file is written as instead of its own bytes, or undefined for those:
|
|
103
|
+
* a `'use client'` module becomes its island stub (story 209). The hash still
|
|
104
|
+
* covers the source, and the source is kept under `.islands/src/`.
|
|
105
|
+
*/
|
|
106
|
+
transform?: (key: string, bytes: Uint8Array) => Uint8Array | undefined
|
|
107
|
+
/**
|
|
108
|
+
* A generation is in place and about to be rendered: its browser code is
|
|
109
|
+
* built here, from the files the transform rewrote. A failure is reported,
|
|
110
|
+
* and the generation still serves.
|
|
111
|
+
*/
|
|
112
|
+
beforeSwap?: (generation: { dir: string; hash: string; transformed: string[] }) => Promise<void>
|
|
101
113
|
now?: () => number
|
|
102
114
|
}
|
|
103
115
|
|
|
116
|
+
/** Beside a generation's views: the client sources and their built browser code. */
|
|
117
|
+
export const ISLANDS_DIR = '.islands'
|
|
118
|
+
|
|
104
119
|
interface FileEntry {
|
|
105
120
|
/** Path relative to the source root, `/`-separated so a hash is portable. */
|
|
106
121
|
key: string
|
|
@@ -137,6 +152,8 @@ export class ViewSnapshots {
|
|
|
137
152
|
#limits: SnapshotLimits
|
|
138
153
|
#onProblem: (message: string) => void
|
|
139
154
|
#onSwap: (hash: string, previous: string | undefined) => void
|
|
155
|
+
#transform: SnapshotOptions['transform']
|
|
156
|
+
#beforeSwap: SnapshotOptions['beforeSwap']
|
|
140
157
|
#now: () => number
|
|
141
158
|
|
|
142
159
|
#current: { hash: string; dir: string } | undefined
|
|
@@ -159,6 +176,8 @@ export class ViewSnapshots {
|
|
|
159
176
|
this.#limits = { ...SNAPSHOT_LIMITS, ...options.limits }
|
|
160
177
|
this.#onProblem = options.onProblem ?? (() => {})
|
|
161
178
|
this.#onSwap = options.onSwap ?? (() => {})
|
|
179
|
+
this.#transform = options.transform
|
|
180
|
+
this.#beforeSwap = options.beforeSwap
|
|
162
181
|
this.#now = options.now ?? Date.now
|
|
163
182
|
if (!relative(this.#sourceDir, this.#cacheDir).startsWith('..')) {
|
|
164
183
|
throw new Error(
|
|
@@ -324,6 +343,7 @@ export class ViewSnapshots {
|
|
|
324
343
|
async #materialise(files: FileEntry[]): Promise<void> {
|
|
325
344
|
const partial = join(this.#cacheDir, `${PARTIAL}${crypto.randomUUID().slice(0, 8)}`)
|
|
326
345
|
const hasher = createHash('sha256')
|
|
346
|
+
const transformed: string[] = []
|
|
327
347
|
try {
|
|
328
348
|
mkdirSync(partial, { recursive: true })
|
|
329
349
|
for (const file of files) {
|
|
@@ -333,7 +353,14 @@ export class ViewSnapshots {
|
|
|
333
353
|
hasher.update('\n')
|
|
334
354
|
const target = join(partial, ...file.key.split('/'))
|
|
335
355
|
mkdirSync(join(target, '..'), { recursive: true })
|
|
336
|
-
|
|
356
|
+
const written = this.#transform?.(file.key, bytes)
|
|
357
|
+
if (written) {
|
|
358
|
+
transformed.push(file.key)
|
|
359
|
+
const kept = join(partial, ISLANDS_DIR, 'src', ...file.key.split('/'))
|
|
360
|
+
mkdirSync(join(kept, '..'), { recursive: true })
|
|
361
|
+
writeFileSync(kept, bytes)
|
|
362
|
+
}
|
|
363
|
+
writeFileSync(target, written ?? bytes)
|
|
337
364
|
}
|
|
338
365
|
const hash = hasher.digest('hex').slice(0, 16)
|
|
339
366
|
|
|
@@ -357,6 +384,10 @@ export class ViewSnapshots {
|
|
|
357
384
|
const dir = join(this.#cacheDir, hash)
|
|
358
385
|
if (existsSync(dir)) rmSync(partial, { recursive: true, force: true })
|
|
359
386
|
else renameSync(partial, dir)
|
|
387
|
+
if (this.#beforeSwap)
|
|
388
|
+
await this.#beforeSwap({ dir, hash, transformed }).catch((error: unknown) =>
|
|
389
|
+
this.#problem(`Could not build the islands for these views: ${String(error)}`),
|
|
390
|
+
)
|
|
360
391
|
|
|
361
392
|
const previous = this.#current?.hash
|
|
362
393
|
this.#current = { hash, dir }
|