@cloudhal/astro-renderer 0.11.0 → 0.12.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.
@@ -59,6 +59,7 @@ import {
59
59
  withRequestSite,
60
60
  } from "@cloudhal/astro-renderer/runtime";
61
61
  import { SqlCommentStore } from "@cloudhal/comments/sql";
62
+ import { RequestMetrics } from "@cloudhal/core-ts";
62
63
  import { GATES_FEATURE_VERSION } from "@cloudhal/core-ts/availability";
63
64
  import { FIELDS_FEATURE_VERSION } from "@cloudhal/core-ts/fields";
64
65
  import { D1Driver } from "@cloudhal/storage/d1";
@@ -282,10 +283,19 @@ function fromAdmin(request , env ) {
282
283
  return !!expected && timingSafeEqual(given, expected);
283
284
  }
284
285
 
286
+ /** This isolate's request counters (#293), for the admin Worker's `/api/metrics`. Never cached. */
287
+ function metricsJson(request , env , metrics ) {
288
+ const headers = { "cache-control": "no-store", "cloudflare-cdn-cache-control": "no-store" };
289
+ if (!fromAdmin(request, env))
290
+ return Response.json({ error: "unauthorized" }, { status: 401, headers });
291
+ return Response.json(metrics.toJSON(), { headers });
292
+ }
293
+
285
294
  /**
286
295
  * What this site Worker enforces (RFC-0008 §7.6–§7.7): the admin Worker asks before it lets anyone
287
- * write time gates, and (RFC-0045 §1, `fields: 2`) reference and repeater fields, which this
288
- * renderer resolves. Authenticated like the purge (it is not a public endpoint), never cached.
296
+ * write time gates, and (RFC-0045 §1) the `fields` feature: 2 for reference and repeater fields,
297
+ * which this renderer resolves, and 3 for listings, conditions and structured data by reference
298
+ * (rollout step 8, enabled in 8c; `FIELDS_FEATURE_VERSION`). Authenticated like the purge (it is not a public endpoint), never cached.
289
299
  */
