@crombolo/render 0.34.0 → 0.35.2

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.34.0",
3
+ "version": "0.35.2",
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",
@@ -32,7 +32,7 @@
32
32
  "access": "public"
33
33
  },
34
34
  "dependencies": {
35
- "@crombolo/core": "0.34.0",
35
+ "@crombolo/core": "0.35.2",
36
36
  "@types/react": "^19.3.0"
37
37
  }
38
38
  }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * What a page needs to call a bundle's member and public routes (story 186):
3
+ * the anti-forgery meta tag, and the script that sends it back.
4
+ * `docs/bundles.md`, Part 3.
5
+ */
6
+ import { currentAntiforgery } from './context.ts'
7
+ import { RawHtml } from './html.ts'
8
+ import { element } from './jsx-runtime.ts'
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
+ /** The header a cookie-authenticated member write carries. */
14
+ export const ANTIFORGERY_HEADER = 'Crombolo-Antiforgery'
15
+
16
+ /** The `<meta>` name `<AntiforgeryMeta />` writes and the script reads. */
17
+ export const ANTIFORGERY_META = 'crombolo-antiforgery'
18
+
19
+ export const BUNDLE_SCRIPT_PATH = '/crombolo/bundle.js'
20
+
21
+ /**
22
+ * Writes `<meta name="crombolo-antiforgery" content="…">` while a member is
23
+ * signed in, and nothing for a visitor. Put it in the layout's `<head>`.
24
+ */
25
+ export function AntiforgeryMeta(): RawHtml {
26
+ const token = currentAntiforgery()
27
+ return token ? element('meta', { name: ANTIFORGERY_META, content: token }) : new RawHtml('')
28
+ }
29
+
30
+ /**
31
+ * `crombolo.fetch(input, init)`: `fetch`, with the page's anti-forgery token
32
+ * on requests to this site. Never sent to another origin.
33
+ */
34
+ export const BUNDLE_SCRIPT = `/* crombolo bundle routes: fetch with the member's anti-forgery token */
35
+ (function () {
36
+ var crombolo = (window.crombolo = window.crombolo || {})
37
+ if (crombolo.fetch) return
38
+ crombolo.fetch = function (input, init) {
39
+ init = init || {}
40
+ var url = new URL(typeof input === 'string' || input instanceof URL ? input : input.url, location.href)
41
+ var headers = new Headers(init.headers || (input instanceof Request ? input.headers : undefined))
42
+ var meta = document.querySelector('meta[name="${ANTIFORGERY_META}"]')
43
+ if (url.origin === location.origin && meta && !headers.has('${ANTIFORGERY_HEADER}'))
44
+ headers.set('${ANTIFORGERY_HEADER}', meta.getAttribute('content'))
45
+ return fetch(input, Object.assign({ credentials: 'same-origin' }, init, { headers: headers }))
46
+ }
47
+ })()
48
+ `
package/src/context.ts CHANGED
@@ -27,6 +27,8 @@ interface RenderScope {
27
27
  blockComponent?: BlockComponentLoader
28
28
  /** A draft is being previewed in the back office. */
29
29
  preview?: boolean
30
+ /** The signed-in member's anti-forgery token, for `<AntiforgeryMeta />`. */
31
+ antiforgery?: string
30
32
  }
31
33
 
32
34
  /** Loads `components/blocks/<alias>.tsx`'s default export, or nothing when there is none. */
@@ -39,6 +41,7 @@ export interface RenderScopeOptions {
39
41
  search?: SiteSearchPort
40
42
  blockComponent?: BlockComponentLoader
41
43
  preview?: boolean
44
+ antiforgery?: string
42
45
  }
43
46
 
