@crombolo/render 0.20.0 → 0.22.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/render",
3
- "version": "0.20.0",
3
+ "version": "0.22.0",
4
4
  "description": "TSX server rendering and the published-content model for crombolo.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -32,7 +32,7 @@
32
32
  "access": "public"
33
33
  },
34
34
  "dependencies": {
35
- "@crombolo/core": "0.20.0",
35
+ "@crombolo/core": "0.22.0",
36
36
  "@types/react": "^19.3.0"
37
37
  }
38
38
  }
@@ -0,0 +1,173 @@
1
+ /**
2
+ * How long copies of a page, an API answer or a media file may be kept, and by
3
+ * whom (story 057). Three levels, the narrowest set winning: the item's own
4
+ * "Keep copies for" choice, its type's lifetime, the site's. Nothing is kept
5
+ * unless one of them says so. docs/operations.md, "Behind a CDN".
6
+ */
7
+ import { CACHE_KEEP_FOR_ALIAS, KEEP_COPIES_FOR } from '@crombolo/core'
8
+
9
+ export interface CacheLifetimeOptions {
10
+ /** Seconds a copy may be reused; 0 keeps none. */
11
+ maxAge?: number
12
+ /** Seconds a stale copy may still be served while a fresh one is fetched. */
13
+ staleWhileRevalidate?: number
14
+ }
15
+
16
+ export interface CacheOptions extends CacheLifetimeOptions {
17
+ /** By content or media type alias, winning over the site's. */
18
+ types?: Record<string, CacheLifetimeOptions>
19
+ /** The header a CDN reads purge tags from, such as `Surrogate-Key` or `Cache-Tag`. */
20
+ tagHeader?: string
21
+ }
22
+
23
+ export interface CacheSettings {
24
+ site: Lifetime
25
+ types: ReadonlyMap<string, Lifetime>
26
+ tagHeader: string | undefined
27
+ }
28
+
29
+ /** Kept this long, or not kept (`none`), or nothing said (`undefined`). */
30
+ export type Lifetime = { maxAge: number; staleWhileRevalidate?: number } | 'none' | undefined
31
+
32
+ /** What every answer that depends on who is asking carries, whatever is configured. */
33
+ export const PRIVATE_NO_STORE = 'private, no-store'
34
+
35
+ const seconds = (value: unknown): number | undefined =>
36
+ typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.floor(value) : undefined
37
+
38
+ function lifetimeOf(options: CacheLifetimeOptions | undefined): Lifetime {
39
+ const maxAge = seconds(options?.maxAge)
40
+ if (maxAge === undefined) return undefined
41
+ if (maxAge === 0) return 'none'
42
+ const swr = seconds(options?.staleWhileRevalidate)
43
+ return swr ? { maxAge, staleWhileRevalidate: swr } : { maxAge }
44
+ }
45
+
46
+ /** The settings with what cannot be used dropped. Pure. */
47
+ export function resolveCacheSettings(options: CacheOptions = {}): CacheSettings {
48
+ const types = new Map<string, Lifetime>()
49
+ for (const [alias, own] of Object.entries(options.types ?? {})) {
50
+ const lifetime = lifetimeOf({
51
+ staleWhileRevalidate: options.staleWhileRevalidate,
52
+ ...own,
53
+ })
54
+ if (lifetime) types.set(alias.toLowerCase(), lifetime)
55
+ }
56
+ const tagHeader = options.tagHeader?.trim()
57
+ return {
58
+ site: lifetimeOf(options),
59
+ types,
60
+ tagHeader: tagHeader && /^[A-Za-z0-9-]+$/.test(tagHeader) ? tagHeader : undefined,
61
+ }
62
+ }
63
+
64
+ /** An editor's "Keep copies for" choice as a lifetime, or undefined for none chosen. Pure. */
65
+ export function chosenLifetime(value: unknown, staleWhileRevalidate?: number): Lifetime {
66
+ const label = Array.isArray(value) ? value[0] : value
67
+ const choice = KEEP_COPIES_FOR.find((c) => c.label === label)
68
+ if (!choice) return undefined
69
+ if (choice.seconds === 0) return 'none'
70
+ return staleWhileRevalidate
71
+ ? { maxAge: choice.seconds, staleWhileRevalidate }
72
+ : { maxAge: choice.seconds }
73
+ }
74
+
75
+ /** Anything with a type and properties: a page, an element or a media item. */
76
+ export interface Cacheable {
77
+ typeAlias: string
78
+ value(alias: string): unknown
79
+ }
80
+
81
+ /**
82
+ * An item's lifetime: its own choice, else its type's, else the site's — or,
83
+ * without `site`, nothing, for media files, which keep their own default. Pure.
84
+ */
85
+ export function lifetimeFor(
86
+ settings: CacheSettings,
87
+ item: Cacheable,
88
+ options: { site?: boolean } = {},
89
+ ): Lifetime {
90
+ const swr =
91
+ settings.site && settings.site !== 'none' ? settings.site.staleWhileRevalidate : undefined
92
+ return (
93
+ chosenLifetime(item.value(CACHE_KEEP_FOR_ALIAS), swr) ??
94
+ settings.types.get(item.typeAlias.toLowerCase()) ??
95
+ (options.site === false ? undefined : settings.site)
96
+ )
97
+ }
98
+
99
+ /** The shortest of several lifetimes: one that keeps nothing wins, one that says nothing is ignored. Pure. */
100
+ export function shortest(lifetimes: readonly Lifetime[], whenEmpty: Lifetime): Lifetime {
101
+ let result: Lifetime
102
+ let any = false
103
+ for (const lifetime of lifetimes) {
104
+ if (lifetime === undefined) continue
105
+ if (lifetime === 'none') return 'none'
106
+ any = true
107
+ if (!result || result === 'none' || lifetime.maxAge < result.maxAge) result = lifetime
108
+ }
109
+ return any ? result : lifetimes.length === 0 ? whenEmpty : undefined
110
+ }
111
+
112
+ /** The `Cache-Control` value for a public answer, or undefined to say nothing. Pure. */
113
+ export function cacheControl(lifetime: Lifetime): string | undefined {
114
+ if (lifetime === undefined) return undefined
115
+ if (lifetime === 'none') return 'no-store'
116
+ return lifetime.staleWhileRevalidate
117
+ ? `public, max-age=${lifetime.maxAge}, stale-while-revalidate=${lifetime.staleWhileRevalidate}`
118
+ : `public, max-age=${lifetime.maxAge}`
119
+ }
120
+
121
+ /** A weak validator over a body's bytes. */
122
+ export function etagFor(body: string | Uint8Array): string {
123
+ return `W/"${Bun.hash(body).toString(36)}"`
124
+ }
125
+
126
+ /** Whether `If-None-Match` names this tag, or `*`. Pure. */
127
+ export function notModified(request: Request, etag: string): boolean {
128
+ const header = request.headers.get('if-none-match')
129
+ if (!header) return false
130
+ const bare = etag.replace(/^W\//, '')
131
+ return header
132
+ .split(',')
133
+ .map((tag) => tag.trim())
134
+ .some((tag) => tag === '*' || tag.replace(/^W\//, '') === bare)
135
+ }
136
+
137
+ /** Purge tags in the form the header expects: spaces for `Surrogate-Key`, commas otherwise. Pure. */
138
+ export function tagValue(header: string, keys: Iterable<string>): string | undefined {
139
+ const unique = [...new Set([...keys].map((key) => key.toLowerCase()))]
140
+ if (unique.length === 0) return undefined
141
+ return unique.join(header.toLowerCase() === 'surrogate-key' ? ' ' : ',')
142
+ }
143
+
144
+ /**
145
+ * The finished headers of a public `200`: its lifetime, an ETag over the body,
146
+ * and its tags; a `304` when the caller already holds it.
147
+ */
148
+ export function cacheable(
149
+ request: Request,
150
+ response: Response,
151
+ body: string | Uint8Array,
152
+ options: { lifetime: Lifetime; tags?: Iterable<string>; tagHeader?: string },
153
+ ): Response {
154
+ const headers = new Headers(response.headers)
155
+ const control = cacheControl(options.lifetime)
156
+ if (control) headers.set('cache-control', control)
157
+ const etag = etagFor(body)
158
+ headers.set('etag', etag)
159
+ if (options.tagHeader && options.tags) {
160
+ const tags = tagValue(options.tagHeader, options.tags)
161
+ if (tags) headers.set(options.tagHeader, tags)
162
+ }
163
+ if (notModified(request, etag)) {
164
+ headers.delete('content-type')
165
+ headers.delete('content-length')
166
+ return new Response(null, { status: 304, headers })
167
+ }
168
+ return new Response(body as BodyInit, {
169
+ status: response.status,
170
+ statusText: response.statusText,
171
+ headers,
172
+ })
173
+ }
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export * from './cache-policy.ts'
1
2
  export * from './context.ts'
2
3
  export * from './email.ts'
3
4
  export * from './excerpt.ts'
@@ -7,6 +8,7 @@ export * from './html.ts'
7
8
  export * from './jsx-attributes.ts'
8
9
  export * from './jsx-runtime.ts'
9
10
  export * from './media.ts'
11
+ export * from './menus.ts'
10
12
  export * from './model.ts'
11
13
  export * from './published-cache.ts'
12
14
  export * from './redirects.ts'
package/src/menus.ts ADDED
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Navigation menus (story 141): a Menu element from the Library, built into the
3
+ * tree a header or footer draws. Each item is a page, a media item, an address or
4
+ * a label, with items below it. A page is read as it is now, so a renamed or
5
+ * moved page follows; one unpublished or in the bin drops out, with the items
6
+ * below it. docs/rendering.md, "Menus".
7
+ */
8
+ import { keyFromReference, MENU_ALIAS_PROPERTY } from '@crombolo/core'
9
+ import type { PublishedMedia } from './media.ts'
10
+ import type { PublishedContent } from './model.ts'
11
+ import type { PublishedElement } from './values.ts'
12
+
13
+ export interface MenuItem {
14
+ /** The item's own label, else the page's or media item's name, else the link's text or address. */
15
+ label: string
16
+ /** Where it goes; null for a label that only holds the items below it. */
17
+ url: string | null
18
+ /** `_blank` and the like, as the editor set it. */
19
+ target: string | null
20
+ kind: 'page' | 'media' | 'external' | 'label'
21
+ /** The page or media item it links to. */
22
+ key: string | null
23
+ /** The page, for `aria-current` and the like. */
24
+ content: PublishedContent | undefined
25
+ children: MenuItem[]
26
+ }
27
+
28
+ export interface Menu {
29
+ key: string
30
+ alias: string
31
+ items: MenuItem[]
32
+ }
33
+
34
+ /** What a menu's links resolve against: one culture's pages, and the media. */
35
+ export interface MenuLookup {
36
+ content(key: string): PublishedContent | undefined
37
+ media(key: string): PublishedMedia | undefined
38
+ }
39
+
40
+ interface StoredBlocks {
41
+ layout?: Record<string, Array<{ contentKey?: string }> | undefined>
42
+ contentData?: Array<{ key: string; values?: Array<{ alias: string; value: unknown }> }>
43
+ }
44
+
45
+ const parsed = (value: unknown): unknown => {
46
+ if (typeof value !== 'string') return value
47
+ try {
48
+ return JSON.parse(value)
49
+ } catch {
50
+ return undefined
51
+ }
52
+ }
53
+
54
+ const text = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')
55
+
56
+ function items(value: unknown, lookup: MenuLookup): MenuItem[] {
57
+ const blocks = parsed(value) as StoredBlocks | undefined
58
+ if (!blocks || typeof blocks !== 'object') return []
59
+ const data = new Map((blocks.contentData ?? []).map((d) => [d.key, d]))
60
+ return (blocks.layout?.['Umbraco.BlockList'] ?? []).flatMap((layout) => {
61
+ const block = data.get(layout.contentKey ?? '')
62
+ if (!block) return []
63
+ const own = (alias: string) => block.values?.find((v) => v.alias === alias)?.value
64
+ const item = menuItem(own('link'), text(own('label')), lookup)
65
+ if (!item) return []
66
+ return [{ ...item, children: items(own('children'), lookup) }]
67
+ })
68
+ }
69
+
70
+ /** One item without its children; undefined when it links to something no longer there. */
71
+ function menuItem(
72
+ storedLink: unknown,
73
+ label: string,
74
+ lookup: MenuLookup,
75
+ ): Omit<MenuItem, 'children'> | undefined {
76
+ const links = parsed(storedLink)
77
+ const link = Array.isArray(links) ? (links[0] as Record<string, unknown> | undefined) : undefined
78
+ if (!link)
79
+ return label
80
+ ? { label, url: null, target: null, kind: 'label', key: null, content: undefined }
81
+ : undefined
82
+ const target = text(link.target) || null
83
+ const query = text(link.queryString)
84
+ const key = keyFromReference(link.unique ?? link.udi)
85
+ if (key && link.type !== 'media') {
86
+ const content = lookup.content(key)
87
+ if (!content?.url || content.url === '#') return undefined
88
+ return {
89
+ label: label || content.name,
90
+ url: `${content.url}${query}`,
91
+ target,
92
+ kind: 'page',
93
+ key: content.key,
94
+ content,
95
+ }
96
+ }
97
+ if (key) {
98
+ const media = lookup.media(key)
99
+ if (!media?.url) return undefined
100
+ return {
101
+ label: label || media.name,
102
+ url: media.url,
103
+ target,
104
+ kind: 'media',
105
+ key: media.key,
106
+ content: undefined,
107
+ }
108
+ }
109
+ const url = text(link.url)
110
+ if (!url || !isSafe(url)) return undefined
111
+ return {
112
+ label: label || text(link.name) || url,
113
+ url: `${url}${query}`,
114
+ target,
115
+ kind: 'external',
116
+ key: null,
117
+ content: undefined,
118
+ }
119
+ }
120
+
121
+ /** An address an editor typed, unless it would run script: `javascript:` and the like. */
122
+ function isSafe(url: string): boolean {
123
+ if (!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(url)) return true
124
+ try {
125
+ return ['http:', 'https:', 'mailto:', 'tel:'].includes(new URL(url).protocol)
126
+ } catch {
127
+ return false
128
+ }
129
+ }
130
+
131
+ /** A Menu element as the tree it describes. Pure. */
132
+ export function buildMenu(element: PublishedElement, lookup: MenuLookup): Menu {
133
+ const own = (alias: string) => element.properties.find((p) => p.alias === alias)?.value
134
+ return {
135
+ key: element.key,
136
+ alias: text(own(MENU_ALIAS_PROPERTY)),
137
+ items: items(own('items'), lookup),
138
+ }
139
+ }
package/src/model.ts CHANGED
@@ -6,9 +6,11 @@
6
6
  * the published cache cheap. `value()` carries the ergonomics: culture is
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
11
  import { RawHtml } from './html.ts'
11
12
  import { MediaWithCrops } from './media.ts'
13
+ import type { MenuItem } from './menus.ts'
12
14
  import type { SeoSiteDefaults } from './seo.ts'
13
15
  import { NAVI_HIDE_ALIAS } from './url-segment.ts'
14
16
  import { convertValue, type ValueContext } from './values.ts'
@@ -253,6 +255,11 @@ export interface PageProps<Properties = any> {
253
255
  culture: string | null
254
256
  /** A dictionary item in the request's culture, then its fallback languages; '' when missing. */
255
257
  dictionary: (key: string) => string
258
+ /**
259
+ * A menu's items by the menu's alias, in the request's culture: `menu('header')`.
260
+ * Empty when there is no such menu (story 141; docs/rendering.md, "Menus").
261
+ */
262
+ menu: (alias: string) => MenuItem[]
256
263
  /** The signed-in member, or undefined for an anonymous visitor. */
257
264
  member: RequestMember | undefined
258
265
  /**
@@ -15,10 +15,12 @@
15
15
  import {
16
16
  type ChoiceOption,
17
17
  type ChoiceSource,
18
+ MENU_ALIAS_PROPERTY,
18
19
  type SchemaForm,
19
20
  withResolvedChoices,
20
21
  } from '@crombolo/core'
21
22
  import { PublishedMedia } from './media.ts'
23
+ import { buildMenu, type Menu } from './menus.ts'
22
24
  import { type Navigation, PublishedContent, type PublishedProperty } from './model.ts'
23
25
  import { matchRedirect, type RedirectRule } from './redirects.ts'
24
26
  import {
@@ -276,8 +278,40 @@ export interface PublishedCacheOptions {
276
278
  * see that.
277
279
  */
278
280
  form?: (key: string) => SchemaForm | undefined
281
+ /** Told on every invalidation, for whatever else is built from the same content. */
282
+ onInvalidate?: () => void
279
283
  }
280
284
 
285
+ /** A menu's items in a culture, from a snapshot already in hand; empty when there is none. Pure. */
286
+ export function menuItemsIn(snapshot: CacheSnapshot, culture: string | null, alias: string) {
287
+ const view =
288
+ snapshot.views.get(viewKey(culture ?? snapshot.defaultCulture)) ??
289
+ snapshot.views.get(viewKey(snapshot.defaultCulture))
290
+ return view ? (menuIn(snapshot, view, alias)?.items ?? []) : []
291
+ }
292
+
293
+ /** The menu published under `alias` in a view, built against that view's pages. Pure. */
294
+ export function menuIn(
295
+ snapshot: CacheSnapshot,
296
+ view: CultureView,
297
+ alias: string,
298
+ ): Menu | undefined {
299
+ const wanted = alias.trim().toLowerCase()
300
+ for (const element of view.elements.values()) {
301
+ if (element.contentType.alias !== 'menu') continue
302
+ const own = element.properties.find((p) => p.alias === MENU_ALIAS_PROPERTY)?.value
303
+ if (typeof own !== 'string' || own.trim().toLowerCase() !== wanted) continue
304
+ return buildMenu(element, {
305
+ content: (key) => view.byKey.get(key.toLowerCase()),
306
+ media: (key) => snapshot.media.get(key.toLowerCase()),
307
+ })
308
+ }
309
+ return undefined
310
+ }
311
+
312
+ /** Built the first time a snapshot is asked for a file, and gone with the snapshot. */
313
+ const mediaByUrl = new WeakMap<CacheSnapshot, Map<string, PublishedMedia>>()
314
+
281
315
  export class PublishedCache {
282
316
  #source: PublishedContentSource
283
317
  #snapshot: CacheSnapshot = EMPTY
@@ -297,6 +331,7 @@ export class PublishedCache {
297
331
  invalidate(): void {
298
332
  this.#loaded = false
299
333
  this.#generation += 1
334
+ this.#options.onInvalidate?.()
300
335
  }
301
336
 
302
337
  /**
@@ -474,11 +509,30 @@ export class PublishedCache {
474
509
  return out
475
510
  }
476
511
 
512
+ /** A menu by its alias, in a culture; undefined when none is published under it (story 141). */
513
+ async menu(alias: string, culture?: string | null): Promise<Menu | undefined> {
514
+ const snapshot = await this.snapshot()
515
+ const view = this.#view(snapshot, culture)
516
+ return view ? menuIn(snapshot, view, alias) : undefined
517
+ }
518
+
477
519
  /** Every media item, in tree order. */
478
520
  async allMedia(): Promise<PublishedMedia[]> {
479
521
  return [...(await this.snapshot()).media.values()]
480
522
  }
481
523
 
524
+ /** The media item whose file is served at this address, `/media/<folder>/<name>`. */
525
+ async mediaAt(url: string): Promise<PublishedMedia | undefined> {
526
+ const snapshot = await this.snapshot()
527
+ let byUrl = mediaByUrl.get(snapshot)
528
+ if (!byUrl) {
529
+ byUrl = new Map()
530
+ for (const media of snapshot.media.values()) if (media.url) byUrl.set(media.url, media)
531
+ mediaByUrl.set(snapshot, byUrl)
532
+ }
533
+ return byUrl.get(url)
534
+ }
535
+
482
536
  /** How URLs are built here: whether the top-level page is left out of paths. */
483
537
  async hidesTopLevel(): Promise<boolean> {
484
538
  return (await this.snapshot()).hideTopLevel ?? true
@@ -918,6 +972,28 @@ export class PublishedCache {
918
972
  }
919
973
 
920
974
  /** The form with its source-backed choices resolved, as a page in `culture` would render it. */
975
+ /**
976
+ * What drawing forms from data needs, synchronously once the snapshot is in
977
+ * hand: a form with its choice sources filled in, and a page's address.
978
+ */
979
+ async formTools(culture?: string | null): Promise<{
980
+ resolve(form: SchemaForm): SchemaForm
981
+ urlOf(key: string): string | undefined
982
+ }> {
983
+ const snapshot = await this.snapshot()
984
+ const view = this.#view(snapshot, culture)
985
+ return {
986
+ resolve: (form) =>
987
+ withResolvedChoices(form, (source) =>
988
+ resolveChoices(snapshot, view, culture ?? null, source),
989
+ ),
990
+ urlOf: (key) => {
991
+ const url = view?.byKey.get(key.toLowerCase())?.url
992
+ return url && url !== '#' ? url : undefined
993
+ },
994
+ }
995
+ }
996
+
921
997
  async resolveForm(form: SchemaForm, culture?: string | null): Promise<SchemaForm> {
922
998
  const snapshot = await this.snapshot()
923
999
  const view = this.#view(snapshot, culture)
package/src/renderer.ts CHANGED
@@ -15,7 +15,7 @@ import type { EmailProps, EmailRenderResult } from './email.ts'
15
15
  import { RawHtml } from './html.ts'
16
16
  import { type Child, renderToString } from './jsx-runtime.ts'
17
17
  import type { PageProps, PublishedContent, RequestMember } from './model.ts'
18
- import { type PublishedCache, translate, urlsIn } from './published-cache.ts'
18
+ import { menuItemsIn, type PublishedCache, translate, urlsIn } from './published-cache.ts'
19
19
  import type { SiteSearchPort } from './search.ts'
20
20
  import { absoluteUrl, type SeoSiteDefaults } from './seo.ts'
21
21
  import type { ViewSnapshots } from './snapshots.ts'
@@ -348,12 +348,14 @@ export class Renderer {
348
348
  const nav = await this.#cache.navigation(culture)
349
349
  const snapshot = await this.#cache.snapshot()
350
350
  const dictionary = (key: string) => translate(snapshot, key, culture)
351
+ const menu = (alias: string) => menuItemsIn(snapshot, culture, alias)
351
352
  const origin = (request.origin ?? 'http://localhost').replace(/\/$/, '')
352
353
  const props: PageProps = {
353
354
  model: content,
354
355
  nav,
355
356
  culture,
356
357
  dictionary,
358
+ menu,
357
359
  member: request.member,
358
360
  submission: request.submission,
359
361
  request: { origin, url: request.url ?? `${origin}/` },