290
300
  function features(request , env ) {
291
301
  const headers = { "cache-control": "no-store", "cloudflare-cdn-cache-control": "no-store" };
@@ -625,10 +635,12 @@ async function siteless(request , state )
625
635
 
626
636
  export function createSiteWorker(options = {}) {
627
637
  const searchLimiter = new SearchLimiter();
638
+ const metrics = new RequestMetrics();
628
639
  async function route(request , env , ctx ) {
629
640
  const url = new URL(request.url);
630
641
  if (url.pathname === "/__cloudhal/purge") return purge(request, env, options.siteId);
631
642
  if (url.pathname === "/__cloudhal/features") return features(request, env);
643
+ if (url.pathname === "/__cloudhal/metrics") return metricsJson(request, env, metrics);
632
644
  const moved = hostRedirect(request, env);
633
645
  if (moved) return moved;
634
646
  // RFC-0034 §4: the hostname picks the site on a multi-site Worker; everything the request
@@ -664,12 +676,18 @@ export function createSiteWorker(options = {}) {
664
676
  return {
665
677
  async fetch(request , env , ctx ) {
666
678
  // #62: the edge cache is shared by every host this Worker answers on, unless told to vary.
679
+ const started = Date.now();
680
+ let response ;
667
681
  try {
668
- return varyByHost(await route(request, env, ctx));
682
+ response = varyByHost(await route(request, env, ctx));
669
683
  } catch (error) {
670
684
  // RFC-0043 §1.8: whatever failed, the visitor gets a page and a reference to quote.
671
- return varyByHost(errorPage(request, error));
685
+ response = varyByHost(errorPage(request, error));
672
686
  }
687
+ // the admin Worker's scrape of these counters is not one of them
688
+ if (!request.url.endsWith("/__cloudhal/metrics"))
689
+ metrics.record("", response.status, (Date.now() - started) / 1000);
690
+ return response;
673
691
  },
674
692
  };
675
693
  }
@@ -10,6 +10,7 @@
10
10
  * only happens after a definition changed.
11
11
  */
12
12
  import type { ContentEntry, ContentListSection, FieldCondition, FieldOrder, Section, Site, Taxonomy, Term } from "@cloudhal/core-contracts";
13
+ import { type HopMembers } from "@cloudhal/core-ts";
13
14
  import { type ResolvedFields } from "@cloudhal/core-ts/fields";
14
15
  import type { GraphSource } from "./source.js";
15
16
  /** A theme's listing by field (RFC-0042 §4). */
@@ -50,9 +51,21 @@ export interface EntryQueryInput {
50
51
  readonly now: number;
51
52
  /** Resolved values by entry id, reused across queries (a snapshot's are immutable). */
52
53
  readonly cache?: Map<string, ResolvedFields> | undefined;
54
+ /**
55
+ * RFC-0045 step 8c: the members one-hop conditions read, as this view shows them
56
+ * (`withHopMembers`); without them a one-hop condition matches nothing.
57
+ */
58
+ readonly members?: HopMembers | undefined;
53
59
  }
54
60
  /** Runs a query over what a source shows. Pure. */
55
61
  export declare function evaluateEntryQuery(input: EntryQueryInput): FieldEntryResult;
62
+ /**
63
+ * RFC-0045 step 8c: `input` with the members its one-hop conditions read: the groups the
64
+ * candidates' references hold, through the source's own `groupMembers` (this view's gates), their
65
+ * originals among those members and the published entries. Unchanged without one-hop conditions
66
+ * or without `groupMembers` (sources from before RFC-0045: such conditions match nothing).
67
+ */
68
+ export declare function withHopMembers(source: Partial<Pick<GraphSource, "groupMembers">>, input: EntryQueryInput): Promise<EntryQueryInput>;
56
69
  /** What a list handed to a theme came from: its source and locale, or a query already run. */
57
70
  type ListOrigin = {
58
71
  readonly source: GraphSource;
@@ -19,13 +19,17 @@
19
19
 
20
20
 
21
21
 
22
+ import { hopMembersIn, hopValuesFor } from "@cloudhal/core-ts";
22
23
  import {
23
24
  compareByField,
25
+ hopGroups,
24
26
  matchesFieldQuery,
27
+ memberGroup,
25
28
  originalsOf,
26
29
  parseFieldQuery,
27
30
 
28
31
  resolveFields,
32
+ withGroupIds,
29
33
  } from "@cloudhal/core-ts/fields";
30
34
  import { matches } from "@cloudhal/core-ts/filter";
31
35
 
@@ -72,6 +76,11 @@ export const QUERY_MAX_LIMIT = 100;
72
76
 
73
77
 
74
78
 
79
+
80
+
81
+
82
+
83
+
75
84
 
76
85
 
77
86
  const published = (e ) => e.publishedAt ?? e.createdAt;
@@ -101,6 +110,18 @@ function termPredicate(input )
101
110
  }
102
111
  }
103
112
 
113
+ /** The group of an entry this source shows, by id (`COALESCE(translation.group, id)`). */
114
+ function groupLookup(input ) {
115
+ let groups ;
116
+ return (id) => {
117
+ if (!groups) {
118
+ groups = new Map();
119
+ for (const e of [...input.published, ...input.candidates]) groups.set(e.id, memberGroup(e));
120
+ }
121
+ return groups.get(id);
122
+ };
123
+ }
124
+
104
125
  /** Runs a query over what a source shows. Pure. */
105
126
  export function evaluateEntryQuery(input ) {
106
127
  const { site, query: q } = input;
@@ -110,7 +131,9 @@ export function evaluateEntryQuery(input ) {
110
131
  const byTerms = termPredicate(input);
111
132
  let rows = input.candidates.filter((e) => !byTerms || byTerms(e));
112
133
  if (q.where?.length || q.orderBy) {
113
- const parsed = parseFieldQuery(site, q.collection, { where: q.where, orderBy: q.orderBy });
134
+ // RFC-0045 step 8a: a member's id in a reference condition reads as its group's.
135
+ const where = withGroupIds(site, q.collection, q.where, groupLookup(input));
136
+ const parsed = parseFieldQuery(site, q.collection, { where, orderBy: q.orderBy });
114
137
  if (!parsed.ok) {
115
138
  const shown = parsed.issues.map((i) => `${i.path}: ${i.message}`).join("; ");
116
139
  console.warn(`cloudhal: query on ${q.collection} matches nothing: ${shown}`);
@@ -125,7 +148,16 @@ export function evaluateEntryQuery(input ) {
125
148
  cache.set(e.id, v);
126
149
  return v;
127
150
  };
128
- rows = rows.filter((e) => matchesFieldQuery(values(e), parsed.query, input.now));
151
+ const members = input.members;
152
+ const hopCache = new Map ();
153
+ rows = rows.filter((e) =>
154
+ matchesFieldQuery(
155
+ values(e),
156
+ parsed.query,
157
+ input.now,
158
+ members ? hopValuesFor(site, e, members, hopCache) : undefined,
159
+ ),
160
+ );
129
161
  rows.sort(
130
162
  (a, b) => compareByField(values(a), values(b), parsed.query) || sort(a, b) || byId(a, b),
131
163
  );
@@ -133,6 +165,32 @@ export function evaluateEntryQuery(input ) {
133
165
  return { entries: rows.slice(offset, offset + limit), total: rows.length };
134
166
  }
135
167
 
168
+ /**
169
+ * RFC-0045 step 8c: `input` with the members its one-hop conditions read: the groups the
170
+ * candidates' references hold, through the source's own `groupMembers` (this view's gates), their
171
+ * originals among those members and the published entries. Unchanged without one-hop conditions
172
+ * or without `groupMembers` (sources from before RFC-0045: such conditions match nothing).
173
+ */
174
+ export async function withHopMembers(
175
+ source ,
176
+ input ,
177
+ ) {
178
+ const { site, query: q } = input;
179
+ if (!source.groupMembers || !q.where?.some((c) => c.field.includes("."))) return input;
180
+ const parsed = parseFieldQuery(site, q.collection, { where: q.where });
181
+ if (!parsed.ok || !parsed.query.where.some((c) => c.via)) return input;
182
+ const originalOf = originalsOf(input.published);
183
+ const groups = new Set ();
184
+ for (const e of input.candidates)
185
+ for (const g of hopGroups(parsed.query, resolveFields(site, e, originalOf(e)))) groups.add(g);
186
+ if (groups.size === 0) return input;
187
+ const shown = await source.groupMembers([...groups]);
188
+ return {
189
+ ...input,
190
+ members: hopMembersIn(shown, [...[...shown.values()].flat(), ...input.published]),
191
+ };
192
+ }
193
+
136
194
  /** What a list handed to a theme came from: its source and locale, or a query already run. */
137
195
 
138
196
  const origins = new WeakMap ();
@@ -36,6 +36,7 @@ import {
36
36
 
37
37
  REFERENCE_BUDGET,
38
38
  } from "./media.js";
39
+ import { previewOptions } from "./preview-media.js";
39
40
  import { conversionsFor } from "./reference-conversions.js";
40
41
  import { referenceCards } from "./references.js";
41
42
  import { safeHref } from "./safe-urls.js";
@@ -151,7 +152,7 @@ function picture(
151
152
  defaultLocale: o.defaultLocale,
152
153
  transform: ctx.transform ?? "none",
153
154
  sizes: o.sizes,
154
- ...(ctx.preview ? { preview: true } : {}),
155
+ ...previewOptions(ctx),
155
156
  ...(ctx.budget ? { budget: ctx.budget } : {}),
156
157
  });
157
158
  return { ...image, assetId: asset.id };
@@ -23,6 +23,7 @@ import {
23
23
 
24
24
 
25
25
  rememberList,
26
+ withHopMembers,
26
27
  } from "./entry-query.js";
27
28
  import { gateIndex, splitEntries } from "./entry-views.js";
28
29
  import { entryFields, } from "./fields.js";
@@ -178,7 +179,7 @@ export class LiveSource {
178
179
  this.#store.listTerms(this.#siteId),
179
180
  ]);
180
181
  const shownHere = q.includeExpired ? split.reachable : split.listed;
181
- return evaluateEntryQuery({
182
+ const input = {
182
183
  site,
183
184
  candidates: shownHere.filter((e) => e.locale === loc),
184
185
  published: split.published,
@@ -186,7 +187,9 @@ export class LiveSource {
186
187
  terms,
187
188
  query: q,
188
189
  now: this.#now(),
189
- });
190
+ };
191
+ // RFC-0045 step 8c: one-hop conditions read the members this view shows.
192
+ return evaluateEntryQuery(await withHopMembers(this, input));
190
193
  }
191
194
 
192
195
  async search(query , options = {}) {
@@ -2,7 +2,7 @@
2
2
  import { createBlockRegistry } from "@cloudhal/core-ts/blocks";
3
3
  import { directiveExtension } from "@cloudhal/core-ts/body-blocks";
4
4
  import { checkDirective, directiveProps } from "@cloudhal/core-ts/directives";
5
- import { ASSET_HREF, assetUrl, mediaPath } from "@cloudhal/core-ts/media";
5
+ import { ASSET_HREF, mediaPath } from "@cloudhal/core-ts/media";
6
6
  import { trimChar } from "@cloudhal/core-ts/names";
7
7
  import { parseSurfaceFence } from "@cloudhal/core-ts/surfaces";
8
8
  import { Marked } from "marked";
@@ -16,6 +16,7 @@ import {
16
16
  isAttachment,
17
17
 
18
18
  } from "./media.js";
19
+ import { previewMediaSrc, previewOptions, shownAssetUrl } from "./preview-media.js";
19
20
  import { safeHref, safeSrc } from "./safe-urls.js";
20
21
  import { sanitizeHtml } from "./sanitize.js";
21
22
  import { renderSurface, surfaceProblems } from "./surfaces.js";
@@ -84,7 +85,7 @@ function localeOf() {
84
85
 
85
86
  /** A download link: the URL comes from validated parts only, the label is the markdown's (§7.6). */
86
87
  function assetLink(asset , labelHtml , title ) {
87
- const href = assetUrl(asset);
88
+ const href = shownAssetUrl(asset, current);
88
89
  const download = isAttachment(asset) ? " download" : "";
89
90
  const link = `<a href="${escapeHtml(href)}" type="${escapeHtml(asset.mediaType)}"${download}${title ? ` title="${escapeHtml(title)}"` : ""}>${labelHtml}</a>`;
90
91
  return asset.kind === "document" || asset.kind === "data" || asset.kind === "other"
@@ -108,14 +109,14 @@ function assetEmbed(asset , text , title ) {
108
109
  transform: current?.transform ?? "none",
109
110
  ...(current?.budget ? { budget: current.budget } : {}),
110
111
  sizes: "(min-width: 48rem) 48rem, 100vw",
111
- ...(current?.preview ? { preview: true } : {}),
112
+ ...previewOptions(current),
112
113
  },
113
114
  ),
114
115
  titleAttr,
115
116
  );
116
117
  case "video":
117
118
  case "audio": {
118
- const src = escapeHtml(assetUrl(asset));
119
+ const src = escapeHtml(shownAssetUrl(asset, current));
119
120
  const fallback = assetLink(asset, escapeHtml(alt || asset.slug));
120
121
  return `<${asset.kind} controls preload="metadata" src="${src}"${alt ? ` aria-label="${escapeHtml(alt)}"` : ""}${titleAttr}>${fallback}</${asset.kind}>`;
121
122
  }
@@ -280,7 +281,7 @@ md.use({
280
281
  }
281
282
  const safe = safeHref(href);
282
283
  if (!safe) return label;
283
- return `<a href="${escapeHtml(safe)}"${title ? ` title="${escapeHtml(title)}"` : ""}>${label}</a>`;
284
+ return `<a href="${escapeHtml(previewMediaSrc(safe, current))}"${title ? ` title="${escapeHtml(title)}"` : ""}>${label}</a>`;
284
285
  },
285
286
  image({ href, title, text }) {
286
287
  if (inlineOnly) return escapeHtml(text);
@@ -290,7 +291,7 @@ md.use({
290
291
  }
291
292
  const safe = safeSrc(href);
292
293
  if (!safe) return escapeHtml(text);
293
- return `<img src="${escapeHtml(safe)}" alt="${escapeHtml(text)}"${title ? ` title="${escapeHtml(title)}"` : ""} loading="lazy">`;
294
+ return `<img src="${escapeHtml(previewMediaSrc(safe, current))}" alt="${escapeHtml(text)}"${title ? ` title="${escapeHtml(title)}"` : ""} loading="lazy">`;
294
295
  },
295
296
  },
296
297
  });
@@ -452,13 +453,14 @@ function coverFigure(image , ctx )
452
453
  ...(ctx?.budget ? { budget: ctx.budget } : {}),
453
454
  sizes: "(min-width: 48rem) 48rem, 100vw",
454
455
  priority: true,
455
- ...(ctx?.preview ? { preview: true } : {}),
456
+ ...previewOptions(ctx),
456
457
  });
457
458
  const caption = assetCaption(asset, locale, defaultLocale);
458
459
  return `<figure class="ch-cover">${imgHtml(attrs)}${caption ? `<figcaption>${escapeHtml(caption)}</figcaption>` : ""}</figure>`;
459
460
  }