44
47
  /**
@@ -98,6 +101,12 @@ export function currentSiteSearch(): { page: PageProps; search: SiteSearchPort |
98
101
  return { page: scope.page, search: scope.search }
99
102
  }
100
103
 
104
+ /** The signed-in member's anti-forgery token for this render, or undefined for a visitor. */
105
+ export function currentAntiforgery(): string | undefined {
106
+ const scope = within('<AntiforgeryMeta />')
107
+ return scope.page?.member ? scope.antiforgery : undefined
108
+ }
109
+
101
110
  /**
102
111
  * An id unique within this render, for tying a label to its input or an
103
112
  * `aria-describedby` to its text. Not for CSS selectors: the colons need escaping.
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './blocks.ts'
2
+ export * from './bundle-script.ts'
2
3
  export * from './cache-policy.ts'
3
4
  export * from './context.ts'
4
5
  export * from './email.ts'
@@ -9,6 +10,7 @@ export * from './html.ts'
9
10
  export * from './jsx-attributes.ts'
10
11
  export * from './jsx-runtime.ts'
11
12
  export * from './media.ts'
13
+ export * from './media-cache.ts'
12
14
  export * from './menus.ts'
13
15
  export * from './model.ts'
14
16
  export * from './published-cache.ts'
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Media, cached apart from the published page snapshot (story 197): the items
3
+ * used most recently, by key and by file URL, held within a memory budget and
4
+ * filled from indexed lookups. A media change drops only the items it touched;
5
+ * a server that missed changes empties the cache and refills it on demand.
6
+ * docs/rendering.md, "The media cache".
7
+ */
8
+
9
+ import type { MediaItemAccess } from '@crombolo/core'
10
+ import { PublishedMedia } from './media.ts'
11
+ import type { PublishedProperty } from './model.ts'
12
+
13
+ /** One media item as a source loads it. */
14
+ export interface PublishedMediaNode {
15
+ key: string
16
+ id: number
17
+ name: string
18
+ mediaTypeAlias: string
19
+ properties: PublishedProperty[]
20
+ /** Its place in the media tree; a root item's parent is -1. */
21
+ parentId?: number
22
+ /** Its ancestors' ids and its own, root first. */
23
+ path?: string
24
+ sortOrder?: number
25
+ createDate?: Date
26
+ updateDate?: Date
27
+ /** Who it says may read and change it; open when absent. */
28
+ access?: MediaItemAccess
29
+ }
30
+
31
+ /** Where the cache fills from: indexed lookups, never a scan of the library. */
32
+ export interface MediaSource {
33
+ /** The items with these keys that are not in the recycle bin. */
34
+ loadMediaByKeys(keys: readonly string[]): Promise<PublishedMediaNode[]>
35
+ /** The items whose files are served at these `/media/…` addresses, not in the bin. */
36
+ loadMediaByUrls(urls: readonly string[]): Promise<PublishedMediaNode[]>
37
+ }
38
+
39
+ /** What a media change touched: the items, and the old paths of any that moved. */
40
+ export interface MediaChange {
41
+ keys: readonly string[]
42
+ /** Paths (`-1,1050,1063`) whose descendants' paths changed with them. */
43
+ moved?: readonly string[]
44
+ }
45
+
46
+ export interface MediaCacheOptions {
47
+ /** The memory budget in bytes; items past it are evicted, least recently used first. */
48
+ budgetBytes?: number
49
+ }
50
+
51
+ export interface MediaCacheStats {
52
+ items: number
53
+ /** The estimated size of what is held, in bytes. */
54
+ bytes: number
55
+ budgetBytes: number
56
+ hits: number
57
+ misses: number
58
+ /** Queries made to the source. */
59
+ loads: number
60
+ evictions: number
61
+ }
62
+
63
+ export const DEFAULT_MEDIA_CACHE_MEGABYTES = 64
64
+
65
+ interface Entry {
66
+ media: PublishedMedia
67
+ bytes: number
68
+ }
69
+
70
+ /** A rough size: twice the JSON of its values (UTF-16), plus the object's own fields. Pure. */
71
+ export function estimateMediaBytes(node: PublishedMediaNode): number {
72
+ let json = 0
73
+ try {
74
+ json = JSON.stringify(node.properties).length
75
+ } catch {
76
+ json = 1024
77
+ }
78
+ return 2 * (json + node.name.length + node.key.length + (node.path?.length ?? 0)) + 400
79
+ }
80
+
81
+ const lower = (key: string) => key.toLowerCase()
82
+
83
+ export class MediaCache {
84
+ #source: MediaSource
85
+ #budget: number
86
+ /** In recency order: the first is the least recently used. */
87
+ #entries = new Map<string, Entry>()
88
+ #byUrl = new Map<string, string>()
89
+ #bytes = 0
90
+ /** Lookups not yet sent, sent together once the current task yields. */
91
+ #batch = new Map<string, Array<(media: PublishedMedia | undefined) => void>>()
92
+ #batchFailures = new Map<string, Array<(error: unknown) => void>>()
93
+ #inFlight = new Map<string, Promise<PublishedMedia | undefined>>()
94
+ #urlsInFlight = new Map<string, Promise<PublishedMedia | undefined>>()
95
+ /** Moves on a clear or a drop under a path, so a load that one overtook is not kept. */
96
+ #generation = 0
97
+ /** Keys dropped while a load of them was in flight. */
98
+ #droppedInFlight = new Set<string>()
99
+ #stats = { hits: 0, misses: 0, loads: 0, evictions: 0 }
100
+
101
+ constructor(source: MediaSource, options: MediaCacheOptions = {}) {
102
+ this.#source = source
103
+ this.#budget = Math.max(0, options.budgetBytes ?? DEFAULT_MEDIA_CACHE_MEGABYTES * 1024 * 1024)
104
+ }
105
+
106
+ /** An item by key; undefined when there is none, or it is in the recycle bin. */
107
+ byKey(key: string): Promise<PublishedMedia | undefined> {
108
+ const id = lower(key)
109
+ const held = this.#touch(id)
110
+ if (held) {
111
+ this.#stats.hits += 1
112
+ return Promise.resolve(held)
113
+ }
114
+ this.#stats.misses += 1
115
+ const pending = this.#inFlight.get(id)
116
+ if (pending) return pending
117
+ const loading = new Promise<PublishedMedia | undefined>((resolve, reject) => {
118
+ const first = this.#batch.size === 0
119
+ this.#batch.set(id, [...(this.#batch.get(id) ?? []), resolve])
120
+ this.#batchFailures.set(id, [...(this.#batchFailures.get(id) ?? []), reject])
121
+ if (first) queueMicrotask(() => void this.#flush())
122
+ })
123
+ this.#inFlight.set(id, loading)
124
+ return loading
125
+ }
126
+
127
+ /** Several items by key, in one query for those not held; keyed by lowercase key. */
128
+ async byKeys(keys: readonly string[]): Promise<Map<string, PublishedMedia>> {
129
+ const found = await Promise.all([...new Set(keys.map(lower))].map((key) => this.byKey(key)))
130
+ const out = new Map<string, PublishedMedia>()
131
+ for (const media of found) if (media) out.set(lower(media.key), media)
132
+ return out
133
+ }
134
+
135
+ /** The item whose file is served at this address, `/media/<folder>/<name>`. */
136
+ byUrl(url: string): Promise<PublishedMedia | undefined> {
137
+ const key = this.#byUrl.get(url)
138
+ const held = key ? this.#touch(key) : undefined
139
+ if (held) {
140
+ this.#stats.hits += 1
141
+ return Promise.resolve(held)
142
+ }
143
+ this.#stats.misses += 1
144
+ const pending = this.#urlsInFlight.get(url)
145
+ if (pending) return pending
146
+ const generation = this.#generation
147
+ this.#stats.loads += 1
148
+ const loading = this.#source
149
+ .loadMediaByUrls([url])
150
+ .then((nodes) => {
151
+ const node = nodes[0]
152
+ if (!node) return undefined
153
+ return this.#keep(node, generation)
154
+ })
155
+ .finally(() => this.#urlsInFlight.delete(url))
156
+ this.#urlsInFlight.set(url, loading)
157
+ return loading
158
+ }
159
+
160
+ /** Drops these items, so the next read loads them again. */
161
+ drop(keys: readonly string[]): void {
162
+ for (const key of keys) {
163
+ const id = lower(key)
164
+ this.#remove(id)
165
+ if (this.#inFlight.has(id)) this.#droppedInFlight.add(id)
166
+ }
167
+ }
168
+
169
+ /** Drops every item below a path (`-1,1050`), whose paths changed with a move. */
170
+ dropUnder(path: string): void {
171
+ const prefix = `${path},`
172
+ for (const [key, entry] of [...this.#entries])
173
+ if (entry.media.path.startsWith(prefix)) this.#remove(key)
174
+ this.#generation += 1
175
+ }
176
+
177
+ /** Applies what a media change says it touched. */
178
+ apply(change: MediaChange): void {
179
+ this.drop(change.keys)
180
+ for (const path of change.moved ?? []) this.dropUnder(path)
181
+ }
182
+
183
+ /** Empties the cache, as a server that missed changes does. */
184
+ clear(): void {
185
+ this.#entries.clear()
186
+ this.#byUrl.clear()
187
+ this.#bytes = 0
188
+ this.#generation += 1
189
+ }
190
+
191
+ stats(): MediaCacheStats {
192
+ return {
193
+ items: this.#entries.size,
194
+ bytes: this.#bytes,
195
+ budgetBytes: this.#budget,
196
+ ...this.#stats,
197
+ }
198
+ }
199
+
200
+ async #flush(): Promise<void> {
201
+ const batch = this.#batch
202
+ const failures = this.#batchFailures
203
+ this.#batch = new Map()
204
+ this.#batchFailures = new Map()
205
+ const keys = [...batch.keys()]
206
+ const generation = this.#generation
207
+ this.#stats.loads += 1
208
+ try {
209
+ const nodes = await this.#source.loadMediaByKeys(keys)
210
+ const loaded = new Map<string, PublishedMedia>()
211
+ for (const node of nodes) {
212
+ const id = lower(node.key)
213
+ const stale = this.#droppedInFlight.has(id)
214
+ loaded.set(id, stale ? new PublishedMedia(node) : this.#keep(node, generation))
215
+ }
216
+ for (const key of keys) {
217
+ this.#inFlight.delete(key)
218
+ this.#droppedInFlight.delete(key)
219
+ for (const resolve of batch.get(key) ?? []) resolve(loaded.get(key))
220
+ }
221
+ } catch (error) {
222
+ for (const key of keys) {
223
+ this.#inFlight.delete(key)
224
+ this.#droppedInFlight.delete(key)
225
+ for (const reject of failures.get(key) ?? []) reject(error)
226
+ }
227
+ }
228
+ }
229
+
230
+ #touch(id: string): PublishedMedia | undefined {
231
+ const entry = this.#entries.get(id)
232
+ if (!entry) return undefined
233
+ this.#entries.delete(id)
234
+ this.#entries.set(id, entry)
235
+ return entry.media
236
+ }
237
+
238
+ /** Holds a loaded item, unless a clear overtook its load; evicts to stay in budget. */
239
+ #keep(node: PublishedMediaNode, generation: number): PublishedMedia {
240
+ const media = new PublishedMedia(node)
241
+ if (generation !== this.#generation) return media
242
+ const id = lower(node.key)
243
+ const bytes = estimateMediaBytes(node)
244
+ if (bytes > this.#budget) return media
245
+ this.#remove(id)
246
+ this.#entries.set(id, { media, bytes })
247
+ this.#bytes += bytes
248
+ if (media.url) this.#byUrl.set(media.url, id)
249
+ while (this.#bytes > this.#budget) {
250
+ const oldest = this.#entries.keys().next().value
251
+ if (oldest === undefined) break
252
+ this.#remove(oldest)
253
+ this.#stats.evictions += 1
254
+ }
255
+ return media
256
+ }
257
+
258
+ #remove(id: string): void {
259
+ const entry = this.#entries.get(id)
260
+ if (!entry) return
261
+ this.#entries.delete(id)
262
+ this.#bytes -= entry.bytes
263
+ const url = entry.media.url
264
+ if (url && this.#byUrl.get(url) === id) this.#byUrl.delete(url)
265
+ }
266
+ }
package/src/media.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  * what the Media Picker and Image Cropper yield — the item with its crops,
4
4
  * each crop reachable as a URL the media route resizes and cuts.
5
5
  */
6
+ import { type MediaItemAccess, OPEN_MEDIA } from '@crombolo/core'
6
7
  import type { PublishedProperty } from './model.ts'
7
8
 
8
9
  export interface Crop {
@@ -125,9 +126,13 @@ export class PublishedMedia {
125
126
  readonly mediaType: { alias: string }
126
127
  readonly properties: PublishedProperty[]
127
128
  readonly parentId: number
129
+ /** Its ancestors' ids and its own, root first: `-1,1050,1063`. */
130
+ readonly path: string
128
131
  readonly sortOrder: number
129
132
  readonly createDate: Date
130
133
  readonly updateDate: Date
134
+ /** Who it says may read and change it (story 196). */
135
+ readonly access: MediaItemAccess
131
136
 
132
137
  constructor(init: {
133
138
  key: string
@@ -136,9 +141,11 @@ export class PublishedMedia {
136
141
  mediaTypeAlias: string
137
142
  properties: PublishedProperty[]
138
143
  parentId?: number
144
+ path?: string
139
145
  sortOrder?: number
140
146
  createDate?: Date
141
147
  updateDate?: Date
148
+ access?: MediaItemAccess
142
149
  }) {
143
150
  this.key = init.key
144
151
  this.id = init.id
@@ -146,6 +153,8 @@ export class PublishedMedia {
146
153
  this.mediaType = { alias: init.mediaTypeAlias }
147
154
  this.properties = init.properties
148
155
  this.parentId = init.parentId ?? -1
156
+ this.path = init.path ?? `${this.parentId},${init.id}`
157
+ this.access = init.access ?? OPEN_MEDIA
149
158
  this.sortOrder = init.sortOrder ?? 0
150
159
  this.createDate = init.createDate ?? new Date(0)
151
160
  this.updateDate = init.updateDate ?? this.createDate
package/src/menus.ts CHANGED
@@ -31,7 +31,7 @@ export interface Menu {
31
31
  items: MenuItem[]
32
32
  }
33
33
 
34
- /** What a menu's links resolve against: one culture's pages, and the media. */
34
+ /** What a menu's links resolve against: one culture's pages, and the media already looked up. */
35
35
  export interface MenuLookup {
36
36
  content(key: string): PublishedContent | undefined
37
37
  media(key: string): PublishedMedia | undefined
@@ -128,6 +128,27 @@ function isSafe(url: string): boolean {
128
128
  }
129
129
  }
130
130
 
131
+ /** The media items a menu links to, at any depth, so they can be looked up in one query. Pure. */
132
+ export function menuMediaKeys(element: PublishedElement): string[] {
133
+ const keys: string[] = []
134
+ const walk = (value: unknown) => {
135
+ const blocks = parsed(value) as StoredBlocks | undefined
136
+ if (!blocks || typeof blocks !== 'object') return
137
+ for (const block of blocks.contentData ?? []) {
138
+ const own = (alias: string) => block.values?.find((v) => v.alias === alias)?.value
139
+ const links = parsed(own('link'))
140
+ const link = Array.isArray(links)
141
+ ? (links[0] as Record<string, unknown> | undefined)
142
+ : undefined
143
+ const key = link ? keyFromReference(link.unique ?? link.udi) : undefined
144
+ if (key && link?.type === 'media') keys.push(key)
145
+ walk(own('children'))
146
+ }
147
+ }
148
+ walk(element.properties.find((p) => p.alias === 'items')?.value)
149
+ return keys
150
+ }
151
+
131
152
  /** A Menu element as the tree it describes. Pure. */
132
153
  export function buildMenu(element: PublishedElement, lookup: MenuLookup): Menu {
133
154
  const own = (alias: string) => element.properties.find((p) => p.alias === alias)?.value
package/src/model.ts CHANGED
@@ -8,12 +8,19 @@
8
8
  */
9
9
 
10
10
  import type { FormSubmissionState } from '@crombolo/core'
11
- import { RawHtml } from './html.ts'
12
- import { MediaWithCrops } from './media.ts'
11
+ import type { RawHtml } from './html.ts'
12
+ import type { MediaWithCrops } from './media.ts'
13
13
  import type { MenuItem } from './menus.ts'
14
14
  import type { SeoSiteDefaults } from './seo.ts'
15
15
  import { NAVI_HIDE_ALIAS } from './url-segment.ts'
16
- import { convertValue, type ValueContext } from './values.ts'
16
+ import {
17
+ convertValue,
18
+ convertValueNow,
19
+ htmlOf,
20
+ picksOf,
21
+ textOf,
22
+ type ValueContext,
23
+ } from './values.ts'
17
24
 
18
25
  export type FallbackStrategy = 'none' | 'defaultValue' | 'language' | 'ancestors'
19
26
 
@@ -130,21 +137,28 @@ export class PublishedContent<Properties = any> {
130
137
  return this
131
138
  }
132
139
 
133
- #convert(property: PublishedProperty): unknown {
134
- return convertValue(
140
+ #convert = (property: PublishedProperty): unknown =>
141
+ convertValue(
142
+ property.editorAlias,
143
+ property.value,
144
+ this.#context as ValueContext,
145
+ property.config,
146
+ )
147
+
148
+ #convertNow = (property: PublishedProperty): unknown =>
149
+ convertValueNow(
135
150
  property.editorAlias,
136
151
  property.value,
137
152
  this.#context as ValueContext,
138
153
  property.config,
139
154
  )
140
- }
141
155
 
142
- /** A Media Picker's picks as a list, whether the picker allows one or many. */
143
- media(alias: AliasOf<Properties>, options: ValueOptions = {}): MediaWithCrops[] {
144
- const value = this.#read(alias, options)
145
- if (Array.isArray(value))
146
- return value.filter((v): v is MediaWithCrops => v instanceof MediaWithCrops)
147
- return value instanceof MediaWithCrops ? [value] : []
156
+ /**
157
+ * A Media Picker's picks as a list, whether the picker allows one or many.
158
+ * Media is looked up as it is read (story 197): `await model.media('hero')`.
159
+ */
160
+ async media(alias: AliasOf<Properties>, options: ValueOptions = {}): Promise<MediaWithCrops[]> {
161
+ return picksOf(await this.#read(alias, options))
148
162
  }
149
163
 
150
164
  /** Ancestors, nearest first; used by the `ancestors` fallback strategy. */
@@ -173,9 +187,10 @@ export class PublishedContent<Properties = any> {
173
187
  return this.#read(alias, options) as ValueOf<Properties, Alias>
174
188
  }
175
189
 
176
- #read(alias: string, options: ValueOptions): unknown {
190
+ #read(alias: string, options: ValueOptions, now = false): unknown {
191
+ const convert = now ? this.#convertNow : this.#convert
177
192
  const exact = this.#find(alias, options)
178
- if (exact && exact.value !== null && exact.value !== '') return this.#convert(exact)
193
+ if (exact && exact.value !== null && exact.value !== '') return convert(exact)
179
194
 
180
195
  switch (options.fallback) {
181
196
  case 'defaultValue':
@@ -183,13 +198,13 @@ export class PublishedContent<Properties = any> {
183
198
  case 'language': {
184
199
  for (const culture of this.#fallbackChain) {
185
200
  const found = this.#find(alias, { ...options, culture })
186
- if (found && found.value !== null && found.value !== '') return this.#convert(found)
201
+ if (found && found.value !== null && found.value !== '') return convert(found)
187
202
  }
188
203
  break
189
204
  }
190
205
  case 'ancestors': {
191
206
  for (const ancestor of this.#ancestors) {
192
- const found = ancestor.#read(alias, { ...options, fallback: 'none' })
207
+ const found = ancestor.#read(alias, { ...options, fallback: 'none' }, now)
193
208
  if (found !== null && found !== undefined && found !== '') return found
194
209
  }
195
210
  break
@@ -202,15 +217,21 @@ export class PublishedContent<Properties = any> {
202
217
  return exact?.value ?? null
203
218
  }
204
219
 
205
- /** `value()` coerced to a string, for direct use in markup. */
220
+ /**
221
+ * `value()` coerced to a string, for direct use in markup. It never waits: a
222
+ * rich text's links to media, which have to be looked up, are `#` here, so
223
+ * rich text is written with `html()`.
224
+ */
206
225
  text(alias: AliasOf<Properties>, options: ValueOptions = {}): string {
207
- const value = this.#read(alias, options)
208
- return value === null || value === undefined ? '' : String(value)
226
+ return textOf(this.#read(alias, options, true))
209
227
  }
210
228
 
211
- /** A rich-text value, marked so the renderer does not escape it. */
212
- html(alias: AliasOf<Properties>, options: ValueOptions = {}): RawHtml {
213
- return new RawHtml(this.text(alias, options))
229
+ /**
230
+ * A rich-text value, marked so the renderer does not escape it. A promise when
231
+ * it links to media, which JSX renders as it is: `{model.html('body')}`.
232
+ */
233
+ html(alias: AliasOf<Properties>, options: ValueOptions = {}): RawHtml | Promise<RawHtml> {
234
+ return htmlOf(this.#read(alias, options))
214
235
  }
215
236
 
216
237
  #find(alias: string, options: ValueOptions): PublishedProperty | undefined {
@@ -257,6 +278,7 @@ export interface PageProps<Properties = any> {
257
278
  dictionary: (key: string) => string
258
279
  /**
259
280
  * A menu's items by the menu's alias, in the request's culture: `menu('header')`.
281
+ * Read before the page renders, media included, so it stays synchronous.
260
282
  * Empty when there is no such menu (story 141; docs/rendering.md, "Menus").
261
283
  */
262
284
  menu: (alias: string) => MenuItem[]
@@ -19,8 +19,9 @@ import {
19
19
  type SchemaForm,
20
20
  withResolvedChoices,
21
21
  } from '@crombolo/core'
22
- import { PublishedMedia } from './media.ts'
23
- import { buildMenu, type Menu } from './menus.ts'
22
+ import type { PublishedMedia } from './media.ts'
23
+ import type { MediaCache } from './media-cache.ts'
24
+ import { buildMenu, type Menu, type MenuItem, menuMediaKeys } from './menus.ts'
24
25
  import { type Navigation, PublishedContent, type PublishedProperty } from './model.ts'
25
26
  import { matchRedirect, type RedirectRule } from './redirects.ts'
26
27
  import {
@@ -72,8 +73,6 @@ export interface PublishedContentSource {
72
73
  loadPublished(): Promise<PublishedNode[]>
73
74
  /** Culture and hostnames, in sort order; none when omitted. */
74
75
  loadDomains?(): Promise<PublishedDomain[]>
75
- /** Every media item not in the recycle bin, for pickers; none when omitted. */
76
- loadMedia?(): Promise<PublishedMediaNode[]>
77
76
  /** The site's languages; an invariant site when omitted. */
78
77
  loadLanguages?(): Promise<PublishedLanguage[]>
79
78
  /** Dictionary translations, by item key then culture; none when omitted. */
@@ -148,19 +147,6 @@ export interface PublishedElementNode {
148
147
  properties: PublishedProperty[]
149
148
  }
150
149
 
151
- export interface PublishedMediaNode {
152
- key: string
153
- id: number
154
- name: string
155
- mediaTypeAlias: string
156
- properties: PublishedProperty[]
157
- /** Its place in the media tree; a root item's parent is -1. */
158
- parentId?: number
159
- sortOrder?: number
160
- createDate?: Date
161
- updateDate?: Date
162
- }
163
-
164
150
  /** The published tree in one culture. */
165
151
  export interface CultureView {
166
152
  culture: string | null
@@ -197,7 +183,6 @@ export interface CacheSnapshot {
197
183
  /** Configured rules first, in their declared order, then the tracked ones. */
198
184
  redirects: RedirectRule[]
199
185
  languages: PublishedLanguage[]
200
- media: Map<string, PublishedMedia>
201
186
  /** Item key (lowercase) → culture (lowercase) → translation. */
202
187
  dictionary: Map<string, Map<string, string>>
203
188
  /** Every dictionary item, for a choice list drawn from one item's children. */
@@ -253,7 +238,6 @@ const EMPTY: CacheSnapshot = {
253
238
  routeKeys: new Map(),
254
239
  redirects: [],
255
240
  languages: [],
256
- media: new Map(),
257
241
  dictionary: new Map(),
258
242
  dictionaryOutline: [],
259
243
  contentTypeAliases: new Map(),
@@ -296,37 +280,75 @@ export interface PublishedCacheOptions {
296
280
  form?: (key: string) => SchemaForm | undefined
297
281
  /** Told on every invalidation, for whatever else is built from the same content. */
298
282
  onInvalidate?: () => void
283
+ /**
284
+ * Media, which the snapshot does not hold (story 197): pickers, links and
285
+ * menus look items up here. Without one, nothing resolves to media.
286
+ */
287
+ media?: MediaCache
299
288
  }
300
289
 
301
- /** A menu's items in a culture, from a snapshot already in hand; empty when there is none. Pure. */
302
- export function menuItemsIn(snapshot: CacheSnapshot, culture: string | null, alias: string) {
290
+ const NO_MEDIA = () => Promise.resolve(undefined)
291
+
292
+ /** A menu's items in a culture, from a snapshot already in hand; empty when there is none. */
293
+ export async function menuItemsIn(
294
+ snapshot: CacheSnapshot,
295
+ culture: string | null,
296
+ alias: string,
297
+ media?: MediaCache,
298
+ ): Promise<MenuItem[]> {
303
299
  const view =
304
300
  snapshot.views.get(viewKey(culture ?? snapshot.defaultCulture)) ??
305
301
  snapshot.views.get(viewKey(snapshot.defaultCulture))
306
- return view ? (menuIn(snapshot, view, alias)?.items ?? []) : []
302
+ return view ? ((await menuIn(view, alias, media))?.items ?? []) : []
307
303
  }
308
304
 
309
- /** The menu published under `alias` in a view, built against that view's pages. Pure. */
310
- export function menuIn(
311
- snapshot: CacheSnapshot,
305
+ const menuElements = (view: CultureView) =>
306
+ [...view.elements.values()].filter((element) => element.contentType.alias === 'menu')
307
+
308
+ const menuAliasOf = (element: PublishedElement) => {
309
+ const own = element.properties.find((p) => p.alias === MENU_ALIAS_PROPERTY)?.value
310
+ return typeof own === 'string' ? own.trim().toLowerCase() : undefined
311
+ }
312
+
313
+ /** The menu published under `alias` in a view, its media looked up in one query. */
314
+ export async function menuIn(
312
315
  view: CultureView,
313
316
  alias: string,
314
- ): Menu | undefined {
317
+ media?: MediaCache,
318
+ ): Promise<Menu | undefined> {
315
319
  const wanted = alias.trim().toLowerCase()
316
- for (const element of view.elements.values()) {
317
- if (element.contentType.alias !== 'menu') continue
318
- const own = element.properties.find((p) => p.alias === MENU_ALIAS_PROPERTY)?.value
319
- if (typeof own !== 'string' || own.trim().toLowerCase() !== wanted) continue
320
- return buildMenu(element, {
321
- content: (key) => view.byKey.get(key.toLowerCase()),
322
- media: (key) => snapshot.media.get(key.toLowerCase()),
323
- })
324
- }
325
- return undefined
320
+ const element = menuElements(view).find((e) => menuAliasOf(e) === wanted)
321
+ if (!element) return undefined
322
+ const items = media ? await media.byKeys(menuMediaKeys(element)) : new Map()
323
+ return buildMenu(element, {
324
+ content: (key) => view.byKey.get(key.toLowerCase()),
325
+ media: (key) => items.get(key.toLowerCase()),
326
+ })
326
327
  }
327
328
 
328
- /** Built the first time a snapshot is asked for a file, and gone with the snapshot. */
329
- const mediaByUrl = new WeakMap<CacheSnapshot, Map<string, PublishedMedia>>()
329
+ /** Every menu in a view by alias, their media looked up together: what a page render offers. */
330
+ export async function menusIn(
331
+ view: CultureView | undefined,
332
+ media?: MediaCache,
333
+ ): Promise<Map<string, Menu>> {
334
+ const out = new Map<string, Menu>()
335
+ if (!view) return out
336
+ const elements = menuElements(view)
337
+ if (elements.length === 0) return out
338
+ const items = media ? await media.byKeys(elements.flatMap(menuMediaKeys)) : new Map()
339
+ for (const element of elements) {
340
+ const alias = menuAliasOf(element)
341
+ if (alias === undefined || out.has(alias)) continue
342
+ out.set(
343
+ alias,
344
+ buildMenu(element, {
345
+ content: (key) => view.byKey.get(key.toLowerCase()),
346
+ media: (key) => items.get(key.toLowerCase()),
347
+ }),
348
+ )
349
+ }
350
+ return out
351
+ }
330
352
 
331
353
  export class PublishedCache {
332
354
  #source: PublishedContentSource
@@ -337,6 +359,8 @@ export class PublishedCache {
337
359
  #generation = 0
338
360
  #building: { generation: number; done: Promise<CacheSnapshot> } | undefined
339
361
  #snapshotGeneration = -1
362
+ /** A checkpoint past the snapshot's own that it is known to hold, every change between being media only. */
363
+ #coveredTo: number | undefined
340
364
 
341
365
  constructor(source: PublishedContentSource, options: PublishedCacheOptions = {}) {
342
366
  this.#source = source
@@ -369,6 +393,7 @@ export class PublishedCache {
369
393
  if (generation >= this.#snapshotGeneration && !older) {
370
394
  this.#snapshot = snapshot
371
395
  this.#snapshotGeneration = generation
396
+ this.#coveredTo = undefined
372
397
  }
373
398
  if (this.#generation === generation) this.#loaded = true
374
399
  return snapshot
@@ -534,24 +559,18 @@ export class PublishedCache {
534
559
  async menu(alias: string, culture?: string | null): Promise<Menu | undefined> {
535
560
  const snapshot = await this.snapshot()
536
561
  const view = this.#view(snapshot, culture)
537
- return view ? menuIn(snapshot, view, alias) : undefined
562
+ return view ? menuIn(view, alias, this.#options.media) : undefined
538
563
  }
539
564
 
540
- /** Every media item, in tree order. */
541
- async allMedia(): Promise<PublishedMedia[]> {
542
- return [...(await this.snapshot()).media.values()]
565
+ /** Every menu a culture's view publishes, by lowercase alias. */
566
+ async menus(culture?: string | null): Promise<Map<string, Menu>> {
567
+ const snapshot = await this.snapshot()
568
+ return menusIn(this.#view(snapshot, culture), this.#options.media)
543
569
  }
544
570
 
545
- /** The media item whose file is served at this address, `/media/<folder>/<name>`. */
546
- async mediaAt(url: string): Promise<PublishedMedia | undefined> {
547
- const snapshot = await this.snapshot()
548
- let byUrl = mediaByUrl.get(snapshot)
549
- if (!byUrl) {
550
- byUrl = new Map()
551
- for (const media of snapshot.media.values()) if (media.url) byUrl.set(media.url, media)
552
- mediaByUrl.set(snapshot, byUrl)
553
- }
554
- return byUrl.get(url)
571
+ /** Where media is looked up (story 197); undefined when this cache resolves none. */
572
+ get media(): MediaCache | undefined {
573
+ return this.#options.media
555
574
  }
556
575
 
557
576
  /** How URLs are built here: whether the top-level page is left out of paths. */
@@ -601,7 +620,7 @@ export class PublishedCache {
601
620
  const view = this.#view(snapshot, culture)
602
621
  return {
603
622
  content: (key) => view?.byKey.get(key.toLowerCase()),
604
- media: (key) => snapshot.media.get(key.toLowerCase()),
623
+ media: this.#mediaLookup(),
605
624
  form: this.#formsIn(snapshot, view, culture ?? null),
606
625
  contentTypeAlias: (key) => snapshot.contentTypeAliases.get(key.toLowerCase()),
607
626
  urlOf: (content) => content.url,
@@ -667,7 +686,21 @@ export class PublishedCache {
667
686
  /** The checkpoint and build time of the snapshot served now; nothing before the first build. */
668
687
  served(): { checkpoint: number | undefined; builtAt: Date } | undefined {
669
688
  if (this.#snapshot === EMPTY || !this.#snapshot.builtAt) return undefined
670
- return { checkpoint: this.#snapshot.checkpoint, builtAt: this.#snapshot.builtAt }
689
+ const own = this.#snapshot.checkpoint
690
+ const checkpoint =
691
+ own === undefined || this.#coveredTo === undefined ? own : Math.max(own, this.#coveredTo)
692
+ return { checkpoint, builtAt: this.#snapshot.builtAt }
693
+ }
694
+
695
+ /**
696
+ * Records that the snapshot served now also holds everything up to
697
+ * `checkpoint`, because every change since its own left the pages alone: a
698
+ * media change does not rebuild it (story 197). Ignored while it is being
699
+ * rebuilt, when the next one will say for itself.
700
+ */
701
+ covered(checkpoint: number): void {
702
+ if (!this.#loaded || this.#snapshot.checkpoint === undefined) return
703
+ if (checkpoint > (this.#coveredTo ?? this.#snapshot.checkpoint)) this.#coveredTo = checkpoint
671
704
  }
672
705
 
673
706
  async #build(): Promise<CacheSnapshot> {
@@ -692,9 +725,7 @@ export class PublishedCache {
692
725
  key.toLowerCase(),
693
726
  new Map([...translations].map(([culture, text]) => [culture.toLowerCase(), text])),
694
727
  )
695
- const media = new Map(
696
- ((await source.loadMedia?.()) ?? []).map((m) => [m.key.toLowerCase(), new PublishedMedia(m)]),
697
- )
728
+ const media = this.#mediaLookup()
698
729
  const redirects = (await source.loadRedirects?.()) ?? []
699
730
  const elementNodes = (await source.loadElements?.()) ?? []
700
731
  const contentTypeAliases = new Map(
@@ -911,7 +942,7 @@ export class PublishedCache {
911
942
  // Pickers and links resolve against this culture's view.
912
943
  const context: ValueContext<PublishedContent, PublishedMedia> = {
913
944
  content: (key) => view.byKey.get(key.toLowerCase()),
914
- media: (key) => media.get(key.toLowerCase()),
945
+ media,
915
946
  // Read lazily: the map is filled just below, with this very context, so an
916
947
  // element picking another element resolves too.
917
948
  element: (key) => view.elements.get(key.toLowerCase()),
@@ -977,7 +1008,6 @@ export class PublishedCache {
977
1008
  routeKeys,
978
1009
  redirects,
979
1010
  languages,
980
- media,
981
1011
  dictionary,
982
1012
  dictionaryOutline,
983
1013
  contentTypeAliases,
@@ -986,6 +1016,11 @@ export class PublishedCache {
986
1016
  }
987
1017
  }
988
1018
 
1019
+ #mediaLookup(): (key: string) => Promise<PublishedMedia | undefined> {
1020
+ const media = this.#options.media
1021
+ return media ? (key) => media.byKey(key) : NO_MEDIA
1022
+ }
1023
+
989
1024
  /** Form lookups whose source-backed choices resolve against this view and culture. */
990
1025
  #formsIn(
991
1026
  snapshot: ChoiceSnapshot,
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 { menuItemsIn, type PublishedCache, translate, urlsIn } from './published-cache.ts'
18
+ import { 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'
@@ -101,6 +101,8 @@ export interface RenderRequest {
101
101
  search?: SiteSearchPort
102
102
  /** A back-office preview of a draft: blocks with no component say so (story 184). */
103
103
  preview?: boolean
104
+ /** The signed-in member's anti-forgery token, written by `<AntiforgeryMeta />` (story 186). */
105
+ antiforgery?: string
104
106
  }
105
107
 
106
108
  /**
@@ -350,7 +352,10 @@ export class Renderer {
350
352
  const nav = await this.#cache.navigation(culture)
351
353
  const snapshot = await this.#cache.snapshot()
352
354
  const dictionary = (key: string) => translate(snapshot, key, culture)
353
- const menu = (alias: string) => menuItemsIn(snapshot, culture, alias)
355
+ // Menus are few, so all of them are read now, their media in one lookup,
356
+ // and `menu()` stays synchronous for the views.
357
+ const menus = await this.#cache.menus(culture)
358
+ const menu = (alias: string) => menus.get(alias.trim().toLowerCase())?.items ?? []
354
359
  const origin = (request.origin ?? 'http://localhost').replace(/\/$/, '')
355
360
  const props: PageProps = {
356
361
  model: content,
@@ -373,6 +378,7 @@ export class Renderer {
373
378
  return renderScope(props, () => this.#renderLayouts(alias, props, rendering), {
374
379
  search: request.search,
375
380
  preview: request.preview,
381
+ antiforgery: request.antiforgery,
376
382
  blockComponent: (blockAlias) => this.blockComponent(blockAlias),
377
383
  })
378
384
  }
package/src/seo.ts CHANGED
@@ -98,12 +98,12 @@ function truthy(value: unknown): boolean {
98
98
  return value === true || value === 1 || value === '1' || value === 'true'
99
99
  }
100
100
 
101
- /** The values a page offers, each with where it came from. */
102
- export function effectiveMeta(
101
+ /** The values a page offers, each with where it came from; its image is looked up in the media cache. */
102
+ export async function effectiveMeta(
103
103
  content: PublishedContent,
104
104
  context: MetaContext,
105
105
  overrides: SeoOverrides = {},
106
- ): EffectiveMeta {
106
+ ): Promise<EffectiveMeta> {
107
107
  const { origin, site } = context
108
108
  const own = (alias: string) => content.text(alias).trim()
109
109
 
@@ -121,7 +121,7 @@ export function effectiveMeta(
121
121
  ? { value: overrides.description, source: 'template' }
122
122
  : { value: undefined, source: 'none' }
123
123
 
124
- const picked = content.media(SEO_ALIASES.image)[0]?.url
124
+ const picked = (await content.media(SEO_ALIASES.image))[0]?.url
125
125
  const image: MetaValue<string | undefined> = filled(picked)
126
126
  ? { value: absoluteUrl(picked, origin), source: 'page' }
127
127
  : filled(overrides.image)
@@ -175,9 +175,9 @@ export interface SeoHeadProps extends SeoOverrides {
175
175
  }
176
176
 
177
177
  /** The head tags for search and sharing. Spread a page's props into it: `<SeoHead {...props} />`. */
178
- export function SeoHead(props: SeoHeadProps): RawHtml {
178
+ export async function SeoHead(props: SeoHeadProps): Promise<RawHtml> {
179
179
  const { model, request, urls, seo, ...overrides } = props
180
- const meta = effectiveMeta(
180
+ const meta = await effectiveMeta(
181
181
  model,
182
182
  { origin: request.origin, alternates: urls.alternates(model), site: seo },
183
183
  overrides,
package/src/values.ts CHANGED
@@ -17,8 +17,11 @@ export interface ValueContext<Content = unknown, Media = unknown> {
17
17
  * what makes a `formPicker` resolve to the form rather than to its key.
18
18
  */
19
19
  form?(key: string): SchemaForm | undefined
20
- /** Absent until the cache knows media. */
21
- media?(key: string): Media | undefined
20
+ /**
21
+ * A media item by key, looked up in the media cache (story 197); absent where
22
+ * nothing resolves media. Lookups made together go to the database as one.
23
+ */
24
+ media?(key: string): Promise<Media | undefined>
22
25
  /** A published library element by key; absent until the cache knows them. */
23
26
  element?(key: string): PublishedElement | undefined
24
27
  /** A content type's alias by key, which is all a block records of its element type. */
@@ -96,22 +99,55 @@ export class PublishedElement {
96
99
  this.#context = context
97
100
  }
98
101
 
102
+ /** A media picker's, multi-node tree picker's or multi URL picker's value is a promise. */
99
103
  value(alias: string): unknown {
100
104
  const property = this.properties.find((p) => p.alias === alias)
101
105
  if (!property) return null
102
106
  return convertValue(property.editorAlias, property.value, this.#context, property.config)
103
107
  }
104
108
 
109
+ /** A media picker's picks as a list, whether the picker allows one or many. */
110
+ async media(alias: string): Promise<MediaWithCrops[]> {
111
+ return picksOf(await this.value(alias))
112
+ }
113
+
114
+ /** `value()` as a string, read now: a rich text's media links that need looking up are `#`. */
105
115
  text(alias: string): string {
106
- const value = this.value(alias)
107
- return value === null || value === undefined ? '' : String(value)
116
+ const property = this.properties.find((p) => p.alias === alias)
117
+ if (!property) return ''
118
+ return textOf(convertValueNow(property.editorAlias, property.value, this.#context))
108
119
  }
109
120
 
110
- html(alias: string): RawHtml {
111
- return new RawHtml(this.text(alias))
121
+ /** A rich-text value, marked so the renderer does not escape it; a promise when it links to media. */
122
+ html(alias: string): RawHtml | Promise<RawHtml> {
123
+ return htmlOf(this.value(alias))
112
124
  }
113
125
  }
114
126
 
127
+ /** Whether a value is still being read. */
128
+ export const isPending = (value: unknown): value is Promise<unknown> =>
129
+ value instanceof Promise ||
130
+ (typeof value === 'object' &&
131
+ value !== null &&
132
+ typeof (value as { then?: unknown }).then === 'function')
133
+
134
+ /** A value as text; a pending one, which `text()` cannot wait for, is empty. */
135
+ export const textOf = (value: unknown): string =>
136
+ value === null || value === undefined || isPending(value) ? '' : String(value)
137
+
138
+ /** A value as markup, waiting for it first when it is still being read. */
139
+ export function htmlOf(value: unknown): RawHtml | Promise<RawHtml> {
140
+ if (!isPending(value)) return new RawHtml(textOf(value))
141
+ return Promise.resolve(value).then((resolved) => new RawHtml(textOf(resolved)))
142
+ }
143
+
144
+ /** A media picker's value as a list of picks. */
145
+ export function picksOf(value: unknown): MediaWithCrops[] {
146
+ if (Array.isArray(value))
147
+ return value.filter((v): v is MediaWithCrops => v instanceof MediaWithCrops)
148
+ return value instanceof MediaWithCrops ? [value] : []
149
+ }
150
+
115
151
  /** An element whose `value()` knows its properties, as `crombolo generate` types block content. */
116
152
  export interface TypedElement<Properties> extends PublishedElement {
117
153
  value<Alias extends keyof Properties & string>(alias: Alias): Properties[Alias]
@@ -221,19 +257,67 @@ const LOCAL_LINK = /\/?(?:\{|%7B)localLink:(?:umb:\/\/[a-z-]+\/)?([0-9a-fA-F-]{3
221
257
  /**
222
258
  * Rich text links to pages and media are stored as `/{localLink:<key>}`, so a
223
259
  * move or rename never breaks them; they become URLs when rendered. A link to
224
- * something unpublished or gone becomes `#`.
260
+ * something unpublished or gone becomes `#`. Pages resolve at once; a link to
261
+ * media is looked up in the media cache, so markup with one is a promise.
225
262
  */
226
- export function resolveLocalLinks(markup: string, context?: ValueContext): string {
227
- return markup.replace(LOCAL_LINK, (_, reference: string) => {
228
- const key = keyFromReference(reference)
229
- if (!key || !context) return '#'
263
+ export function resolveLocalLinks(
264
+ markup: string,
265
+ context?: ValueContext,
266
+ ): string | Promise<string> {
267
+ const pageUrl = (key: string | undefined) => {
268
+ if (!key || !context) return undefined
230
269
  const content = context.content(key)
231
- if (content) return context.urlOf(content)
232
- const media = context.media?.(key)
233
- return media && context.mediaUrlOf ? context.mediaUrlOf(media) : '#'
270
+ return content ? context.urlOf(content) : undefined
271
+ }
272
+ const media = new Set<string>()
273
+ for (const match of markup.matchAll(LOCAL_LINK)) {
274
+ const key = keyFromReference(match[1] as string)
275
+ if (key && context?.media && pageUrl(key) === undefined) media.add(key)
276
+ }
277
+ if (media.size === 0) return replaceLinks(markup, (key) => pageUrl(key) ?? '#')
278
+ return Promise.all(
279
+ [...media].map(async (key) => [key, await context?.media?.(key)] as const),
280
+ ).then((found) => {
281
+ const urls = new Map(
282
+ found.flatMap(([key, item]) =>
283
+ item && context?.mediaUrlOf ? [[key, context.mediaUrlOf(item)] as const] : [],
284
+ ),
285
+ )
286
+ return replaceLinks(markup, (key) => pageUrl(key) ?? (key ? urls.get(key) : undefined) ?? '#')
234
287
  })
235
288
  }
236
289
 
290
+ function replaceLinks(markup: string, urlOf: (key: string | undefined) => string): string {
291
+ return markup.replace(LOCAL_LINK, (_, reference: string) => urlOf(keyFromReference(reference)))
292
+ }
293
+
294
+ /**
295
+ * A value as `text()` reads it, without waiting: rich text with its page links
296
+ * resolved and any media link `#`, and nothing for a value only a lookup gives.
297
+ */
298
+ export function convertValueNow(
299
+ editorAlias: string,
300
+ value: unknown,
301
+ context?: ValueContext,
302
+ config: Record<string, unknown> = {},
303
+ ): unknown {
304
+ if (value === null || value === undefined) return value
305
+ if (editorAlias === 'Umbraco.RichText') {
306
+ if (typeof value !== 'string') return value
307
+ const { media: _, ...pagesOnly } = context ?? ({} as ValueContext)
308
+ return resolveLocalLinks(value, context ? (pagesOnly as ValueContext) : undefined)
309
+ }
310
+ if (ASYNC_EDITORS.has(editorAlias)) return null
311
+ return convertValue(editorAlias, value, context, config)
312
+ }
313
+
314
+ /** The editors whose values are read asynchronously, because they can name media (story 197). */
315
+ export const ASYNC_EDITORS: ReadonlySet<string> = new Set([
316
+ 'Umbraco.MediaPicker3',
317
+ 'Umbraco.MultiNodeTreePicker',
318
+ 'Umbraco.MultiUrlPicker',
319
+ ])
320
+
237
321
  /** A stored (editor-shaped) value as a template receives it. */
238
322
  export function convertValue(
239
323
  editorAlias: string,
@@ -243,15 +327,18 @@ export function convertValue(
243
327
  ): unknown {
244
328
  if (value === null || value === undefined) return value
245
329
  switch (editorAlias) {
246
- case 'Umbraco.MediaPicker3': {
247
- const picks = (Array.isArray(value) ? value : []).flatMap((raw) => {
248
- const pick = raw as Record<string, unknown>
249
- const key = keyFromReference(pick.mediaKey)
250
- const media = key ? context?.media?.(key) : undefined
251
- return media instanceof PublishedMedia ? [new MediaWithCrops(media, pick)] : []
330
+ case 'Umbraco.MediaPicker3':
331
+ return Promise.all(
332
+ (Array.isArray(value) ? value : []).map(async (raw) => {
333
+ const pick = raw as Record<string, unknown>
334
+ const key = keyFromReference(pick.mediaKey)
335
+ const media = key ? await context?.media?.(key) : undefined
336
+ return media instanceof PublishedMedia ? new MediaWithCrops(media, pick) : undefined
337
+ }),
338
+ ).then((found) => {
339
+ const picks = found.filter((pick): pick is MediaWithCrops => pick !== undefined)
340
+ return config.multiple === false ? (picks[0] ?? null) : picks
252
341
  })
253
- return config.multiple === false ? (picks[0] ?? null) : picks
254
- }
255
342
  case 'Umbraco.RichText':
256
343
  return typeof value === 'string' ? resolveLocalLinks(value, context) : value
257
344
  case 'Umbraco.ImageCropper':
@@ -284,39 +371,39 @@ export function convertValue(
284
371
  return found ? [found] : []
285
372
  })
286
373
  case 'Umbraco.MultiNodeTreePicker':
287
- return references(value).flatMap((reference) => {
288
- const key = keyFromReference(reference)
289
- const found = key ? (context?.content(key) ?? context?.media?.(key)) : undefined
290
- return found ? [found] : []
291
- })
292
- case 'Umbraco.MultiUrlPicker': {
293
- if (!Array.isArray(value)) return []
294
- return value.flatMap((raw): Link[] => {
295
- const link = raw as Record<string, unknown>
296
- const key = keyFromReference(link.unique ?? link.udi)
297
- const type = link.type === 'media' ? 'media' : key ? 'document' : 'external'
298
- const queryString = typeof link.queryString === 'string' ? link.queryString : ''
299
- let url: string | undefined
300
- if (type === 'document' && key) {
301
- const content = context?.content(key)
302
- if (!content) return []
303
- url = context?.urlOf(content)
304
- } else if (type === 'media' && key) {
305
- const media = context?.media?.(key)
306
- if (!media) return []
307
- url = context?.mediaUrlOf?.(media)
308
- } else url = safeExternalUrl(typeof link.url === 'string' ? link.url : '')
309
- return [
310
- {
374
+ return Promise.all(
375
+ references(value).map(async (reference) => {
376
+ const key = keyFromReference(reference)
377
+ if (!key) return undefined
378
+ return context?.content(key) ?? (await context?.media?.(key))
379
+ }),
380
+ ).then((found) => found.filter((item) => item !== undefined && item !== null))
381
+ case 'Umbraco.MultiUrlPicker':
382
+ return Promise.all(
383
+ (Array.isArray(value) ? value : []).map(async (raw): Promise<Link | undefined> => {
384
+ const link = raw as Record<string, unknown>
385
+ const key = keyFromReference(link.unique ?? link.udi)
386
+ const type = link.type === 'media' ? 'media' : key ? 'document' : 'external'
387
+ const queryString = typeof link.queryString === 'string' ? link.queryString : ''
388
+ let url: string | undefined
389
+ if (type === 'document' && key) {
390
+ const content = context?.content(key)
391
+ if (!content) return undefined
392
+ url = context?.urlOf(content)
393
+ } else if (type === 'media' && key) {
394
+ const media = await context?.media?.(key)
395
+ if (!media) return undefined
396
+ url = context?.mediaUrlOf?.(media)
397
+ } else url = safeExternalUrl(typeof link.url === 'string' ? link.url : '')
398
+ return {
311
399
  name: typeof link.name === 'string' ? link.name : '',
312
400
  url: `${url ?? ''}${queryString}`,
313
401
  target: typeof link.target === 'string' && link.target ? link.target : null,
314
402
  type,
315
403
  key: key ?? null,
316
- },
317
- ]
318
- })
319
- }
404
+ }
405
+ }),
406
+ ).then((links) => links.filter((link): link is Link => link !== undefined))
320
407
  case 'Umbraco.BlockList':
321
408
  return blockItems<BlockItem>(value, 'Umbraco.BlockList', context, (_, item) => item)
322
409
  case 'Umbraco.BlockGrid': {