@crombolo/render 0.45.0 → 0.47.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 +3 -3
- package/src/assets.ts +44 -0
- package/src/cache-policy.ts +189 -28
- package/src/context.ts +24 -3
- package/src/deferred.ts +179 -0
- package/src/index.ts +2 -0
- package/src/islands.ts +35 -7
- package/src/published-cache.ts +3 -0
- package/src/renderer.ts +110 -12
- package/src/snapshots.ts +13 -1
- package/src/values.ts +22 -3
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crombolo/render",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.47.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",
|
|
@@ -34,8 +34,8 @@
|
|
|
34
34
|
"access": "public"
|
|
35
35
|
},
|
|
36
36
|
"dependencies": {
|
|
37
|
-
"@crombolo/common": "0.
|
|
38
|
-
"@crombolo/core": "0.
|
|
37
|
+
"@crombolo/common": "0.47.0",
|
|
38
|
+
"@crombolo/core": "0.47.0",
|
|
39
39
|
"@types/react": "^19.3.0"
|
|
40
40
|
}
|
|
41
41
|
}
|
package/src/assets.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stylesheets and scripts at addresses that change with their content (story
|
|
3
|
+
* 260): `/css/site.css` is also `/css/site.<hash>.css`, kept for a year, and
|
|
4
|
+
* `asset()` gives a template the hashed address of the file as it is now.
|
|
5
|
+
* docs/rendering.md, "Stylesheets and scripts".
|
|
6
|
+
*/
|
|
7
|
+
import { createHash } from 'node:crypto'
|
|
8
|
+
|
|
9
|
+
/** The first eight characters of a SHA-256 over the bytes. Pure. */
|
|
10
|
+
export function contentHash(body: string | Uint8Array): string {
|
|
11
|
+
return createHash('sha256').update(body).digest('hex').slice(0, 8)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** `/css/site.css` with a hash: `/css/site.3f9a1c2b.css`. Pure. */
|
|
15
|
+
export function hashedAddress(path: string, hash: string): string {
|
|
16
|
+
const dot = path.lastIndexOf('.')
|
|
17
|
+
const slash = path.lastIndexOf('/')
|
|
18
|
+
return dot > slash + 1 ? `${path.slice(0, dot)}.${hash}${path.slice(dot)}` : `${path}.${hash}`
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The plain address and the hash in a hashed one, or undefined when it has none. Pure. */
|
|
22
|
+
export function splitHashedAddress(path: string): { path: string; hash: string } | undefined {
|
|
23
|
+
const match = /^(.*\/[^/]+)\.([0-9a-f]{8})(\.[A-Za-z0-9]+)$/.exec(path)
|
|
24
|
+
return match ? { path: `${match[1]}${match[3]}`, hash: match[2] as string } : undefined
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
type AssetResolver = (path: string) => string
|
|
28
|
+
|
|
29
|
+
const KEY = Symbol.for('crombolo.assets')
|
|
30
|
+
const shared = globalThis as Record<symbol, AssetResolver | undefined>
|
|
31
|
+
|
|
32
|
+
/** What `asset()` asks: the server's, which knows the site's files. */
|
|
33
|
+
export function setAssetResolver(resolve: AssetResolver | undefined): void {
|
|
34
|
+
shared[KEY] = resolve
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The address to link a stylesheet or script by: `asset('/css/site.css')` is
|
|
39
|
+
* `/css/site.3f9a1c2b.css` while the file is as it is now. A file the site
|
|
40
|
+
* does not have keeps its plain address, and development says so.
|
|
41
|
+
*/
|
|
42
|
+
export function asset(path: string): string {
|
|
43
|
+
return shared[KEY]?.(path) ?? path
|
|
44
|
+
}
|
package/src/cache-policy.ts
CHANGED
|
@@ -7,27 +7,68 @@
|
|
|
7
7
|
import { CACHE_KEEP_FOR_ALIAS, KEEP_COPIES_FOR } from '@crombolo/core'
|
|
8
8
|
|
|
9
9
|
export interface CacheLifetimeOptions {
|
|
10
|
-
/** Seconds a copy may be reused; 0 keeps none
|
|
10
|
+
/** Seconds a copy may be reused; 0 keeps none, unless the mode is `check`. */
|
|
11
11
|
maxAge?: number
|
|
12
12
|
/** Seconds a stale copy may still be served while a fresh one is fetched. */
|
|
13
13
|
staleWhileRevalidate?: number
|
|
14
|
+
/** Seconds a stale copy may still be served while the site answers with an error (story 259). */
|
|
15
|
+
staleIfError?: number
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* How copies are kept (story 259): for the lifetime given, or, with `check`,
|
|
20
|
+
* kept and checked back with the site before each use, served while checking
|
|
21
|
+
* and while the site is down.
|
|
22
|
+
*/
|
|
23
|
+
export type CacheMode = 'lifetime' | 'check'
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* What an ETag is worked out from (story 258): the body, after rendering, or
|
|
27
|
+
* what was published, which a cache's check is answered from without rendering.
|
|
28
|
+
*/
|
|
29
|
+
export type Validator = 'published' | 'body'
|
|
30
|
+
|
|
31
|
+
export interface CacheTypeOptions extends CacheLifetimeOptions {
|
|
32
|
+
validator?: Validator
|
|
14
33
|
}
|
|
15
34
|
|
|
16
35
|
export interface CacheOptions extends CacheLifetimeOptions {
|
|
17
36
|
/** By content or media type alias, winning over the site's. */
|
|
18
|
-
types?: Record<string,
|
|
37
|
+
types?: Record<string, CacheTypeOptions>
|
|
19
38
|
/** The header a CDN reads purge tags from, such as `Surrogate-Key` or `Cache-Tag`. */
|
|
20
39
|
tagHeader?: string
|
|
40
|
+
/** `body` unless set: a page that reads the clock changes with no publish. */
|
|
41
|
+
validator?: Validator
|
|
42
|
+
/** `lifetime` unless set. */
|
|
43
|
+
mode?: CacheMode
|
|
44
|
+
/** With `check`, the seconds a copy whose ETag is over its body is kept before checking: a minute. */
|
|
45
|
+
checkFloor?: number
|
|
21
46
|
}
|
|
22
47
|
|
|
23
48
|
export interface CacheSettings {
|
|
24
49
|
site: Lifetime
|
|
25
50
|
types: ReadonlyMap<string, Lifetime>
|
|
26
51
|
tagHeader: string | undefined
|
|
52
|
+
validator: Validator
|
|
53
|
+
validators: ReadonlyMap<string, Validator>
|
|
54
|
+
mode: CacheMode
|
|
55
|
+
checkFloor: number
|
|
56
|
+
/** What "Keep copies for" and a template's `revalidate` are served stale for on an error. */
|
|
57
|
+
staleIfError: number
|
|
27
58
|
}
|
|
28
59
|
|
|
29
|
-
/**
|
|
30
|
-
|
|
60
|
+
/**
|
|
61
|
+
* Kept this long, or not kept (`none`), or nothing said (`undefined`). A
|
|
62
|
+
* `check` lifetime's `maxAge` is 0, or the floor for an ETag over the body.
|
|
63
|
+
*/
|
|
64
|
+
export type Lifetime =
|
|
65
|
+
| { maxAge: number; staleWhileRevalidate?: number; staleIfError?: number; check?: boolean }
|
|
66
|
+
| 'none'
|
|
67
|
+
| undefined
|
|
68
|
+
|
|
69
|
+
const DAY = 86_400
|
|
70
|
+
const WEEK = 604_800
|
|
71
|
+
const CHECK_FLOOR = 60
|
|
31
72
|
|
|
32
73
|
/** What every answer that depends on who is asking carries, whatever is configured. */
|
|
33
74
|
export const PRIVATE_NO_STORE = 'private, no-store'
|
|
@@ -35,41 +76,87 @@ export const PRIVATE_NO_STORE = 'private, no-store'
|
|
|
35
76
|
const seconds = (value: unknown): number | undefined =>
|
|
36
77
|
typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.floor(value) : undefined
|
|
37
78
|
|
|
38
|
-
function lifetimeOf(
|
|
79
|
+
function lifetimeOf(
|
|
80
|
+
options: CacheLifetimeOptions | undefined,
|
|
81
|
+
mode: CacheMode = 'lifetime',
|
|
82
|
+
): Lifetime {
|
|
39
83
|
const maxAge = seconds(options?.maxAge)
|
|
40
|
-
if (maxAge === undefined) return undefined
|
|
41
|
-
if (maxAge === 0) return 'none'
|
|
42
84
|
const swr = seconds(options?.staleWhileRevalidate)
|
|
43
|
-
|
|
85
|
+
// A copy kept for any time is served for a week if the site fails, unless told otherwise.
|
|
86
|
+
const sie = seconds(options?.staleIfError) ?? WEEK
|
|
87
|
+
if (maxAge === undefined) {
|
|
88
|
+
if (mode !== 'check') return undefined
|
|
89
|
+
return { maxAge: 0, staleWhileRevalidate: swr ?? DAY, staleIfError: sie, check: true }
|
|
90
|
+
}
|
|
91
|
+
if (maxAge === 0 && mode !== 'check') return 'none'
|
|
92
|
+
return {
|
|
93
|
+
maxAge,
|
|
94
|
+
...(swr ? { staleWhileRevalidate: swr } : {}),
|
|
95
|
+
...(sie ? { staleIfError: sie } : {}),
|
|
96
|
+
}
|
|
44
97
|
}
|
|
45
98
|
|
|
46
99
|
/** The settings with what cannot be used dropped. Pure. */
|
|
47
100
|
export function resolveCacheSettings(options: CacheOptions = {}): CacheSettings {
|
|
101
|
+
const mode: CacheMode = options.mode === 'check' ? 'check' : 'lifetime'
|
|
48
102
|
const types = new Map<string, Lifetime>()
|
|
103
|
+
const validators = new Map<string, Validator>()
|
|
49
104
|
for (const [alias, own] of Object.entries(options.types ?? {})) {
|
|
50
|
-
|
|
105
|
+
if (isValidator(own.validator)) validators.set(alias.toLowerCase(), own.validator)
|
|
106
|
+
const inherited = {
|
|
51
107
|
staleWhileRevalidate: options.staleWhileRevalidate,
|
|
108
|
+
staleIfError: options.staleIfError,
|
|
52
109
|
...own,
|
|
53
|
-
}
|
|
110
|
+
}
|
|
111
|
+
// In `check`, a type naming only how long stale copies last is checked with those.
|
|
112
|
+
const lifetime =
|
|
113
|
+
mode === 'check' && own.maxAge === undefined && !own.staleWhileRevalidate && !own.staleIfError
|
|
114
|
+
? undefined
|
|
115
|
+
: lifetimeOf(inherited, mode)
|
|
54
116
|
if (lifetime) types.set(alias.toLowerCase(), lifetime)
|
|
55
117
|
}
|
|
56
118
|
const tagHeader = options.tagHeader?.trim()
|
|
57
119
|
return {
|
|
58
|
-
|
|
120
|
+
mode,
|
|
121
|
+
checkFloor: seconds(options.checkFloor) ?? CHECK_FLOOR,
|
|
122
|
+
staleIfError: seconds(options.staleIfError) ?? WEEK,
|
|
123
|
+
site: lifetimeOf(options, mode),
|
|
59
124
|
types,
|
|
60
125
|
tagHeader: tagHeader && /^[A-Za-z0-9-]+$/.test(tagHeader) ? tagHeader : undefined,
|
|
126
|
+
validator: isValidator(options.validator) ? options.validator : 'body',
|
|
127
|
+
validators,
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const isValidator = (value: unknown): value is Validator =>
|
|
132
|
+
value === 'published' || value === 'body'
|
|
133
|
+
|
|
134
|
+
/** The validator for an answer holding these types: `published` only when every one is. Pure. */
|
|
135
|
+
export function validatorFor(settings: CacheSettings, typeAliases: Iterable<string>): Validator {
|
|
136
|
+
let any = false
|
|
137
|
+
for (const alias of typeAliases) {
|
|
138
|
+
any = true
|
|
139
|
+
if ((settings.validators.get(alias.toLowerCase()) ?? settings.validator) !== 'published')
|
|
140
|
+
return 'body'
|
|
61
141
|
}
|
|
142
|
+
return any ? 'published' : settings.validator
|
|
62
143
|
}
|
|
63
144
|
|
|
64
145
|
/** An editor's "Keep copies for" choice as a lifetime, or undefined for none chosen. Pure. */
|
|
65
|
-
export function chosenLifetime(
|
|
146
|
+
export function chosenLifetime(
|
|
147
|
+
value: unknown,
|
|
148
|
+
staleWhileRevalidate?: number,
|
|
149
|
+
staleIfError = WEEK,
|
|
150
|
+
): Lifetime {
|
|
66
151
|
const label = Array.isArray(value) ? value[0] : value
|
|
67
152
|
const choice = KEEP_COPIES_FOR.find((c) => c.label === label)
|
|
68
153
|
if (!choice) return undefined
|
|
69
154
|
if (choice.seconds === 0) return 'none'
|
|
70
|
-
return
|
|
71
|
-
|
|
72
|
-
|
|
155
|
+
return {
|
|
156
|
+
maxAge: choice.seconds,
|
|
157
|
+
...(staleWhileRevalidate ? { staleWhileRevalidate } : {}),
|
|
158
|
+
...(staleIfError ? { staleIfError } : {}),
|
|
159
|
+
}
|
|
73
160
|
}
|
|
74
161
|
|
|
75
162
|
/** Anything with a type and properties: a page, an element or a media item. */
|
|
@@ -90,7 +177,7 @@ export function lifetimeFor(
|
|
|
90
177
|
const swr =
|
|
91
178
|
settings.site && settings.site !== 'none' ? settings.site.staleWhileRevalidate : undefined
|
|
92
179
|
return (
|
|
93
|
-
chosenLifetime(item.value(CACHE_KEEP_FOR_ALIAS), swr) ??
|
|
180
|
+
chosenLifetime(item.value(CACHE_KEEP_FOR_ALIAS), swr, settings.staleIfError) ??
|
|
94
181
|
settings.types.get(item.typeAlias.toLowerCase()) ??
|
|
95
182
|
(options.site === false ? undefined : settings.site)
|
|
96
183
|
)
|
|
@@ -110,12 +197,18 @@ export function shortest(lifetimes: readonly Lifetime[], whenEmpty: Lifetime): L
|
|
|
110
197
|
}
|
|
111
198
|
|
|
112
199
|
/** The `Cache-Control` value for a public answer, or undefined to say nothing. Pure. */
|
|
113
|
-
export function cacheControl(lifetime: Lifetime): string | undefined {
|
|
200
|
+
export function cacheControl(lifetime: Lifetime, checkFloor?: number): string | undefined {
|
|
114
201
|
if (lifetime === undefined) return undefined
|
|
115
202
|
if (lifetime === 'none') return 'no-store'
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
203
|
+
// A check answered by rendering is kept a little first, so each cache renders a page once a floor.
|
|
204
|
+
const maxAge = lifetime.check && checkFloor !== undefined ? checkFloor : lifetime.maxAge
|
|
205
|
+
return [
|
|
206
|
+
`public, max-age=${maxAge}`,
|
|
207
|
+
...(lifetime.staleWhileRevalidate
|
|
208
|
+
? [`stale-while-revalidate=${lifetime.staleWhileRevalidate}`]
|
|
209
|
+
: []),
|
|
210
|
+
...(lifetime.staleIfError ? [`stale-if-error=${lifetime.staleIfError}`] : []),
|
|
211
|
+
].join(', ')
|
|
119
212
|
}
|
|
120
213
|
|
|
121
214
|
/** A weak validator over a body's bytes. */
|
|
@@ -123,6 +216,11 @@ export function etagFor(body: string | Uint8Array): string {
|
|
|
123
216
|
return `W/"${Bun.hash(body).toString(36)}"`
|
|
124
217
|
}
|
|
125
218
|
|
|
219
|
+
/** A weak validator over what an answer was made from, rather than its bytes. Pure. */
|
|
220
|
+
export function publishedEtag(parts: readonly (string | number | null | undefined)[]): string {
|
|
221
|
+
return `W/"p${Bun.hash(parts.map((part) => part ?? '').join('\u0000')).toString(36)}"`
|
|
222
|
+
}
|
|
223
|
+
|
|
126
224
|
/** Whether `If-None-Match` names this tag, or `*`. Pure. */
|
|
127
225
|
export function notModified(request: Request, etag: string): boolean {
|
|
128
226
|
const header = request.headers.get('if-none-match')
|
|
@@ -149,25 +247,88 @@ export function cacheable(
|
|
|
149
247
|
request: Request,
|
|
150
248
|
response: Response,
|
|
151
249
|
body: string | Uint8Array,
|
|
152
|
-
options: {
|
|
250
|
+
options: {
|
|
251
|
+
lifetime: Lifetime
|
|
252
|
+
tags?: Iterable<string>
|
|
253
|
+
tagHeader?: string
|
|
254
|
+
etag?: string
|
|
255
|
+
/** With `check`, how long a copy whose ETag is over its body is kept (story 259). */
|
|
256
|
+
checkFloor?: number
|
|
257
|
+
},
|
|
153
258
|
): Response {
|
|
154
259
|
const headers = new Headers(response.headers)
|
|
155
|
-
const control = cacheControl(options.lifetime)
|
|
260
|
+
const control = cacheControl(options.lifetime, options.etag ? undefined : options.checkFloor)
|
|
156
261
|
if (control) headers.set('cache-control', control)
|
|
157
|
-
const etag = etagFor(body)
|
|
262
|
+
const etag = options.etag ?? etagFor(body)
|
|
158
263
|
headers.set('etag', etag)
|
|
159
264
|
if (options.tagHeader && options.tags) {
|
|
160
265
|
const tags = tagValue(options.tagHeader, options.tags)
|
|
161
266
|
if (tags) headers.set(options.tagHeader, tags)
|
|
162
267
|
}
|
|
163
|
-
if (notModified(request, etag))
|
|
164
|
-
headers.delete('content-type')
|
|
165
|
-
headers.delete('content-length')
|
|
166
|
-
return new Response(null, { status: 304, headers })
|
|
167
|
-
}
|
|
268
|
+
if (notModified(request, etag)) return unchanged(headers)
|
|
168
269
|
return new Response(body as BodyInit, {
|
|
169
270
|
status: response.status,
|
|
170
271
|
statusText: response.statusText,
|
|
171
272
|
headers,
|
|
172
273
|
})
|
|
173
274
|
}
|
|
275
|
+
|
|
276
|
+
/** A `304` carrying the headers a `200` would, less the body's own. */
|
|
277
|
+
export function unchanged(headers: HeadersInit): Response {
|
|
278
|
+
const kept = new Headers(headers)
|
|
279
|
+
kept.delete('content-type')
|
|
280
|
+
kept.delete('content-length')
|
|
281
|
+
return new Response(null, { status: 304, headers: kept })
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** The ETag an address was last answered with, and what a `304` for it repeats. */
|
|
285
|
+
export interface RememberedAnswer {
|
|
286
|
+
etag: string
|
|
287
|
+
headers: [string, string][]
|
|
288
|
+
/** What a check must still find unchanged before it is answered. */
|
|
289
|
+
guard?: unknown
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* The last answer each address was given, so a check is answered without
|
|
294
|
+
* making it again (story 258). Held in memory by each server, the oldest
|
|
295
|
+
* dropped past `limit`; one not held renders once and is remembered.
|
|
296
|
+
*/
|
|
297
|
+
export class RememberedAnswers<T extends RememberedAnswer = RememberedAnswer> {
|
|
298
|
+
readonly #limit: number
|
|
299
|
+
readonly #answers = new Map<string, T>()
|
|
300
|
+
|
|
301
|
+
constructor(limit = 10_000) {
|
|
302
|
+
this.#limit = limit
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
get size(): number {
|
|
306
|
+
return this.#answers.size
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
get(address: string): T | undefined {
|
|
310
|
+
const answer = this.#answers.get(address)
|
|
311
|
+
if (!answer) return undefined
|
|
312
|
+
this.#answers.delete(address)
|
|
313
|
+
this.#answers.set(address, answer)
|
|
314
|
+
return answer
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
set(address: string, answer: T): void {
|
|
318
|
+
this.#answers.delete(address)
|
|
319
|
+
this.#answers.set(address, answer)
|
|
320
|
+
if (this.#answers.size > this.#limit)
|
|
321
|
+
this.#answers.delete(this.#answers.keys().next().value as string)
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
delete(address: string): void {
|
|
325
|
+
this.#answers.delete(address)
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** The headers a remembered answer repeats: the ETag, the lifetime and the purge tags. Pure. */
|
|
330
|
+
export function rememberedHeaders(headers: Headers, tagHeader?: string): [string, string][] {
|
|
331
|
+
return ['etag', 'cache-control', 'vary', ...(tagHeader ? [tagHeader.toLowerCase()] : [])]
|
|
332
|
+
.map((name) => [name, headers.get(name)] as const)
|
|
333
|
+
.filter((pair): pair is [string, string] => pair[1] !== null)
|
|
334
|
+
}
|
package/src/context.ts
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
13
13
|
import type { ActionState } from '@crombolo/common'
|
|
14
|
+
import type { DeferredScope } from './deferred.ts'
|
|
14
15
|
import type { Child } from './jsx-runtime.ts'
|
|
15
16
|
import type { PageProps } from './model.ts'
|
|
16
17
|
import type { SiteSearchPort } from './search.ts'
|
|
@@ -43,6 +44,8 @@ interface RenderScope {
|
|
|
43
44
|
islands?: { used: boolean }
|
|
44
45
|
/** The site's server actions, and what one answered the visitor just now (story 219). */
|
|
45
46
|
actions?: PageActions
|
|
47
|
+
/** How `'use deferred'` parts render here (story 263). */
|
|
48
|
+
deferred?: DeferredScope
|
|
46
49
|
}
|
|
47
50
|
|
|
48
51
|
/** A page's server actions: each one's id, and the result the visitor returned with. */
|
|
@@ -73,6 +76,7 @@ export interface RenderScopeOptions {
|
|
|
73
76
|
metadata?: { value?: Metadata }
|
|
74
77
|
islands?: { used: boolean }
|
|
75
78
|
actions?: PageActions
|
|
79
|
+
deferred?: DeferredScope
|
|
76
80
|
}
|
|
77
81
|
|
|
78
82
|
/**
|
|
@@ -169,7 +173,25 @@ export function actionFormFields(): { returnTo: string; antiforgery: string | un
|
|
|
169
173
|
const parsed = new URL(url, 'http://localhost')
|
|
170
174
|
returnTo = `${parsed.pathname}${parsed.search}`
|
|
171
175
|
}
|
|
172
|
-
return { returnTo, antiforgery: scope
|
|
176
|
+
return { returnTo, antiforgery: memberAntiforgery(scope) }
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** The member's token, which makes the page theirs. */
|
|
180
|
+
function memberAntiforgery(scope: RenderScope | undefined): string | undefined {
|
|
181
|
+
if (!scope?.page?.member || !scope.antiforgery) return undefined
|
|
182
|
+
if (scope.personal) scope.personal.value = true
|
|
183
|
+
return scope.antiforgery
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** How `'use deferred'` parts render in this one, if it is a page. */
|
|
187
|
+
export function currentDeferred(): DeferredScope | undefined {
|
|
188
|
+
return store.getStore()?.deferred
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** The page rendering and its culture, or undefined outside a page. */
|
|
192
|
+
export function currentPlace(): { key: string; culture: string | null } | undefined {
|
|
193
|
+
const page = store.getStore()?.page
|
|
194
|
+
return page ? { key: page.model.key, culture: page.culture } : undefined
|
|
173
195
|
}
|
|
174
196
|
|
|
175
197
|
/**
|
|
@@ -187,8 +209,7 @@ export function actionState<T = unknown>(action: unknown): ActionState<T> | unde
|
|
|
187
209
|
|
|
188
210
|
/** The signed-in member's anti-forgery token for this render, or undefined for a visitor. */
|
|
189
211
|
export function currentAntiforgery(): string | undefined {
|
|
190
|
-
|
|
191
|
-
return scope.page?.member ? scope.antiforgery : undefined
|
|
212
|
+
return memberAntiforgery(within('<AntiforgeryMeta />'))
|
|
192
213
|
}
|
|
193
214
|
|
|
194
215
|
/**
|
package/src/deferred.ts
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deferred parts (story 263). A view module whose first statement is
|
|
3
|
+
* `'use deferred'` renders in a request of its own, for the visitor: in the
|
|
4
|
+
* page it is a placeholder holding its `fallback`, so the page stays the same
|
|
5
|
+
* for everyone, and `/crombolo/deferred.js` fetches each part and puts it in.
|
|
6
|
+
* docs/rendering.md, "Deferred parts".
|
|
7
|
+
*/
|
|
8
|
+
import { basename } from 'node:path'
|
|
9
|
+
import { contentHash, hashedAddress } from './assets.ts'
|
|
10
|
+
import { currentDeferred, currentPlace } from './context.ts'
|
|
11
|
+
import { escapeHtml, RawHtml } from './html.ts'
|
|
12
|
+
import { hasDirective, serializeProps } from './islands.ts'
|
|
13
|
+
import { type Child, renderToString } from './jsx-runtime.ts'
|
|
14
|
+
import type { SnapshotTransform } from './snapshots.ts'
|
|
15
|
+
|
|
16
|
+
/** Where a part is rendered for the visitor. */
|
|
17
|
+
export const DEFERRED_PATH = '/crombolo/deferred'
|
|
18
|
+
/** The script every page with a part links to. */
|
|
19
|
+
export const DEFERRED_LOADER_PATH = '/crombolo/deferred.js'
|
|
20
|
+
|
|
21
|
+
/** What a render does with the parts it meets: placeholders, or, inside a part's own request, the parts. */
|
|
22
|
+
export interface DeferredScope {
|
|
23
|
+
inPart: boolean
|
|
24
|
+
/** Signs a placeholder's address, so a visitor cannot change what it renders. */
|
|
25
|
+
sign(data: string): string
|
|
26
|
+
/** Set once the page holds a placeholder, so the loader is linked. */
|
|
27
|
+
used: boolean
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** What a placeholder's address names. */
|
|
31
|
+
export interface DeferredRequest {
|
|
32
|
+
module: string
|
|
33
|
+
exportName: string
|
|
34
|
+
/** The page it sits on, for `usePage()`. */
|
|
35
|
+
key: string
|
|
36
|
+
culture: string | null
|
|
37
|
+
props: Record<string, unknown>
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function isDeferredModule(source: string): boolean {
|
|
41
|
+
return hasDirective(source, 'use deferred')
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Where a part's own source is kept in a snapshot, beside the stub that imports it. */
|
|
45
|
+
export function deferredSourceKey(key: string): string {
|
|
46
|
+
return key.replace(/(\.[jt]sx?)$/, '.deferred-source$1')
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function isDeferredSource(path: string): boolean {
|
|
50
|
+
return /\.deferred-source\.[jt]sx?$/.test(path)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const transpiler = new Bun.Transpiler({ loader: 'tsx' })
|
|
54
|
+
|
|
55
|
+
/** What a deferred module is written as in a snapshot: each export a placeholder, over the source beside it. */
|
|
56
|
+
export function deferredStub(key: string, source: string): string {
|
|
57
|
+
const { exports } = transpiler.scan(source)
|
|
58
|
+
const lines = [
|
|
59
|
+
`// The page half of ${key} ('use deferred', story 263).`,
|
|
60
|
+
`import * as part from ${JSON.stringify(`./${basename(deferredSourceKey(key))}`)}`,
|
|
61
|
+
]
|
|
62
|
+
for (const name of exports) {
|
|
63
|
+
const call = `(props) => globalThis[Symbol.for("crombolo.deferred")](${JSON.stringify(key)}, ${JSON.stringify(name)}, props, part[${JSON.stringify(name)}])`
|
|
64
|
+
lines.push(name === 'default' ? `export default ${call}` : `export const ${name} = ${call}`)
|
|
65
|
+
}
|
|
66
|
+
return `${lines.join('\n')}\n`
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const encoder = new TextEncoder()
|
|
70
|
+
const decoder = new TextDecoder()
|
|
71
|
+
|
|
72
|
+
/** The snapshot transform for a deferred module, or undefined for any other file. */
|
|
73
|
+
export function deferredTransform(key: string, bytes: Uint8Array): SnapshotTransform | undefined {
|
|
74
|
+
if (!/\.[jt]sx?$/.test(key)) return undefined
|
|
75
|
+
const source = decoder.decode(bytes)
|
|
76
|
+
if (!isDeferredModule(source)) return undefined
|
|
77
|
+
return { bytes: encoder.encode(deferredStub(key, source)), beside: deferredSourceKey(key) }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const base64url = (text: string) => Buffer.from(text, 'utf8').toString('base64url')
|
|
81
|
+
|
|
82
|
+
/** A part's address: what it renders, signed. */
|
|
83
|
+
export function deferredAddress(request: DeferredRequest, sign: (data: string) => string): string {
|
|
84
|
+
const data = base64url(
|
|
85
|
+
JSON.stringify({
|
|
86
|
+
m: request.module,
|
|
87
|
+
e: request.exportName,
|
|
88
|
+
k: request.key,
|
|
89
|
+
c: request.culture,
|
|
90
|
+
p: request.props,
|
|
91
|
+
}),
|
|
92
|
+
)
|
|
93
|
+
return `${DEFERRED_PATH}?d=${data}&s=${sign(data)}`
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** What a part's address names, or undefined when it was not signed here. */
|
|
97
|
+
export function readDeferredAddress(
|
|
98
|
+
search: URLSearchParams,
|
|
99
|
+
verify: (data: string, signature: string) => boolean,
|
|
100
|
+
): DeferredRequest | undefined {
|
|
101
|
+
const data = search.get('d')
|
|
102
|
+
const signature = search.get('s')
|
|
103
|
+
if (!data || !signature || !verify(data, signature)) return undefined
|
|
104
|
+
try {
|
|
105
|
+
const parsed = JSON.parse(Buffer.from(data, 'base64url').toString('utf8'))
|
|
106
|
+
if (
|
|
107
|
+
typeof parsed.m !== 'string' ||
|
|
108
|
+
typeof parsed.e !== 'string' ||
|
|
109
|
+
typeof parsed.k !== 'string'
|
|
110
|
+
)
|
|
111
|
+
return undefined
|
|
112
|
+
return {
|
|
113
|
+
module: parsed.m,
|
|
114
|
+
exportName: parsed.e,
|
|
115
|
+
key: parsed.k,
|
|
116
|
+
culture: typeof parsed.c === 'string' ? parsed.c : null,
|
|
117
|
+
props: parsed.p && typeof parsed.p === 'object' ? parsed.p : {},
|
|
118
|
+
}
|
|
119
|
+
} catch {
|
|
120
|
+
return undefined
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
type PartComponent = (props: Record<string, unknown>) => Child
|
|
125
|
+
|
|
126
|
+
/** What a deferred module's stub calls: the placeholder, or the part itself in its own request. */
|
|
127
|
+
async function renderDeferred(
|
|
128
|
+
module: string,
|
|
129
|
+
exportName: string,
|
|
130
|
+
props: Record<string, unknown> | undefined,
|
|
131
|
+
component: PartComponent | undefined,
|
|
132
|
+
): Promise<RawHtml> {
|
|
133
|
+
if (typeof component !== 'function')
|
|
134
|
+
throw new Error(`${module} has no export "${exportName}" a page can render.`)
|
|
135
|
+
const { fallback, ...rest } = props ?? {}
|
|
136
|
+
const scope = currentDeferred()
|
|
137
|
+
const place = currentPlace()
|
|
138
|
+
// Outside a page, or with nobody to sign for it, the part renders where it is, as any view.
|
|
139
|
+
if (!scope || scope.inPart || !place)
|
|
140
|
+
return new RawHtml(await renderToString(component(rest as Record<string, unknown>)))
|
|
141
|
+
const json = serializeProps(rest, module, 'part')
|
|
142
|
+
const src = deferredAddress(
|
|
143
|
+
{ module, exportName, key: place.key, culture: place.culture, props: JSON.parse(json) },
|
|
144
|
+
scope.sign,
|
|
145
|
+
)
|
|
146
|
+
scope.used = true
|
|
147
|
+
const shown =
|
|
148
|
+
fallback === undefined || fallback === null ? '' : await renderToString(fallback as Child)
|
|
149
|
+
return new RawHtml(`<crombolo-deferred src="${escapeHtml(src)}">${shown}</crombolo-deferred>`)
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const KEY = Symbol.for('crombolo.deferred')
|
|
153
|
+
;(globalThis as Record<symbol, unknown>)[KEY] ??= renderDeferred
|
|
154
|
+
|
|
155
|
+
/** Fetches each part with the visitor's cookies and puts it in place of its fallback. */
|
|
156
|
+
export const DEFERRED_LOADER = `for (const part of document.querySelectorAll('crombolo-deferred[src]')) {
|
|
157
|
+
const src = part.getAttribute('src')
|
|
158
|
+
part.removeAttribute('src')
|
|
159
|
+
fetch(src, { credentials: 'same-origin', headers: { accept: 'text/html' } })
|
|
160
|
+
.then((response) => (response.ok ? response.text() : undefined))
|
|
161
|
+
.then((html) => {
|
|
162
|
+
if (html === undefined) return
|
|
163
|
+
const template = document.createElement('template')
|
|
164
|
+
template.innerHTML = html
|
|
165
|
+
part.replaceChildren(template.content)
|
|
166
|
+
part.dispatchEvent(new CustomEvent('crombolo:deferred', { bubbles: true }))
|
|
167
|
+
})
|
|
168
|
+
.catch(() => {})
|
|
169
|
+
}
|
|
170
|
+
`
|
|
171
|
+
|
|
172
|
+
/** The loader's address while its script is as it is now (story 260). */
|
|
173
|
+
export const DEFERRED_LOADER_ADDRESS = hashedAddress(
|
|
174
|
+
DEFERRED_LOADER_PATH,
|
|
175
|
+
contentHash(DEFERRED_LOADER),
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
/** The tag a page with a part ends with. */
|
|
179
|
+
export const DEFERRED_TAGS = `<script type="module" src="${DEFERRED_LOADER_ADDRESS}"></script>`
|
package/src/index.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
export * from './assets.ts'
|
|
1
2
|
export * from './blocks.ts'
|
|
2
3
|
export * from './bundle-script.ts'
|
|
3
4
|
export * from './cache-policy.ts'
|
|
4
5
|
export * from './component-stack.ts'
|
|
5
6
|
export * from './context.ts'
|
|
7
|
+
export * from './deferred.ts'
|
|
6
8
|
export * from './email.ts'
|
|
7
9
|
export * from './excerpt.ts'
|
|
8
10
|
export * from './form-script.ts'
|
package/src/islands.ts
CHANGED
|
@@ -6,8 +6,11 @@
|
|
|
6
6
|
* generation, and `/crombolo/islands.js` mounts each island when it is needed.
|
|
7
7
|
* docs/rendering.md, "Islands".
|
|
8
8
|
*/
|
|
9
|
+
|
|
10
|
+
import { contentHash, hashedAddress } from './assets.ts'
|
|
9
11
|
import { actionIdOf, markIslands } from './context.ts'
|
|
10
12
|
import { escapeHtml, RawHtml } from './html.ts'
|
|
13
|
+
import { ISLAND_LOADER_SCRIPT } from './islands-loader.ts'
|
|
11
14
|
import { type Child, renderToString } from './jsx-runtime.ts'
|
|
12
15
|
|
|
13
16
|
/** The loader every page with an island links to; a file, so no inline script is written. */
|
|
@@ -24,7 +27,15 @@ const LOADS: readonly IslandLoad[] = ['visible', 'idle', 'load']
|
|
|
24
27
|
* before it; the words anywhere else, in a string or later on, do not count.
|
|
25
28
|
*/
|
|
26
29
|
export function isClientModule(source: string): boolean {
|
|
27
|
-
|
|
30
|
+
return hasDirective(source, 'use client')
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Whether a module's first statement is this directive. Comments may come
|
|
35
|
+
* before it; the words anywhere else do not count.
|
|
36
|
+
*/
|
|
37
|
+
export function hasDirective(source: string, directive: string): boolean {
|
|
38
|
+
let rest = source.replace(/^\ufeff/, '')
|
|
28
39
|
for (;;) {
|
|
29
40
|
rest = rest.replace(/^\s+/, '')
|
|
30
41
|
if (rest.startsWith('//')) {
|
|
@@ -36,7 +47,8 @@ export function isClientModule(source: string): boolean {
|
|
|
36
47
|
rest = rest.slice(end + 2)
|
|
37
48
|
} else break
|
|
38
49
|
}
|
|
39
|
-
|
|
50
|
+
const quoted = /^(['"])(.*?)\1\s*(;|\n|$)/.exec(rest)
|
|
51
|
+
return quoted?.[2] === directive
|
|
40
52
|
}
|
|
41
53
|
|
|
42
54
|
/** A prop an island cannot carry to the browser, named by where it is. */
|
|
@@ -47,7 +59,11 @@ export class IslandPropsError extends Error {}
|
|
|
47
59
|
* when anything would not survive the trip, escaped so nothing in it can close
|
|
48
60
|
* the script or read as markup.
|
|
49
61
|
*/
|
|
50
|
-
export function serializeProps(
|
|
62
|
+
export function serializeProps(
|
|
63
|
+
props: Record<string, unknown>,
|
|
64
|
+
island: string,
|
|
65
|
+
carried: 'island' | 'part' = 'island',
|
|
66
|
+
): string {
|
|
51
67
|
const seen = new Set<object>()
|
|
52
68
|
const check = (value: unknown, path: string): void => {
|
|
53
69
|
if (value === null || typeof value === 'string' || typeof value === 'boolean') return
|
|
@@ -57,11 +73,13 @@ export function serializeProps(props: Record<string, unknown>, island: string):
|
|
|
57
73
|
return
|
|
58
74
|
}
|
|
59
75
|
// A server action travels as its id, and the browser calls it (story 219).
|
|
60
|
-
if (typeof value === 'function' && actionIdOf(value)) return
|
|
76
|
+
if (typeof value === 'function' && actionIdOf(value) && carried === 'island') return
|
|
61
77
|
if (typeof value !== 'object') {
|
|
62
78
|
const what = value === undefined ? 'undefined' : `a ${typeof value}`
|
|
63
79
|
throw new IslandPropsError(
|
|
64
|
-
|
|
80
|
+
carried === 'island'
|
|
81
|
+
? `${island}: ${path} is ${what}; an island's props travel to the browser as JSON, so only data, or one of the site's server actions, can be passed.`
|
|
82
|
+
: `${island}: ${path} is ${what}; a deferred part's props travel in its address as JSON, so only data can be passed.`,
|
|
65
83
|
)
|
|
66
84
|
}
|
|
67
85
|
if (seen.has(value))
|
|
@@ -211,14 +229,24 @@ export function Island({
|
|
|
211
229
|
})
|
|
212
230
|
}
|
|
213
231
|
|
|
232
|
+
/** The loader's address while its script is as it is now (story 260). */
|
|
233
|
+
export const ISLAND_LOADER_ADDRESS = hashedAddress(
|
|
234
|
+
ISLAND_LOADER_PATH,
|
|
235
|
+
contentHash(ISLAND_LOADER_SCRIPT),
|
|
236
|
+
)
|
|
237
|
+
|
|
214
238
|
/** The tags a page with islands ends with: where its browser code is, and the loader. */
|
|
215
239
|
export function islandTags(manifestUrl: string): string {
|
|
216
|
-
return `<meta name="crombolo-islands" content="${escapeHtml(manifestUrl)}"><script type="module" src="${
|
|
240
|
+
return `<meta name="crombolo-islands" content="${escapeHtml(manifestUrl)}"><script type="module" src="${ISLAND_LOADER_ADDRESS}"></script>`
|
|
217
241
|
}
|
|
218
242
|
|
|
219
243
|
/** A page's HTML with the island tags before `</body>`, or at the end when it has none. */
|
|
220
244
|
export function withIslandTags(html: string, manifestUrl: string): string {
|
|
221
|
-
|
|
245
|
+
return beforeBodyEnd(html, islandTags(manifestUrl))
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** `tags` before `</body>`, or at the end when there is none. */
|
|
249
|
+
export function beforeBodyEnd(html: string, tags: string): string {
|
|
222
250
|
const at = html.toLowerCase().lastIndexOf('</body>')
|
|
223
251
|
return at < 0 ? `${html}${tags}` : `${html.slice(0, at)}${tags}${html.slice(at)}`
|
|
224
252
|
}
|
package/src/published-cache.ts
CHANGED
|
@@ -293,6 +293,8 @@ export function fallbackChain(
|
|
|
293
293
|
|
|
294
294
|
/** What the cache needs besides content, for values that resolve outside it. */
|
|
295
295
|
export interface PublishedCacheOptions {
|
|
296
|
+
/** Each read of the snapshot: answered from the one built, or after building one (story 262). */
|
|
297
|
+
onRead?: (hit: boolean) => void
|
|
296
298
|
/**
|
|
297
299
|
* A form definition by key, for a `formPicker` property.
|
|
298
300
|
*
|
|
@@ -429,6 +431,7 @@ export class PublishedCache {
|
|
|
429
431
|
* the first build there is none, so they share the build.
|
|
430
432
|
*/
|
|
431
433
|
async snapshot(): Promise<CacheSnapshot> {
|
|
434
|
+
this.#options.onRead?.(this.#loaded)
|
|
432
435
|
if (this.#loaded) return this.#snapshot
|
|
433
436
|
const generation = this.#generation
|
|
434
437
|
const previous = this.#snapshotGeneration >= 0 ? this.#snapshot : undefined
|
package/src/renderer.ts
CHANGED
|
@@ -7,14 +7,20 @@
|
|
|
7
7
|
* declares it too — in the file, not the database.
|
|
8
8
|
*/
|
|
9
9
|
import { existsSync, readFileSync } from 'node:fs'
|
|
10
|
-
import { basename, join, resolve, sep } from 'node:path'
|
|
10
|
+
import { basename, dirname, join, relative, resolve, sep } from 'node:path'
|
|
11
11
|
import { pathToFileURL } from 'node:url'
|
|
12
12
|
import { type FormSubmissionState, isOutcome, type Outcome } from '@crombolo/core'
|
|
13
13
|
import { componentStackOf, trackComponent } from './component-stack.ts'
|
|
14
14
|
import { emailScope, markPersonal, type PageActions, renderScope } from './context.ts'
|
|
15
|
+
import {
|
|
16
|
+
DEFERRED_TAGS,
|
|
17
|
+
type DeferredRequest,
|
|
18
|
+
type DeferredScope,
|
|
19
|
+
isDeferredSource,
|
|
20
|
+
} from './deferred.ts'
|
|
15
21
|
import type { EmailProps, EmailRenderResult } from './email.ts'
|
|
16
22
|
import { RawHtml } from './html.ts'
|
|
17
|
-
import { ISLANDS_PATH, withIslandTags } from './islands.ts'
|
|
23
|
+
import { beforeBodyEnd, ISLANDS_PATH, withIslandTags } from './islands.ts'
|
|
18
24
|
import { type Child, renderToString } from './jsx-runtime.ts'
|
|
19
25
|
import type {
|
|
20
26
|
PageOutcome,
|
|
@@ -76,6 +82,11 @@ export interface RenderedCaching {
|
|
|
76
82
|
personal: boolean
|
|
77
83
|
/** The template's own `revalidate`, overriding its type's and the site's lifetime. */
|
|
78
84
|
revalidate?: number | false
|
|
85
|
+
/**
|
|
86
|
+
* The view files it rendered that mention `member` (story 263): the page
|
|
87
|
+
* depends on who is signed in, and is shared only with signed-out visitors.
|
|
88
|
+
*/
|
|
89
|
+
memberFiles?: string[]
|
|
79
90
|
}
|
|
80
91
|
|
|
81
92
|
export type RenderResult =
|
|
@@ -146,6 +157,10 @@ export interface RenderRequest {
|
|
|
146
157
|
site?: () => unknown
|
|
147
158
|
/** On a status page, the outcome it is answering, for `usePage().outcome`. */
|
|
148
159
|
outcome?: PageOutcome
|
|
160
|
+
/** Signs a `'use deferred'` part's address; without it, parts render in place (story 263). */
|
|
161
|
+
signDeferred?: (data: string) => string
|
|
162
|
+
/** Renders only this part of the page, for its own request. */
|
|
163
|
+
part?: DeferredRequest
|
|
149
164
|
}
|
|
150
165
|
|
|
151
166
|
/** The query string as Next.js hands it to a page: a name given twice becomes an array. */
|
|
@@ -208,6 +223,8 @@ export class Renderer {
|
|
|
208
223
|
/** Keyed by the generation that holds the view, so one swap retires them all. */
|
|
209
224
|
#modules = new Map<string, ComponentModule>()
|
|
210
225
|
#importedFrom: string | undefined
|
|
226
|
+
/** Per view file in the current generation: the files it or its imports have that mention `member`. */
|
|
227
|
+
#memberFiles = new Map<string, string[]>()
|
|
211
228
|
#renderTimeoutMs: number
|
|
212
229
|
#islandsManifest: (generation: string | undefined) => string | undefined
|
|
213
230
|
|
|
@@ -246,11 +263,52 @@ export class Renderer {
|
|
|
246
263
|
const dir = this.#snapshots?.directory() ?? this.#componentsDir
|
|
247
264
|
if (dir !== this.#importedFrom) {
|
|
248
265
|
this.#modules.clear()
|
|
266
|
+
this.#memberFiles.clear()
|
|
249
267
|
this.#importedFrom = dir
|
|
250
268
|
}
|
|
251
269
|
return dir
|
|
252
270
|
}
|
|
253
271
|
|
|
272
|
+
/**
|
|
273
|
+
* The files among `file` and what it imports from the views that mention
|
|
274
|
+
* `member` (story 263). Read once per file per generation. A deferred part's
|
|
275
|
+
* own source is left out, as it renders in its own request, and so is any
|
|
276
|
+
* package, whose code cannot be read here.
|
|
277
|
+
*/
|
|
278
|
+
#filesMentioningMember(file: string, seen = new Set<string>()): string[] {
|
|
279
|
+
const known = this.#memberFiles.get(file)
|
|
280
|
+
if (known) return known
|
|
281
|
+
if (seen.has(file) || isDeferredSource(file)) return []
|
|
282
|
+
seen.add(file)
|
|
283
|
+
let source: string
|
|
284
|
+
try {
|
|
285
|
+
source = readFileSync(file, 'utf8')
|
|
286
|
+
} catch {
|
|
287
|
+
return []
|
|
288
|
+
}
|
|
289
|
+
const found: string[] = []
|
|
290
|
+
try {
|
|
291
|
+
if (/\bmember\b/.test(viewTranspiler.transformSync(source))) found.push(file)
|
|
292
|
+
for (const { path } of viewTranspiler.scanImports(source)) {
|
|
293
|
+
if (!path.startsWith('.')) continue
|
|
294
|
+
const target = resolveView(join(dirname(file), path))
|
|
295
|
+
if (target) found.push(...this.#filesMentioningMember(target, seen))
|
|
296
|
+
}
|
|
297
|
+
} catch {
|
|
298
|
+
// A file that does not parse fails its render, which says so.
|
|
299
|
+
found.push(file)
|
|
300
|
+
}
|
|
301
|
+
const unique = [...new Set(found)]
|
|
302
|
+
this.#memberFiles.set(file, unique)
|
|
303
|
+
return unique
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** A view file as a person reads it: `components/shared/layout.tsx`. */
|
|
307
|
+
#shownPath(file: string): string {
|
|
308
|
+
const dir = this.#importedFrom ?? this.#componentsDir
|
|
309
|
+
return `${basename(this.#componentsDir)}/${relative(dir, file).split(sep).join('/')}`
|
|
310
|
+
}
|
|
311
|
+
|
|
254
312
|
/**
|
|
255
313
|
* The file a view is imported from, inside the current generation.
|
|
256
314
|
*
|
|
@@ -458,7 +516,8 @@ export class Renderer {
|
|
|
458
516
|
rendering: { alias: string },
|
|
459
517
|
caching: RenderedCaching,
|
|
460
518
|
): Promise<string | undefined> {
|
|
461
|
-
const
|
|
519
|
+
const used = new Set<string>()
|
|
520
|
+
const page = await this.#load(alias, used)
|
|
462
521
|
if (!page) return undefined
|
|
463
522
|
const dynamic = page.dynamic ?? 'auto'
|
|
464
523
|
const shared = dynamic === 'force-static'
|
|
@@ -501,43 +560,68 @@ export class Renderer {
|
|
|
501
560
|
|
|
502
561
|
const metadata: { value?: Metadata } = {}
|
|
503
562
|
const islands = { used: false }
|
|
563
|
+
const deferred: DeferredScope | undefined = request.signDeferred
|
|
564
|
+
? { inPart: request.part !== undefined, sign: request.signDeferred, used: false }
|
|
565
|
+
: undefined
|
|
504
566
|
// Inside the page's scope, so any component can ask for it with `usePage()`.
|
|
505
567
|
try {
|
|
506
568
|
const html = await renderScope(
|
|
507
569
|
props,
|
|
508
570
|
async () => {
|
|
571
|
+
if (request.part) return this.#renderPart(request.part)
|
|
509
572
|
if (page.generateMetadata) metadata.value = await page.generateMetadata(props)
|
|
510
|
-
return this.#renderLayouts(alias, props, rendering)
|
|
573
|
+
return this.#renderLayouts(alias, props, rendering, used)
|
|
511
574
|
},
|
|
512
575
|
{
|
|
513
576
|
search: request.search,
|
|
514
577
|
preview: request.preview,
|
|
515
578
|
antiforgery: request.antiforgery,
|
|
516
|
-
blockComponent: (blockAlias) => this.blockComponent(blockAlias),
|
|
579
|
+
blockComponent: (blockAlias) => this.blockComponent(blockAlias, used),
|
|
517
580
|
request: { headers: shared ? new Headers() : (request.headers ?? new Headers()) },
|
|
518
581
|
site: request.site,
|
|
519
582
|
personal: shared ? { value: false } : personal,
|
|
520
583
|
metadata,
|
|
521
584
|
islands,
|
|
522
585
|
actions: request.actions,
|
|
586
|
+
deferred,
|
|
523
587
|
},
|
|
524
588
|
)
|
|
525
|
-
if (html === undefined ||
|
|
589
|
+
if (html === undefined || request.part) return html
|
|
590
|
+
const withParts = deferred?.used ? beforeBodyEnd(html, DEFERRED_TAGS) : html
|
|
591
|
+
if (!islands.used) return withParts
|
|
526
592
|
// The generation the views were imported from, so the page loads the code built with them.
|
|
527
593
|
const manifest = this.#islandsManifest(
|
|
528
594
|
this.#importedFrom && this.#snapshots ? basename(this.#importedFrom) : undefined,
|
|
529
595
|
)
|
|
530
|
-
return manifest ? withIslandTags(
|
|
596
|
+
return manifest ? withIslandTags(withParts, manifest) : withParts
|
|
531
597
|
} finally {
|
|
532
|
-
|
|
598
|
+
const files = [...new Set([...used].flatMap((file) => this.#filesMentioningMember(file)))]
|
|
599
|
+
if (files.length > 0) caching.memberFiles = files.map((file) => this.#shownPath(file))
|
|
600
|
+
caching.personal = !shared && (personal.value || (member !== undefined && files.length > 0))
|
|
533
601
|
}
|
|
534
602
|
}
|
|
535
603
|
|
|
604
|
+
/** A `'use deferred'` part alone, for its own request: its module's export, rendered in place. */
|
|
605
|
+
async #renderPart(part: DeferredRequest): Promise<string | undefined> {
|
|
606
|
+
const segments = part.module.split('/')
|
|
607
|
+
const safe =
|
|
608
|
+
/\.[jt]sx?$/.test(part.module) &&
|
|
609
|
+
segments.every((segment) => /^[A-Za-z0-9_.-]+$/.test(segment) && !/^\.+$/.test(segment))
|
|
610
|
+
if (!safe) return undefined
|
|
611
|
+
const file = join(this.#importDir(), ...segments)
|
|
612
|
+
if (!existsSync(file)) return undefined
|
|
613
|
+
const module = (await import(pathToFileURL(file).href)) as Record<string, unknown>
|
|
614
|
+
const render = module[part.exportName]
|
|
615
|
+
if (typeof render !== 'function') return undefined
|
|
616
|
+
return renderToString((render as (props: object) => Child)({ ...part.props }))
|
|
617
|
+
}
|
|
618
|
+
|
|
536
619
|
/** Generic over its props: a page's, or an e-mail's. */
|
|
537
620
|
async #renderLayouts<Props extends object>(
|
|
538
621
|
alias: string,
|
|
539
622
|
props: Props,
|
|
540
623
|
rendering: { alias: string },
|
|
624
|
+
used?: Set<string>,
|
|
541
625
|
): Promise<string | undefined> {
|
|
542
626
|
let currentAlias: string | undefined = alias
|
|
543
627
|
let body: RawHtml | undefined
|
|
@@ -547,7 +631,7 @@ export class Renderer {
|
|
|
547
631
|
// wraps the result. A cycle would otherwise hang the request.
|
|
548
632
|
while (currentAlias && depth < MAX_LAYOUT_DEPTH) {
|
|
549
633
|
rendering.alias = currentAlias
|
|
550
|
-
const module = await this.#load(currentAlias)
|
|
634
|
+
const module = await this.#load(currentAlias, used)
|
|
551
635
|
if (!module) return depth === 0 || body === undefined ? undefined : withDoctype(body.value)
|
|
552
636
|
const render = module.default as unknown as (props: object) => Child | Promise<Child>
|
|
553
637
|
const layoutProps = body === undefined ? props : { ...props, children: body }
|
|
@@ -570,15 +654,16 @@ export class Renderer {
|
|
|
570
654
|
* nowhere else. The alias is one plain segment, so an element type alias can
|
|
571
655
|
* never reach outside `blocks/`.
|
|
572
656
|
*/
|
|
573
|
-
async blockComponent(alias: string) {
|
|
657
|
+
async blockComponent(alias: string, used?: Set<string>) {
|
|
574
658
|
if (!/^[A-Za-z0-9_-]+$/.test(alias)) return undefined
|
|
575
|
-
const module = await this.#load(`blocks/${alias}
|
|
659
|
+
const module = await this.#load(`blocks/${alias}`, used)
|
|
576
660
|
return module?.default as ((props: never) => Child | Promise<Child>) | undefined
|
|
577
661
|
}
|
|
578
662
|
|
|
579
|
-
async #load(alias: string): Promise<ComponentModule | undefined> {
|
|
663
|
+
async #load(alias: string, used?: Set<string>): Promise<ComponentModule | undefined> {
|
|
580
664
|
const file = this.componentPath(alias)
|
|
581
665
|
if (!file) return undefined
|
|
666
|
+
used?.add(file)
|
|
582
667
|
// The path carries the generation, so one entry per view per generation and
|
|
583
668
|
// a swap never answers from the generation before it.
|
|
584
669
|
const cached = this.#modules.get(file)
|
|
@@ -593,6 +678,19 @@ export class Renderer {
|
|
|
593
678
|
}
|
|
594
679
|
}
|
|
595
680
|
|
|
681
|
+
const viewTranspiler = new Bun.Transpiler({ loader: 'tsx' })
|
|
682
|
+
|
|
683
|
+
/** A relative import's file in the views: as written, or with the extension it leaves off. */
|
|
684
|
+
function resolveView(path: string): string | undefined {
|
|
685
|
+
for (const candidate of [
|
|
686
|
+
path,
|
|
687
|
+
...['.tsx', '.ts', '.jsx', '.js'].map((extension) => `${path}${extension}`),
|
|
688
|
+
...['index.tsx', 'index.ts'].map((name) => join(path, name)),
|
|
689
|
+
])
|
|
690
|
+
if (/\.[jt]sx?$/.test(candidate) && existsSync(candidate)) return candidate
|
|
691
|
+
return undefined
|
|
692
|
+
}
|
|
693
|
+
|
|
596
694
|
/** What a template threw, for a person to act on (`Renderer.describeError`). */
|
|
597
695
|
export interface ErrorDescription {
|
|
598
696
|
message: string
|
package/src/snapshots.ts
CHANGED
|
@@ -103,7 +103,7 @@ export interface SnapshotOptions {
|
|
|
103
103
|
* a `'use client'` module becomes its island stub (story 209). The hash still
|
|
104
104
|
* covers the source, and the source is kept under `.islands/src/`.
|
|
105
105
|
*/
|
|
106
|
-
transform?: (key: string, bytes: Uint8Array) =>
|
|
106
|
+
transform?: (key: string, bytes: Uint8Array) => SnapshotTransform | undefined
|
|
107
107
|
/**
|
|
108
108
|
* A generation is in place and about to be rendered: its browser code is
|
|
109
109
|
* built here, from the files the transform rewrote. A failure is reported,
|
|
@@ -113,6 +113,13 @@ export interface SnapshotOptions {
|
|
|
113
113
|
now?: () => number
|
|
114
114
|
}
|
|
115
115
|
|
|
116
|
+
/**
|
|
117
|
+
* What a file is written as: an island's stub, its source kept for the browser
|
|
118
|
+
* build; or a deferred part's stub, its source written beside it under
|
|
119
|
+
* `beside`, where the stub imports it (story 263).
|
|
120
|
+
*/
|
|
121
|
+
export type SnapshotTransform = Uint8Array | { bytes: Uint8Array; beside: string }
|
|
122
|
+
|
|
116
123
|
/** Beside a generation's views: the client sources and their built browser code. */
|
|
117
124
|
export const ISLANDS_DIR = '.islands'
|
|
118
125
|
|
|
@@ -354,6 +361,11 @@ export class ViewSnapshots {
|
|
|
354
361
|
const target = join(partial, ...file.key.split('/'))
|
|
355
362
|
mkdirSync(join(target, '..'), { recursive: true })
|
|
356
363
|
const written = this.#transform?.(file.key, bytes)
|
|
364
|
+
if (written && !(written instanceof Uint8Array)) {
|
|
365
|
+
writeFileSync(join(partial, ...written.beside.split('/')), bytes)
|
|
366
|
+
writeFileSync(target, written.bytes)
|
|
367
|
+
continue
|
|
368
|
+
}
|
|
357
369
|
if (written) {
|
|
358
370
|
transformed.push(file.key)
|
|
359
371
|
const kept = join(partial, ISLANDS_DIR, 'src', ...file.key.split('/'))
|
package/src/values.ts
CHANGED
|
@@ -44,6 +44,8 @@ export interface Link {
|
|
|
44
44
|
|
|
45
45
|
export interface BlockItem {
|
|
46
46
|
contentKey: string
|
|
47
|
+
/** The name it was given on the page, unique within its property (story 253). */
|
|
48
|
+
alias: string | null
|
|
47
49
|
content: PublishedElement
|
|
48
50
|
settingsKey: string | null
|
|
49
51
|
settings: PublishedElement | null
|
|
@@ -66,8 +68,21 @@ export interface BlockGridItem extends BlockItem {
|
|
|
66
68
|
areas: BlockGridArea[]
|
|
67
69
|
}
|
|
68
70
|
|
|
71
|
+
/** A block list's items, with the one given an alias picked out by it. */
|
|
72
|
+
export type BlockListValue<T extends BlockItem = BlockItem> = T[] & {
|
|
73
|
+
byAlias(alias: string): T | undefined
|
|
74
|
+
}
|
|
75
|
+
|
|
69
76
|
/** A Block Grid's items, carrying the grid's column count for its markup. */
|
|
70
|
-
export type BlockGridValue = BlockGridItem
|
|
77
|
+
export type BlockGridValue = BlockListValue<BlockGridItem> & { gridColumns: number }
|
|
78
|
+
|
|
79
|
+
/** Items with `byAlias`, which finds an alias in any case. */
|
|
80
|
+
function withAliases<T extends BlockItem>(items: T[]): BlockListValue<T> {
|
|
81
|
+
return Object.assign(items, {
|
|
82
|
+
byAlias: (alias: string) =>
|
|
83
|
+
items.find((item) => item.alias?.toLowerCase() === alias.toLowerCase()),
|
|
84
|
+
})
|
|
85
|
+
}
|
|
71
86
|
|
|
72
87
|
const references = (value: unknown): string[] => {
|
|
73
88
|
if (Array.isArray(value)) return value.flatMap((v) => (typeof v === 'string' ? [v] : []))
|
|
@@ -194,6 +209,7 @@ interface BlockData {
|
|
|
194
209
|
|
|
195
210
|
interface BlockLayout {
|
|
196
211
|
contentKey?: string
|
|
212
|
+
alias?: unknown
|
|
197
213
|
settingsKey?: string | null
|
|
198
214
|
columnSpan?: number
|
|
199
215
|
rowSpan?: number
|
|
@@ -247,6 +263,7 @@ function blockItems<T extends BlockItem>(
|
|
|
247
263
|
if (!content) return []
|
|
248
264
|
const item: BlockItem = {
|
|
249
265
|
contentKey: content.key,
|
|
266
|
+
alias: typeof layout.alias === 'string' && layout.alias ? layout.alias : null,
|
|
250
267
|
content,
|
|
251
268
|
settingsKey: layout.settingsKey ?? null,
|
|
252
269
|
settings: elementFrom(settings.get(layout.settingsKey ?? ''), context),
|
|
@@ -449,7 +466,9 @@ export function convertValue(
|
|
|
449
466
|
}),
|
|
450
467
|
).then((links) => links.filter((link): link is Link => link !== undefined))
|
|
451
468
|
case 'Umbraco.BlockList':
|
|
452
|
-
return
|
|
469
|
+
return withAliases(
|
|
470
|
+
blockItems<BlockItem>(value, 'Umbraco.BlockList', context, (_, item) => item),
|
|
471
|
+
)
|
|
453
472
|
case 'Umbraco.BlockGrid': {
|
|
454
473
|
// What the data type says of each block type's areas: their aliases and spans.
|
|
455
474
|
const blockTypes = Array.isArray(config.blocks) ? (config.blocks as GridBlockConfig[]) : []
|
|
@@ -484,7 +503,7 @@ export function convertValue(
|
|
|
484
503
|
}
|
|
485
504
|
},
|
|
486
505
|
)
|
|
487
|
-
return Object.assign(items, { gridColumns: Number(config.gridColumns) || 12 })
|
|
506
|
+
return Object.assign(withAliases(items), { gridColumns: Number(config.gridColumns) || 12 })
|
|
488
507
|
}
|
|
489
508
|
default:
|
|
490
509
|
return value
|