460
- const src = safeSrc(image.src);
461
- if (!src) return "";
461
+ const safe = safeSrc(image.src);
462
+ if (!safe) return "";
463
+ const src = previewMediaSrc(safe, ctx);
462
464
  const size =
463
465
  image.width && image.height ? ` width="${image.width}" height="${image.height}"` : "";
464
466
  return `<figure class="ch-cover"><img src="${escapeHtml(src)}" alt="${escapeHtml(image.alt)}"${size} fetchpriority="high" decoding="async"></figure>`;
@@ -17,6 +17,11 @@ export type ImageTransform = "cdn-cgi" | "none";
17
17
  export declare const WIDTH_LADDER: readonly number[];
18
18
  /** Assets by id (what a page needs to resolve `assetId` and `asset:<id>`). */
19
19
  export type AssetIndex = ReadonlyMap<string, Asset>;
20
+ /**
21
+ * #383: where a preview shows a blob asset from (Studio's signed `preview-media` URL), or
22
+ * undefined to keep its `/media/…` path. Previews are shown on Studio's origin, not the site's.
23
+ */
24
+ export type PreviewAssetUrl = (asset: Asset) => string | undefined;
20
25
  export interface MediaContext {
21
26
  readonly assets?: AssetIndex | undefined;
22
27
  readonly locale?: string | undefined;
@@ -40,6 +45,8 @@ export interface MediaContext {
40
45
  readonly budget?: PlaceholderBudget | undefined;
41
46
  /** RFC-0038: the site's collection permalinks, for links to entries (`entryPath`). */
42
47
  readonly permalinks?: PermalinkSite | undefined;
48
+ /** #383: in previews, the URL a blob asset is shown from (see `shownAssetUrl`). */
49
+ readonly previewAssetUrl?: PreviewAssetUrl | undefined;
43
50
  }
44
51
  export interface ImageAttributeOptions {
45
52
  locale: string;
@@ -50,6 +57,8 @@ export interface ImageAttributeOptions {
50
57
  quality?: number;
51
58
  priority?: boolean;
52
59
  preview?: boolean;
60
+ /** #383: with `preview`, the URL a blob asset is shown from. */
61
+ previewAssetUrl?: PreviewAssetUrl;
53
62
  /** RFC-0028 §4: the page's placeholder bytes left; spent as LQIPs are drawn (colour only after). */
54
63
  budget?: PlaceholderBudget;
55
64
  /** RFC-0028 §3: how the image meets its frame (the theme sets `object-fit` to match). */
package/dist/src/media.js CHANGED
@@ -13,7 +13,8 @@
13
13
 
14
14
 
15
15
 
16
- import { assetUrl, formatBytes, MEDIA_TYPES, mediaPath } from "@cloudhal/core-ts/media";
16
+ import { formatBytes, MEDIA_TYPES, mediaPath } from "@cloudhal/core-ts/media";
17
+ import { shownAssetUrl } from "./preview-media.js";
17
18
 
18
19
  const escapeHtml = (s ) =>
19
20
  s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -26,6 +27,12 @@ export const WIDTH_LADDER = [320, 640, 960, 1280, 1600, 1920,
26
27
  /** Assets by id (what a page needs to resolve `assetId` and `asset:<id>`). */
27
28
 
28
29
 
30
+ /**
31
+ * #383: where a preview shows a blob asset from (Studio's signed `preview-media` URL), or
32
+ * undefined to keep its `/media/…` path. Previews are shown on Studio's origin, not the site's.
33
+ */
34
+
35
+
29
36
 
30
37
 
31
38
 
@@ -48,6 +55,8 @@ export const WIDTH_LADDER = [320, 640, 960, 1280, 1600, 1920,
48
55
 
49
56
 
50
57
 
58
+
59
+
51
60
 
52
61
 
53
62
 
@@ -59,6 +68,8 @@ export const WIDTH_LADDER = [320, 640, 960, 1280, 1600, 1920,
59
68
 
60
69
 
61
70
 
71
+
72
+
62
73
   
63
74
 
64
75
   
@@ -211,7 +222,7 @@ export function imageAttributes(
211
222
  const width = asset.image?.width ?? ref?.width ?? 0;
212
223
  const height = asset.image?.height ?? ref?.height ?? 0;
213
224
  const base = {
214
- src: assetUrl(asset),
225
+ src: shownAssetUrl(asset, o),
215
226
  width,
216
227
  height,
217
228
  alt: assetAlt(asset, ref?.alt, o.locale, o.defaultLocale),
@@ -13,7 +13,12 @@
13
13
  * watched instead.
14
14
  * - **Scroll stories.** A `Scrolly`'s step crossing the middle of the screen becomes the active one;
15
15
  * its number goes to the surface's data through a `ch:set` event the interaction runtime takes
16
- * (at every motion level: it is content, not movement).
16
+ * (at every motion level: it is content, not movement). Beside the steps the band is 45–55 % of
17
+ * the screen. Where the theme stacks the sticky panel above them (phones), it is a line in the
18
+ * middle of the screen below the panel's stuck extent (its `top` plus its tallest height so far,
19
+ * capped by its `max-height`), so the current step is the one the reader sees under it (#288);
20
+ * the tallest height goes to `--ch-scrolly-panel-h` on the story, which the theme can use as the
21
+ * panel's `min-height` so that a shorter card does not pull the steps up under the line.
17
22
  * - **Scroll effects without scroll-driven CSS** (Firefox today): `--ch-p` (0–1) on each element,
18
23
  * written once a frame from passive scroll events, which the theme's fallback rules read.
19
24
  * - **Kinetic type and loops** (24c): split lines numbered once the line breaks are known; a
@@ -32,8 +37,8 @@
32
37
  * Nothing moves when the page's level is `none` or the reader asks for reduced motion.
33
38
  */
34
39
  export declare const MOTION_SCRIPT: {
35
- readonly path: "/_cloudhal/motion.4.js";
40
+ readonly path: "/_cloudhal/motion.5.js";
36
41
  readonly code: string;
37
42
  };
38
43
  /** Earlier names of the module, served with the current code (each version only adds). */
39
- export declare const MOTION_SCRIPT_ALIASES: readonly ["/_cloudhal/motion.1.js", "/_cloudhal/motion.2.js", "/_cloudhal/motion.3.js"];
44
+ export declare const MOTION_SCRIPT_ALIASES: readonly ["/_cloudhal/motion.1.js", "/_cloudhal/motion.2.js", "/_cloudhal/motion.3.js", "/_cloudhal/motion.4.js"];
@@ -13,7 +13,12 @@
13
13
  * watched instead.
14
14
  * - **Scroll stories.** A `Scrolly`'s step crossing the middle of the screen becomes the active one;
15
15
  * its number goes to the surface's data through a `ch:set` event the interaction runtime takes
16
- * (at every motion level: it is content, not movement).
16
+ * (at every motion level: it is content, not movement). Beside the steps the band is 45–55 % of
17
+ * the screen. Where the theme stacks the sticky panel above them (phones), it is a line in the
18
+ * middle of the screen below the panel's stuck extent (its `top` plus its tallest height so far,
19
+ * capped by its `max-height`), so the current step is the one the reader sees under it (#288);
20
+ * the tallest height goes to `--ch-scrolly-panel-h` on the story, which the theme can use as the
21
+ * panel's `min-height` so that a shorter card does not pull the steps up under the line.
17
22
  * - **Scroll effects without scroll-driven CSS** (Firefox today): `--ch-p` (0–1) on each element,
18
23
  * written once a frame from passive scroll events, which the theme's fallback rules read.
19
24
  * - **Kinetic type and loops** (24c): split lines numbered once the line breaks are known; a
@@ -78,10 +83,22 @@ for(const sc of d.querySelectorAll(".ch-scrolly[data-ch-step-path]")){
78
83
  const steps=[...sc.children].filter((c)=>c.classList.contains("ch-step"));const path=sc.getAttribute("data-ch-step-path");
79
84
  const root=sc.closest("[data-ch-surface]");if(!steps.length||!path||!root||!("IntersectionObserver"in window))continue;
80
85
  sc.setAttribute("data-ch-live","");
81
- const so=new IntersectionObserver((es)=>{for(const e of es){if(!e.isIntersecting)continue;const n=steps.indexOf(e.target)+1;
86
+ const panel=sc.firstElementChild&&!sc.firstElementChild.classList.contains("ch-step")?sc.firstElementChild:null;
87
+ let so=null,band="",tall=0,cur=0;
88
+ const pick=(es)=>{for(const e of es){if(!e.isIntersecting)continue;const n=steps.indexOf(e.target)+1;if(n===cur)continue;cur=n;
82
89
  for(const s of steps)s.toggleAttribute("data-ch-active",s===e.target);sc.setAttribute("data-ch-current",String(n));
83
- root.dispatchEvent(new CustomEvent("ch:set",{detail:{path,value:n}}));}},{rootMargin:"-45% 0px -45% 0px",threshold:0});
84
- for(const s of steps)so.observe(s);}
90
+ root.dispatchEvent(new CustomEvent("ch:set",{detail:{path,value:n}}));}};
91
+ const place=()=>{let m="-45% 0px -45% 0px";
92
+ if(panel){const cs=getComputedStyle(panel),p=panel.getBoundingClientRect(),f=steps[0].getBoundingClientRect();
93
+ if(cs.position==="sticky"&&p.left<f.right&&f.left<p.right){const vh=innerHeight,mh=parseFloat(cs.maxHeight),h=panel.offsetHeight;
94
+ if(h>tall){tall=h;const px=(k)=>parseFloat(cs[k])||0;
95
+ const pad=cs.boxSizing==="border-box"?0:px("paddingTop")+px("paddingBottom")+px("borderTopWidth")+px("borderBottomWidth");
96
+ sc.style.setProperty("--ch-scrolly-panel-h",Math.max(0,tall-pad)+"px");}
97
+ const line=Math.round((Math.min(vh*0.8,(parseFloat(cs.top)||0)+(mh>=0?Math.min(mh,tall):tall))+vh)/2);
98
+ m=-line+"px 0px "+(line+1-vh)+"px 0px";}else if(tall){tall=0;sc.style.removeProperty("--ch-scrolly-panel-h");}}
99
+ if(m===band)return;band=m;if(so)so.disconnect();so=new IntersectionObserver(pick,{rootMargin:m,threshold:0});for(const s of steps)so.observe(s);};
100
+ place();addEventListener("resize",()=>{tall=0;sc.style.removeProperty("--ch-scrolly-panel-h");place();},{passive:true});
101
+ if(panel&&"ResizeObserver"in window)new ResizeObserver(()=>place()).observe(panel);}
85
102
  if(moving&&!(window.CSS&&CSS.supports("animation-timeline: view()"))){
86
103
  const els=[...d.querySelectorAll("[data-ch-scroll],.ch-progress")];
87
104
  if(els.length){let raf=0;const tick=()=>{raf=0;const vh=innerHeight,sh=d.documentElement.scrollHeight;
@@ -105,11 +122,12 @@ d.addEventListener("pointerout",(e)=>{const el=e.target instanceof Element&&e.ta
105
122
  if(el&&!(e.relatedTarget instanceof Node&&el.contains(e.relatedTarget))){el.style.removeProperty("--ch-mx");el.style.removeProperty("--ch-my");}},{passive:true});}
106
123
  `;
107
124
 
108
- export const MOTION_SCRIPT = { path: "/_cloudhal/motion.4.js", code } ;
125
+ export const MOTION_SCRIPT = { path: "/_cloudhal/motion.5.js", code } ;
109
126
 
110
127
  /** Earlier names of the module, served with the current code (each version only adds). */
111
128
  export const MOTION_SCRIPT_ALIASES = [
112
129
  "/_cloudhal/motion.1.js",
113
130
  "/_cloudhal/motion.2.js",
114
131
  "/_cloudhal/motion.3.js",
132
+ "/_cloudhal/motion.4.js",
115
133
  ] ;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * #383: the one place a preview's media URLs are rewritten. Previews are shown on Studio's origin
3
+ * (a served, sandboxed document or an iframe's `srcdoc`), where the site's `/media/…` paths do not
4
+ * exist; the caller (the admin API) passes `previewAssetUrl`, which names a signed URL Studio
5
+ * serves. Published pages never set it. External (https) assets keep their own URL.
6
+ */
7
+ import type { Asset } from "@cloudhal/core-contracts";
8
+ import type { MediaContext, PreviewAssetUrl } from "./media.js";
9
+ interface PreviewUrlOptions {
10
+ readonly preview?: boolean | undefined;
11
+ readonly previewAssetUrl?: PreviewAssetUrl | undefined;
12
+ }
13
+ /** Where an asset is shown from: in a preview with the hook, a blob's signed URL; else `assetUrl`. */
14
+ export declare function shownAssetUrl(asset: Asset, o: PreviewUrlOptions | undefined): string;
15
+ /** The preview fields of `imageAttributes` options for a render context (none on the site). */
16
+ export declare function previewOptions(ctx: PreviewUrlOptions | undefined): {
17
+ preview: true;
18
+ previewAssetUrl?: PreviewAssetUrl;
19
+ } | Record<string, never>;
20
+ /**
21
+ * A site-relative `/media/<16 hex>/<slug>.<ext>` written as a plain URL (a markdown image, a
22
+ * legacy `image.src` without `assetId`) resolved to its asset by the prefix, then shown like an
23
+ * asset. Anything else, or a path whose asset the render does not know, is returned unchanged.
24
+ */
25
+ export declare function previewMediaSrc(src: string, ctx: MediaContext | undefined): string;
26
+ export {};
@@ -0,0 +1,60 @@
1
+ /**
2
+ * #383: the one place a preview's media URLs are rewritten. Previews are shown on Studio's origin
3
+ * (a served, sandboxed document or an iframe's `srcdoc`), where the site's `/media/…` paths do not
4
+ * exist; the caller (the admin API) passes `previewAssetUrl`, which names a signed URL Studio
5
+ * serves. Published pages never set it. External (https) assets keep their own URL.
6
+ */
7
+
8
+ import { assetUrl, MEDIA_ROUTE, mediaPrefix } from "@cloudhal/core-ts/media";
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+ /** Where an asset is shown from: in a preview with the hook, a blob's signed URL; else `assetUrl`. */
17
+ export function shownAssetUrl(asset , o ) {
18
+ if (o?.preview && o.previewAssetUrl && asset.storage.kind === "blob")
19
+ return o.previewAssetUrl(asset) ?? assetUrl(asset);
20
+ return assetUrl(asset);
21
+ }
22
+
23
+ /** The preview fields of `imageAttributes` options for a render context (none on the site). */
24
+ export function previewOptions(
25
+ ctx ,
26
+ ) {
27
+ if (!ctx?.preview) return {};
28
+ return ctx.previewAssetUrl
29
+ ? { preview: true, previewAssetUrl: ctx.previewAssetUrl }
30
+ : { preview: true };
31
+ }
32
+
33
+ /** Blob assets by their 16-hex media prefix, built once per index. */
34
+ const byPrefix = new WeakMap ();
35
+
36
+ function assetAtPrefix(assets , prefix ) {
37
+ let map = byPrefix.get(assets);
38
+ if (!map) {
39
+ map = new Map();
40
+ for (const a of assets.values())
41
+ if (a.storage.kind === "blob") map.set(mediaPrefix(a.sha256), a);
42
+ byPrefix.set(assets, map);
43
+ }
44
+ return map.get(prefix);
45
+ }
46
+
47
+ /**
48
+ * A site-relative `/media/<16 hex>/<slug>.<ext>` written as a plain URL (a markdown image, a
49
+ * legacy `image.src` without `assetId`) resolved to its asset by the prefix, then shown like an
50
+ * asset. Anything else, or a path whose asset the render does not know, is returned unchanged.
51
+ */
52
+ export function previewMediaSrc(src , ctx ) {
53
+ if (!ctx?.preview || !ctx.previewAssetUrl || !ctx.assets) return src;
54
+ // Bounded before the (anchored) route pattern runs: a media path is short.
55
+ if (src.length > 160 || !src.startsWith("/media/")) return src;
56
+ const m = MEDIA_ROUTE.exec(src);
57
+ if (!m || m[4] !== undefined) return src;
58
+ const asset = assetAtPrefix(ctx.assets, m[1] );
59
+ return asset ? shownAssetUrl(asset, ctx) : src;
60
+ }
@@ -58,6 +58,8 @@ export interface ArchivePreviewInput {
58
58
  readonly termId: string;
59
59
  /** The site's entries (any status): the archive lists the published ones in the default locale. */
60
60
  readonly entries: readonly ContentEntry[];
61
+ /** #383: the assets the term shows and how a preview names them (`MediaContext`). */
62
+ readonly media?: MediaContext | undefined;
61
63
  /** Entries per page (the blog starter's `ARCHIVE_PAGE_SIZE`). */
62
64
  readonly perPage?: number;
63
65
  }
@@ -83,3 +85,10 @@ export interface ArchivePreviewDocument extends PreviewDocument {
83
85
  * goes public; `state` and `reason` say what the public route answers today (`archiveState`).
84
86
  */
85
87
  export declare function renderArchivePreview(site: Site, input: ArchivePreviewInput): ArchivePreviewDocument;
88
+ /**
89
+ * The same policy `previewResponse` (packages/api) sends as a header, repeated in the document so
90
+ * it also holds where the document is shown without that response (an iframe's `srcdoc`). Images:
91
+ * any https host, data URLs, and Studio's own signed `preview-media` URLs (#383), which are
92
+ * http on a local `cloudhal studio`; a sandboxed `srcdoc` has no origin of its own to call 'self'.
93
+ */
94
+ export declare const PREVIEW_IMG_SRC = "'self' https: data: http://localhost:* http://127.0.0.1:*";
@@ -8,8 +8,8 @@
8
8
 
9
9
 
10
10
 
11
- import { entryPath } from "@cloudhal/core-ts";
12
- import { derivedGate } from "@cloudhal/core-ts/fields";
11
+ import { entryPath, hopMembersIn } from "@cloudhal/core-ts";
12
+ import { derivedGate, memberGroup } from "@cloudhal/core-ts/fields";
13
13
  import {
14
14
 
15
15
 
@@ -23,6 +23,7 @@ import { evaluateEntryQuery, listsByField, sectionQuery } from "./entry-query.js
23
23
  import { formatGateTime, gateNotice } from "./gates.js";
24
24
  import { renderBody, renderEntryArticle, renderMarkdown, safeHref, safeSrc } from "./markdown.js";
25
25
  import { assetCaption, imageAttributes, imgHtml, } from "./media.js";
26
+ import { previewMediaSrc, previewOptions } from "./preview-media.js";
26
27
  import { archiveHead, siteOrigin } from "./seo.js";
27
28
  import { pickEntries, renderSurface, surfaceSources } from "./surfaces.js";
28
29
  import {
@@ -58,11 +59,12 @@ function sectionImage(image , media )
58
59
  transform: "none",
59
60
  sizes: "(min-width: 48rem) 48rem, 100vw",
60
61
  preview: true,
62
+ ...previewOptions(media),
61
63
  }),
62
64
  );
63
65
  }
64
66
  const src = safeSrc(image.src);
65
- return src ? `<img src="${esc(src)}" alt="${esc(image.alt)}">` : "";
67
+ return src ? `<img src="${esc(previewMediaSrc(src, media))}" alt="${esc(image.alt)}">` : "";
66
68
  }
67
69
 
68
70
  /** The collections a page's sections list: content lists and surfaces' entry sources. */
@@ -107,6 +109,15 @@ function previewList(
107
109
  const all = entries[section.collection] ?? [];
108
110
  if (listing && listsByField(section)) {
109
111
  const { filter: _ignored, ...query } = sectionQuery(section);
112
+ // RFC-0045 step 8c: one-hop conditions read the preview's entries of every collection.
113
+ const pool = Object.values(entries).flat();
114
+ const shown = new Map ();
115
+ for (const e of pool) {
116
+ const g = memberGroup(e);
117
+ const list = shown.get(g);
118
+ if (list) list.push(e);
119
+ else shown.set(g, [e]);
120
+ }
110
121
  return evaluateEntryQuery({
111
122
  site: listing.site,
112
123
  candidates: all,
@@ -115,6 +126,7 @@ function previewList(
115
126
  terms: [],
116
127
  query,
117
128
  now: listing.now ?? Date.now(),
129
+ members: hopMembersIn(shown, pool),
118
130
  }).entries;
119
131
  }
120
132
  return [...all]
@@ -339,6 +351,8 @@ export function renderFragmentPreview(
339
351
 
340
352
 
341
353
 
354
+
355
+
342
356
 
343
357
 
344
358
 
@@ -479,7 +493,9 @@ export function renderArchivePreview(
479
493
  const label = term.labels[locale];
480
494
  const kind =
481
495
  taxonomy.labels[locale]?.singular ?? Object.values(taxonomy.labels)[0]?.singular ?? "";
482
- const imageSrc = term.image ? safeSrc(term.image.src) : undefined;
496
+ const media = previewMedia(site, input.media);
497
+ const safeImage = term.image ? safeSrc(term.image.src) : undefined;
498
+ const imageSrc = safeImage ? previewMediaSrc(safeImage, media) : undefined;
483
499
  const crumbs = [
484
500
  { name: words.home, href: "/" },
485
501
  ...view.trail.map((t) => ({ name: t.name, href: t.href })),
@@ -521,7 +537,7 @@ export function renderArchivePreview(
521
537
  term.image && imageSrc
522
538
  ? `<img class="ch-archive-image" src="${esc(imageSrc)}" alt="${esc(term.image.alt)}"${term.image.width ? ` width="${term.image.width}"` : ""}${term.image.height ? ` height="${term.image.height}"` : ""}>`
523
539
  : ""
524
- }${label?.description ? `<div class="ch-richtext">${renderMarkdown(label.description)}</div>` : ""}</header>${list}${pagination}</section>`;
540
+ }${label?.description ? `<div class="ch-richtext">${renderMarkdown(label.description, media)}</div>` : ""}</header>${list}${pagination}</section>`;
525
541
  return {
526
542
  title: head.title,
527
543
  path: root,
@@ -617,10 +633,12 @@ const PREVIEW_CSS =
617
633
 
618
634
  /**
619
635
  * The same policy `previewResponse` (packages/api) sends as a header, repeated in the document so
620
- * it also holds where the document is shown without that response (an iframe's `srcdoc`).
636
+ * it also holds where the document is shown without that response (an iframe's `srcdoc`). Images:
637
+ * any https host, data URLs, and Studio's own signed `preview-media` URLs (#383), which are
638
+ * http on a local `cloudhal studio`; a sandboxed `srcdoc` has no origin of its own to call 'self'.
621
639
  */
622
- const PREVIEW_CSP =
623
- "default-src 'none'; img-src https: data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'";
640
+ export const PREVIEW_IMG_SRC = "'self' https: data: http://localhost:* http://127.0.0.1:*";
641
+ const PREVIEW_CSP = `default-src 'none'; img-src ${PREVIEW_IMG_SRC}; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'`;
624
642
 
625
643
  function document(
626
644
  site ,
@@ -26,6 +26,7 @@ import {
26
26
 
27
27
 
28
28
  rememberList,
29
+ withHopMembers,
29
30
  } from "./entry-query.js";
30
31
  import { gateIndex, splitEntries } from "./entry-views.js";
31
32
  import { entryFields, } from "./fields.js";
@@ -516,7 +517,7 @@ export class SnapshotSource {
516
517
  const view = await this.#current();
517
518
  const loc = q.locale ?? view.site.defaultLocale;
518
519
  const shownHere = q.includeExpired ? view.reachable : view.entries;
519
- return evaluateEntryQuery({
520
+ const input = {
520
521
  site: view.site,
521
522
  candidates: shownHere.filter((e) => e.collection === q.collection && e.locale === loc),
522
523
  published: view.published,
@@ -525,7 +526,9 @@ export class SnapshotSource {
525
526
  query: q,
526
527
  now: this.#clock?.() ?? Date.now(),
527
528
  cache: view.resolved,
528
- });
529
+ };
530
+ // RFC-0045 step 8c: one-hop conditions read the members this view shows.
531
+ return evaluateEntryQuery(await withHopMembers(this, input));
529
532
  }
530
533
 
531
534
  async search(query , options = {}) {
@@ -18,6 +18,7 @@ import { messages as nl } from "./nl.js";
18
18
  import { messages as pl } from "./pl.js";
19
19
  import { messages as pt_BR } from "./pt-BR.js";
20
20
  import { messages as ru } from "./ru.js";
21
+ import { messages as sv } from "./sv.js";
21
22
  import { messages as tr } from "./tr.js";
22
23
  import { messages as uk } from "./uk.js";
23
24
  import { messages as zh_Hans } from "./zh-Hans.js";
@@ -39,6 +40,7 @@ export const STATUS_CATALOG = {
39
40
  "pt-BR": { messages: pt_BR, dir: "ltr" },
40
41
  nl: { messages: nl, dir: "ltr" },
41
42
  pl: { messages: pl, dir: "ltr" },
43
+ sv: { messages: sv, dir: "ltr" },
42
44
  ru: { messages: ru, dir: "ltr" },
43
45
  uk: { messages: uk, dir: "ltr" },
44
46
  ja: { messages: ja, dir: "ltr" },
@@ -1,34 +1,34 @@
1
1
  // Generated by `pnpm i18n:import` (ADR-0034): es status page messages.
2
2
  // Do not edit: change the translation file and import it; only English is edited here.
3
- // hash: 328d0dacfe8b0e76
3
+ // hash: 7f47ff4c01101ad8
4
4
 
5
5
 
6
6
  export const messages = {
7
7
  notPublished: {
8
8
  title: "Próximamente",
9
- body: "Este sitio aún no está publicado. Vuelve pronto.",
9
+ body: "Este sitio aún no está publicado. Pronto estará disponible.",
10
10
  },
11
11
  maintenance: {
12
12
  title: "Volveremos pronto",
13
- body: "Este sitio está en mantenimiento. Gracias por tu paciencia.",
13
+ body: "Este sitio está en mantenimiento. Gracias por la paciencia.",
14
14
  },
15
15
  comingSoon: {
16
16
  title: "Próximamente",
17
- body: "Este sitio aún no está abierto. Vuelve pronto.",
17
+ body: "Este sitio aún no está abierto. Pronto estará disponible.",
18
18
  },
19
19
  unavailable: {
20
20
  title: "Temporalmente no disponible",
21
- body: "No es posible acceder a este sitio en este momento. Inténtalo de nuevo en unos minutos.",
21
+ body: "No es posible acceder a este sitio en este momento. Se puede volver a intentar en unos minutos.",
22
22
  },
23
23
  error: {
24
24
  title: "Algo salió mal",
25
- body: "No se pudo mostrar esta página. Inténtalo de nuevo en un momento.",
25
+ body: "No se pudo mostrar esta página. Se puede volver a intentar en un momento.",
26
26
  },
27
27
  previewExpired: {
28
28
  title: "Este enlace de vista previa ha caducado",
29
- body: "Pide un enlace nuevo para ver esta versión.",
29
+ body: "Para ver esta versión se necesita un enlace nuevo.",
30
30
  },
31
- backBy: "Volvemos el {time}",
31
+ backBy: "Disponible de nuevo: {time}",
32
32
  reference: "Referencia: {reference}",
33
33
  builtWith: "Creado con Cloudhal",
34
34
  };
@@ -0,0 +1,2 @@
1
+ import type { StatusMessages } from "./en.js";
2
+ export declare const messages: StatusMessages;
@@ -0,0 +1,34 @@
1
+ // Generated by `pnpm i18n:import` (ADR-0034): sv status page messages.
2
+ // Do not edit: change the translation file and import it; only English is edited here.
3
+ // hash: 529ba2d55a63ad60
4
+
5
+
6
+ export const messages = {
7
+ notPublished: {
8
+ title: "Kommer snart",
9
+ body: "Webbplatsen är inte publicerad ännu. Den blir tillgänglig snart.",
10
+ },
11
+ maintenance: {
12
+ title: "Snart tillbaka",
13
+ body: "Webbplatsen är nere för underhåll. Tack för tålamodet.",
14
+ },
15
+ comingSoon: {
16
+ title: "Kommer snart",
17
+ body: "Webbplatsen har inte öppnat ännu. Den öppnar snart.",
18
+ },
19
+ unavailable: {
20
+ title: "Tillfälligt otillgänglig",
21
+ body: "Webbplatsen kan inte nås just nu. Det går att försöka igen om några minuter.",
22
+ },
23
+ error: {
24
+ title: "Något gick fel",
25
+ body: "Sidan kunde inte visas. Det går att försöka igen om en stund.",
26
+ },
27
+ previewExpired: {
28
+ title: "Förhandsvisningslänken har gått ut",
29
+ body: "En ny länk behövs för att se den här versionen.",
30
+ },
31
+ backBy: "Tillbaka senast {time}",
32
+ reference: "Referens: {reference}",
33
+ builtWith: "Byggd med Cloudhal",
34
+ };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * RFC-0045 step 8b: the referenced entries a structured-data preset reads (`ReferenceValueSource`),
3
+ * for `entryStructuredData`. For each reference field a source names, the member the view shows:
4
+ * the source's `groupMembers` (gated by the view), then `pickMember` in the entry's language (the
5
+ * default language's under `default-with-notice`), then `resolveFields` with the member's
6
+ * same-site original, so a translation member's non-localized `street` comes from its original.
7
+ * One `groupMembers` call for every field; a field without a member reads as nothing.
8
+ */
9
+ import type { ContentEntry, Site } from "@cloudhal/core-contracts";
10
+ import { resolveFields } from "@cloudhal/core-ts/fields";
11
+ import type { ReferencedValues } from "@cloudhal/core-ts/structured-data";
12
+ import type { SqlDriver } from "@cloudhal/storage";
13
+ import type { GraphSource } from "./source.js";
14
+ type MembersSource = Partial<Pick<GraphSource, "groupMembers">>;
15
+ /** The `references` of `StructuredDataContext`: one entry per field with a member the view shows. */
16
+ export declare function referencedValues(input: {
17
+ readonly source: MembersSource;
18
+ readonly site: Site;
19
+ readonly entry: ContentEntry;
20
+ readonly resolved: ReturnType<typeof resolveFields>;
21
+ readonly origin: string;
22
+ }): Promise<Map<string, ReferencedValues> | undefined>;
23
+ /**
24
+ * The previews' `groupMembers` (MCP `preview_structured_data`, the API's structured-data route):
25
+ * the working copy's published members, what the site would show once the entry is published.
26
+ * Time gates are not applied: a preview shows the mapping, not a moment.
27
+ */
28
+ export declare function previewGroupMembers(sql: SqlDriver, siteId: string): (groupIds: readonly string[]) => Promise<Map<string, ContentEntry[]>>;
29
+ export {};
@@ -0,0 +1,91 @@
1
+ /**
2
+ * RFC-0045 step 8b: the referenced entries a structured-data preset reads (`ReferenceValueSource`),
3
+ * for `entryStructuredData`. For each reference field a source names, the member the view shows:
4
+ * the source's `groupMembers` (gated by the view), then `pickMember` in the entry's language (the
5
+ * default language's under `default-with-notice`), then `resolveFields` with the member's
6
+ * same-site original, so a translation member's non-localized `street` comes from its original.
7
+ * One `groupMembers` call for every field; a field without a member reads as nothing.
8
+ */
9
+
10
+ import { getGroupMembers } from "@cloudhal/core-ts";
11
+ import { pickMember, resolveFields } from "@cloudhal/core-ts/fields";
12
+ import { itemUrl } from "@cloudhal/core-ts/locale-paths";
13
+
14
+
15
+
16
+
17
+
18
+
19
+ /** The reference fields the entry's preset reads, with each one's group id and target. */
20
+ function namedReferences(
21
+ site ,
22
+ entry ,
23
+ resolved ,
24
+ ) {
25
+ const preset = site.collections?.[entry.collection]?.structuredData;
26
+ const out = new Map ();
27
+ for (const source of Object.values(preset?.properties ?? {})) {
28
+ if (source?.kind !== "reference" || out.has(source.field)) continue;
29
+ const field = resolved[source.field];
30
+ if (field?.def.type !== "reference" || typeof field.value !== "string") continue;
31
+ out.set(source.field, { groupId: field.value, collections: field.def.collections });
32
+ }
33
+ return out;
34
+ }
35
+
36
+ /** A member's same-site original among the members the view shows (RFC-0041 §5). */
37
+ function originalAmong(members , member ) {
38
+ const g = member.translation?.group;
39
+ if (!g || g === member.id || member.translation?.source?.siteId !== undefined) return undefined;
40
+ return members.find((m) => m.id === g);
41
+ }
42
+
43
+ /** The `references` of `StructuredDataContext`: one entry per field with a member the view shows. */
44
+ export async function referencedValues(input
45
+
46
+
47
+
48
+
49
+
50
+ ) {
51
+ const { source, site, entry, resolved, origin } = input;
52
+ const named = namedReferences(site, entry, resolved);
53
+ if (named.size === 0 || !source.groupMembers) return undefined;
54
+ const groups = [...new Set([...named.values()].map((n) => n.groupId))];
55
+ const members = await source.groupMembers(groups);
56
+ const out = new Map ();
57
+ for (const [field, { groupId, collections }] of named) {
58
+ const all = members.get(groupId) ?? [];
59
+ const picked = pickMember(groupId, all, {
60
+ locale: entry.locale,
61
+ defaultLocale: site.defaultLocale,
62
+ fallback: site.localization?.fallback,
63
+ collections,
64
+ });
65
+ if (!picked) continue;
66
+ const m = picked.member;
67
+ out.set(field, {
68
+ member: m,
69
+ fields: resolveFields(site, m, originalAmong(all, m)),
70
+ url: itemUrl(site, origin, m),
71
+ });
72
+ }
73
+ return out;
74
+ }
75
+
76
+ /**
77
+ * The previews' `groupMembers` (MCP `preview_structured_data`, the API's structured-data route):
78
+ * the working copy's published members, what the site would show once the entry is published.
79
+ * Time gates are not applied: a preview shows the mapping, not a moment.
80
+ */
81
+ export function previewGroupMembers(
82
+ sql ,
83
+ siteId ,
84
+ ) {
85
+ return async (groupIds) => {
86
+ const read = await getGroupMembers(sql, siteId, groupIds);
87
+ return new Map(
88
+ [...read].map(([g, members]) => [g, members.filter((m) => m.status === "published")]),
89
+ );
90
+ };
91
+ }
@@ -7,20 +7,23 @@
7
7
  * The document is built by core-ts's pure `structuredDataFor` from typed values (resolved, so a
8
8
  * translation reads its original's non-localized ones), capped at 32 KB, and rendered through
9
9
  * `jsonLdText` by `SeoHead.astro` like every other JSON-LD block. An entry missing a required value
10
- * keeps its `BlogPosting`; the `BreadcrumbList` always stays.
10
+ * keeps its `BlogPosting`; the `BreadcrumbList` always stays. RFC-0045 step 8b: reference sources
11
+ * read the member the source's `groupMembers` shows (`structured-data-references.ts`); a source
12
+ * without `groupMembers` gives them nothing.
11
13
  */
12
14
  import type { ContentEntry } from "@cloudhal/core-contracts";
13
15
  import { type StructuredDataResult } from "@cloudhal/core-ts/structured-data";
14
16
  import { type MediaContext } from "./media.js";
15
17
  import type { HeadMeta } from "./seo.js";
16
18
  import type { GraphSource } from "./source.js";
19
+ export { previewGroupMembers } from "./structured-data-references.js";
17
20
  export interface StructuredDataOptions {
18
21
  /** The site's public origin (`siteOrigin`); every URL in the document is absolute on it. */
19
22
  readonly origin: string;
20
23
  /** The page's media context: its asset index is reused when given. */
21
24
  readonly media?: MediaContext | undefined;
22
25
  }
23
- type StructuredDataSource = Pick<GraphSource, "site"> & Partial<Pick<GraphSource, "entryById" | "assets">>;
26
+ type StructuredDataSource = Pick<GraphSource, "site"> & Partial<Pick<GraphSource, "entryById" | "assets" | "groupMembers">>;
24
27
  /**
25
28
  * The preset document of an entry and why it has none (`issues`): no preset, a required value
26
29
  * missing, or over the cap. What `withStructuredData` emits, and what previews and checks show.
@@ -32,4 +35,3 @@ export declare function entryStructuredData(source: StructuredDataSource, entry:
32
35
  * The `BreadcrumbList` stays; the `BlogPosting`'s `commentCount` does not move to the preset.
33
36
  */
34
37
  export declare function withStructuredData(head: HeadMeta, source: StructuredDataSource, entry: ContentEntry, options: StructuredDataOptions): Promise<HeadMeta>;
35
- export {};
@@ -7,7 +7,9 @@
7
7
  * The document is built by core-ts's pure `structuredDataFor` from typed values (resolved, so a
8
8
  * translation reads its original's non-localized ones), capped at 32 KB, and rendered through
9
9
  * `jsonLdText` by `SeoHead.astro` like every other JSON-LD block. An entry missing a required value
10
- * keeps its `BlogPosting`; the `BreadcrumbList` always stays.
10
+ * keeps its `BlogPosting`; the `BreadcrumbList` always stays. RFC-0045 step 8b: reference sources
11
+ * read the member the source's `groupMembers` shows (`structured-data-references.ts`); a source
12
+ * without `groupMembers` gives them nothing.
11
13
  */
12
14
 
13
15
  import { entryPath } from "@cloudhal/core-ts";
@@ -20,6 +22,9 @@ import {
20
22
  import { loadAssetIndex, socialImageUrl } from "./media.js";
21
23
 
22
24
 
25
+ import { referencedValues } from "./structured-data-references.js";
26
+
27
+ export { previewGroupMembers } from "./structured-data-references.js";
23
28
 
24
29
 
25
30
 
@@ -29,7 +34,7 @@ import { loadAssetIndex, socialImageUrl } from "./media.js";
29
34
 
30
35
 
31
36
 
32
-
37
+
33
38
 
34
39
  /** The asset index to resolve image fields, the cover image and the site logo with. */
35
40
  async function assetsFor(
@@ -56,8 +61,11 @@ export async function entryStructuredData(
56
61
  const resolved = resolveFields(site, entry, original);
57
62
  const assets = await assetsFor(source, options.media);
58
63
  const { origin } = options;
64
+ // RFC-0045 step 8b: the members reference sources read, as this view shows them.
65
+ const references = await referencedValues({ source, site, entry, resolved, origin });
59
66
  return structuredDataFor(site, resolved, entry, {
60
67
  origin,
68
+ ...(references ? { references } : {}),
61
69
  entryUrl: `${origin}${entryPath(site, entry)}`,
62
70
  imageUrl: (image) => {
63
71
  const asset = image.assetId ? assets.get(image.assetId) : undefined;
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { escapeHtml } from "../../markdown.js";
7
7
  import { imageAttributes, imgHtml, } from "../../media.js";
8
+ import { previewOptions } from "../../preview-media.js";
8
9
  import { attr, CHILDREN, iconOf, SPACE, str } from "../markup.js";
9
10
 
10
11
 
@@ -31,7 +32,7 @@ function thumbHtml(slide , i , media
31
32
  transform: media?.transform ?? "none",
32
33
  ...(media?.budget ? { budget: media.budget } : {}),
33
34
  sizes: "5rem",
34
- ...(media?.preview ? { preview: true } : {}),
35
+ ...previewOptions(media),
35
36
  },
36
37
  ),
37
38
  ).replace(/ alt="[^"]*"/, ' alt=""');
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { escapeHtml, renderMarkdown, safeHref } from "../../markdown.js";
6
6
  import { IMAGE_FITS, imageAttributes, imgHtml } from "../../media.js";
7
+ import { previewOptions } from "../../preview-media.js";
7
8
  import {
8
9
  ALIGN,
9
10
  attr,
@@ -61,7 +62,7 @@ export const imageHtml = (node, { media }) => {
61
62
  transform: media?.transform ?? "none",
62
63
  ...(media?.budget ? { budget: media.budget } : {}),
63
64
  sizes: "(min-width: 64rem) 64rem, 100vw",
64
- ...(media?.preview ? { preview: true } : {}),
65
+ ...previewOptions(media),
65
66
  ...(node.priority ? { priority: true } : {}),
66
67
  ...(fit ? { fit } : {}),
67
68
  },
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { escapeHtml } from "../../markdown.js";
6
6
  import { imageAttributes, imgHtml, } from "../../media.js";
7
+ import { previewOptions } from "../../preview-media.js";
7
8
  import { attr, CHILDREN, closeButton, iconOf, str } from "../markup.js";
8
9
 
9
10
  /**
@@ -19,7 +20,7 @@ function lightboxHtml(id , p , media
19
20
  defaultLocale,
20
21
  transform: media?.transform ?? "none",
21
22
  ...(media?.budget ? { budget: media.budget } : {}),
22
- ...(media?.preview ? { preview: true } : {}),
23
+ ...previewOptions(media),
23
24
  } ;
24
25
  const items = (Array.isArray(p.items) ? p.items : []).slice(0, 24).flatMap((raw) => {
25
26
  const it = (raw ?? {}) ;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudhal/astro-renderer",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Render a Cloudhal Site Graph with Astro: data sources (live/snapshot), section components and the cloudhal() integration",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://cloudhal.dev",
@@ -223,14 +223,14 @@
223
223
  "README.md"
224
224
  ],
225
225
  "dependencies": {
226
- "@cloudhal/core-contracts": "0.11.0",
227
- "@cloudhal/core-ts": "0.11.0",
228
- "@cloudhal/storage": "0.11.0",
226
+ "@cloudhal/core-contracts": "0.12.0",
227
+ "@cloudhal/core-ts": "0.12.0",
228
+ "@cloudhal/storage": "0.12.0",
229
229
  "marked": "^18.1.1",
230
230
  "parse5": "8.1.0",
231
- "@cloudhal/analytics": "0.11.0",
232
- "vite": "^8.3.8",
233
- "@cloudhal/comments": "0.11.0"
231
+ "@cloudhal/analytics": "0.12.0",
232
+ "vite": "^8.4.0",
233
+ "@cloudhal/comments": "0.12.0"
234
234
  },
235
235
  "peerDependencies": {
236
236
  "astro": "^7.4.0",
@@ -239,13 +239,13 @@
239
239
  "devDependencies": {
240
240
  "@astrojs/cloudflare": "14.4.9",
241
241
  "@cloudflare/workers-types": "^5.20261007.1",
242
- "@types/node": "^26.6.5",
243
- "astro": "^7.4.7",
242
+ "@types/node": "^26.6.11",
243
+ "astro": "^7.4.13",
244
244
  "better-sqlite3": "13.2.0",
245
245
  "happy-dom": "^21.0.4",
246
246
  "typescript": "7.0.2",
247
247
  "vitest": "5.1.2",
248
- "wrangler": "4.168.0"
248
+ "wrangler": "4.169.0"
249
249
  },
250
250
  "peerDependenciesMeta": {
251
251
  "@astrojs/cloudflare": {