@eldrajs/theme-core 0.3.6 → 0.4.1

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/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import { decodeStega, encodeStega, stripStega } from "./stega.js";
2
2
  import { a as blockApiIdOf, c as registeredBlockApiId, i as THEME_ID_PATTERN, l as themeSchemaApiId, n as createTemplateLayoutRenderModel, o as getRegisteredThemeId, r as RESERVED_THEME_IDS, s as registerThemeId, t as buildTemplateBlockRenames } from "./templateLayout-CGMAmJBe.js";
3
+ import { ReusableComponentSnapshotCache, asPublicRead, createReusableLayoutRenderModel, expandReusableLayout } from "./reusable.js";
4
+ import { r as createProjectionResolver } from "./reusableExpansion-Cg9AE8JX.js";
3
5
  import { a as parseDynamicRoutePattern, i as matchDynamicRoutePattern, n as buildDynamicRoutePath, o as resolveRoute, r as catalogRouteTarget, s as resolvePagePath, t as MAX_DYNAMIC_ROUTE_PATTERN_BYTES } from "./dynamicRoute-k60idORj.js";
4
- import { a as RICH_TEXT_PAD_ATTR, c as domRangeToPositions, d as restampRichTextPositions, f as richTextMarkNameOf, h as layoutIdentityOf, i as RICH_TEXT_MARK_ELEMENTS, l as resolveDomPoint, m as richTextText, n as createOverlayRuntime, o as computeRichTextPositions, p as richTextNodeSize, r as RICH_TEXT_LEAF_TYPES, s as describeSelectionContext, t as classifyBeforeInput, u as resolveDomPosition } from "./overlay-a8pghnYy.js";
6
+ import { a as RICH_TEXT_PAD_ATTR, c as domRangeToPositions, d as restampRichTextPositions, f as richTextMarkNameOf, h as layoutIdentityOf, i as RICH_TEXT_MARK_ELEMENTS, l as resolveDomPoint, m as richTextText, n as createOverlayRuntime, o as computeRichTextPositions, p as richTextNodeSize, r as RICH_TEXT_LEAF_TYPES, s as describeSelectionContext, t as classifyBeforeInput, u as resolveDomPosition } from "./overlay-C6lCvEGm.js";
5
7
  import { PREVIEW_ROUTER_MESSAGE_TYPES, createPreviewMessageRouter } from "./preview-router.js";
6
8
  import { DEFAULT_LAYOUT_BREAKPOINTS, EDIT_MODE_HIDDEN_OPACITY, LAYOUT_BREAKPOINTS, LayoutValidationError, activeLayoutBreakpoint, createLayoutRenderModel, generateLayoutCss, hiddenLayoutBreakpoints, layoutNodeClass, layoutRenderNodeId, normalizeLayoutDocument, resolveLayoutBreakpoints, resolveLayoutDocument, validateLayoutDocument } from "./layout.js";
7
- import { ReusableComponentSnapshotCache, createReusableLayoutRenderModel } from "./reusable.js";
8
- import { r as createProjectionResolver } from "./reusableExpansion-Cg9AE8JX.js";
9
9
  import { DesignTokenValidationError, applyDesignTokenOverrides, designTokenRevisionHash, generateDesignTokenCss, generateTailwindThemeCss, normalizeColorSelection, normalizeSiteDesignTokenOverrides, normalizeThemeDesignTokens, resolveColorSelection, resolveDesignTokenCatalog, responsiveValue } from "./design-tokens.js";
10
10
  import { DEFAULT_IMAGE_FRAMING, IMAGE_FRAMING_MAX_ZOOM, IMAGE_FRAMING_MIN_ZOOM, clampFocal, clampImageFraming, focalBand, framingDrag, framingZoom, imageFramingAttrs, imageFramingStyle, normalizeImageFraming, parseImageFramingValueAttr, unscaledFrameRect } from "./image-framing.js";
11
11
  // src/blockFields.ts
@@ -29,7 +29,8 @@ function registerBlockFields(fields, themeId) {
29
29
  registerThemeId(themeId);
30
30
  }
31
31
  /**
32
- * Whether the manifest marks this block field `localized`. A rich-text
32
+ * Whether the manifest marks this block field `localized`: a top-level field id, or a data path
33
+ * into a `list`'s item (`items.0.answer`, see `resolveBlockField`). A rich-text
33
34
  * renderer uses it to default an omitted `locale` to the preview's active
34
35
  * content locale — a localized field's draft is keyed per locale, so the
35
36
  * marking attributes (and therefore every §18 v3 rich-text report) must carry
@@ -42,10 +43,10 @@ function registerBlockFields(fields, themeId) {
42
43
  */
43
44
  function isBlockFieldLocalized(apiId, fieldId) {
44
45
  if (apiId === void 0) return false;
45
- return registeredBlockFields[registeredBlockApiId(apiId)]?.find((field) => field.fieldId === fieldId)?.localized === true;
46
+ return resolveBlockField(registeredBlockFields[registeredBlockApiId(apiId)], fieldId.split("."))?.localized === true;
46
47
  }
47
48
  /**
48
- * Resolves the manifest `type` of a block field from its dot-separated data
49
+ * Resolves the manifest definition of a block field from its dot-separated data
49
50
  * path, descending into `list` (via `metadata.item`, projected verbatim by
50
51
  * `blockFieldsModuleSource`) and `composite` (via `metadata.fields`) field
51
52
  * definitions as the path requires. A path segment that is purely digits
@@ -61,31 +62,31 @@ function isBlockFieldLocalized(apiId, fieldId) {
61
62
  * type other than `list`/`composite`, resolves to `undefined` — never a
62
63
  * guess.
63
64
  */
64
- function resolveBlockFieldType(fields, segments) {
65
+ function resolveBlockField(fields, segments) {
65
66
  const [head, ...rest] = segments;
66
67
  if (head === void 0) return void 0;
67
68
  const field = fields?.find((f) => f.fieldId === head);
68
69
  if (field === void 0) return void 0;
69
- if (rest.length === 0) return field.type;
70
+ if (rest.length === 0) return field;
70
71
  if (field.type === "list") {
71
72
  const item = field.metadata?.item;
72
73
  if (item === null || typeof item !== "object" || Array.isArray(item)) return void 0;
73
74
  const itemDef = item;
74
75
  const afterIndex = /^\d+$/.test(rest[0] ?? "") ? rest.slice(1) : rest;
75
- if (afterIndex.length === 0) return typeof itemDef.type === "string" ? itemDef.type : void 0;
76
+ if (afterIndex.length === 0) return typeof itemDef.type === "string" ? itemDef : void 0;
76
77
  if (itemDef.type !== "composite") return void 0;
77
- return resolveBlockFieldType(Array.isArray(itemDef.metadata?.fields) ? itemDef.metadata.fields : void 0, afterIndex);
78
+ return resolveBlockField(Array.isArray(itemDef.metadata?.fields) ? itemDef.metadata.fields : void 0, afterIndex);
78
79
  }
79
80
  if (field.type === "composite") {
80
81
  const metaFields = field.metadata?.fields;
81
- return resolveBlockFieldType(Array.isArray(metaFields) ? metaFields : void 0, rest);
82
+ return resolveBlockField(Array.isArray(metaFields) ? metaFields : void 0, rest);
82
83
  }
83
- if (rest.every((segment) => /^\d+$/.test(segment))) return field.type;
84
+ if (rest.every((segment) => /^\d+$/.test(segment))) return field;
84
85
  }
85
86
  /**
86
87
  * Whether the manifest marks the block field at `path` (a top-level field
87
88
  * id, or a dot-separated data path reaching into a `list`'s composite item —
88
- * see `resolveBlockFieldType`) `type: "select"`. `encodeEntryDataStega` and
89
+ * see `resolveBlockField`) `type: "select"`. `encodeEntryDataStega` and
89
90
  * the public/preview read path's `{value,label}` unwrap both use this to
90
91
  * recognize a select field's resolved value (a plain string like
91
92
  * `"primary"`/`"subtle"`, or `{value,label}` before unwrapping): a
@@ -101,7 +102,7 @@ function resolveBlockFieldType(fields, segments) {
101
102
  */
102
103
  function isBlockFieldSelect(apiId, path) {
103
104
  if (apiId === void 0) return false;
104
- return resolveBlockFieldType(registeredBlockFields[registeredBlockApiId(apiId)], path.split(".")) === "select";
105
+ return resolveBlockField(registeredBlockFields[registeredBlockApiId(apiId)], path.split("."))?.type === "select";
105
106
  }
106
107
  /** Ceiling on the *computed* backoff. A `Retry-After` is honoured beyond it. */
107
108
  const DEFAULT_RETRY_MAX_DELAY_MS = 5e3;
@@ -484,11 +485,22 @@ function looksLikeRichTextNode(value) {
484
485
  var EldraClientError = class extends Error {
485
486
  status;
486
487
  path;
487
- constructor(status, statusText, path) {
488
+ /**
489
+ * The refusal's `errorId`, when the answer named one. Read only from a draft preview session's
490
+ * reads (`enableSessionPreview`), where the preview router answers `application/problem+json` and
491
+ * the id says which notice to show (`SITE_PREVIEW_SESSION_EXPIRED`, `_REVOKED`, …). `null`
492
+ * everywhere else: an ordinary read's failure body is never read.
493
+ */
494
+ errorId;
495
+ /** Whether the failed request was a draft preview session read through the same-origin proxy. */
496
+ sessionPreview;
497
+ constructor(status, statusText, path, details) {
488
498
  super(`[eldra] gateway request failed: ${status} ${statusText} for ${path}`);
489
499
  this.name = "EldraClientError";
490
500
  this.status = status;
491
501
  this.path = path;
502
+ this.errorId = details?.errorId ?? null;
503
+ this.sessionPreview = details?.sessionPreview === true;
492
504
  }
493
505
  };
494
506
  // src/client.ts
@@ -511,9 +523,11 @@ function createEldraClient(opts) {
511
523
  const stegaEnabled = opts.stega === true;
512
524
  const defaultLocale = opts.defaultLocale ?? null;
513
525
  let previewToken = null;
526
+ /** The draft preview session's proxy (`enableSessionPreview`), or `null` outside one. */
527
+ let sessionProxyBase = null;
514
528
  const requestErrorListeners = /* @__PURE__ */ new Set();
515
- function buildUrl(path, query, extra) {
516
- const url = new URL(gatewayUrl + path);
529
+ function buildUrl(path, query, extra, base = gatewayUrl) {
530
+ const url = new URL(base + path);
517
531
  if (query?.locale !== void 0) url.searchParams.set("locale", query.locale);
518
532
  if (query?.depth !== void 0) url.searchParams.set("depth", String(query.depth));
519
533
  if (query?.page !== void 0) url.searchParams.set("page", String(query.page));
@@ -527,7 +541,7 @@ function createEldraClient(opts) {
527
541
  async function request(url, init) {
528
542
  const headers = new Headers(init?.headers);
529
543
  headers.set("X-Org-Id", opts.orgId);
530
- if (previewToken !== null) headers.set("X-Preview-Token", previewToken);
544
+ if (previewToken !== null && sessionProxyBase === null) headers.set("X-Preview-Token", previewToken);
531
545
  if (opts.buildToken) headers.set("X-Eldra-Build-Token", opts.buildToken);
532
546
  const merged = {
533
547
  ...init,
@@ -543,6 +557,75 @@ function createEldraClient(opts) {
543
557
  }
544
558
  return res;
545
559
  }
560
+ /**
561
+ * One CMS read: through the session's same-origin proxy when a draft preview session is on,
562
+ * otherwise exactly the read it has always been.
563
+ */
564
+ async function cmsRequest(path, query, init) {
565
+ if (sessionProxyBase === null) return request(buildUrl(path, query), init);
566
+ return sessionRequest(buildUrl(path, query, void 0, sessionProxyBase), init);
567
+ }
568
+ /**
569
+ * A draft read through the preview router's proxy. A fresh header set — the caller's own
570
+ * (`content-type` on the one POST) and `accept`, never `X-Org-Id`, `X-Preview-Token` or the build
571
+ * token: the router adds the organisation and the session itself, from the HttpOnly cookie
572
+ * `credentials: 'same-origin'` sends. `no-store`, because a draft must never be cached.
573
+ */
574
+ async function sessionRequest(url, init) {
575
+ const headers = new Headers(init?.headers);
576
+ headers.set("accept", "application/json");
577
+ const merged = {
578
+ ...init,
579
+ headers,
580
+ cache: "no-store",
581
+ credentials: "same-origin"
582
+ };
583
+ const res = await fetchWithRetry(doFetch, url.toString(), merged, retryPolicy);
584
+ if (!res.ok) {
585
+ const error = new EldraClientError(res.status, res.statusText, url.pathname, {
586
+ errorId: await readErrorId(res),
587
+ sessionPreview: true
588
+ });
589
+ notifyRequestError(error);
590
+ throw error;
591
+ }
592
+ if (res.headers.get("eldra-preview") !== "draft") {
593
+ res.body?.cancel().catch(() => void 0);
594
+ const error = new EldraClientError(502, "Bad Gateway", url.pathname, {
595
+ errorId: "PREVIEW_UPSTREAM_NOT_PREVIEW",
596
+ sessionPreview: true
597
+ });
598
+ notifyRequestError(error);
599
+ throw error;
600
+ }
601
+ const text = await res.text();
602
+ let body;
603
+ try {
604
+ body = JSON.stringify(asPublicRead(JSON.parse(text)));
605
+ } catch {
606
+ body = text;
607
+ }
608
+ return new Response(body, {
609
+ status: res.status,
610
+ statusText: res.statusText,
611
+ headers: res.headers
612
+ });
613
+ }
614
+ /** `getSiteSetting`: see its doc comment in `./clientTypes.ts`. */
615
+ async function siteSetting(path) {
616
+ if (sessionProxyBase === null) return (await request(buildUrl(path))).json();
617
+ const url = buildUrl(path, void 0, void 0, sessionProxyBase);
618
+ const res = await fetchWithRetry(doFetch, url.toString(), {
619
+ headers: { accept: "application/json" },
620
+ cache: "no-store",
621
+ credentials: "same-origin"
622
+ }, retryPolicy);
623
+ if (!res.ok) throw new EldraClientError(res.status, res.statusText, url.pathname, {
624
+ errorId: await readErrorId(res),
625
+ sessionPreview: true
626
+ });
627
+ return res.json();
628
+ }
546
629
  function notifyRequestError(error) {
547
630
  for (const listener of [...requestErrorListeners]) try {
548
631
  listener(error);
@@ -579,7 +662,7 @@ function createEldraClient(opts) {
579
662
  }
580
663
  },
581
664
  async getEntries(schemaIdentifier, query) {
582
- const list = await (await request(buildUrl(`/cms/v1/schema/${encodeURIComponent(schemaIdentifier)}/entry`, query))).json();
665
+ const list = await (await cmsRequest(`/cms/v1/schema/${encodeURIComponent(schemaIdentifier)}/entry`, query)).json();
583
666
  if (list.data !== void 0 && list.data !== null && !Array.isArray(list.data)) throw new TypeError("[eldra] gateway entry list data must be an array");
584
667
  return {
585
668
  ...list,
@@ -587,16 +670,16 @@ function createEldraClient(opts) {
587
670
  };
588
671
  },
589
672
  async getEntry(schemaIdentifier, entryId, query) {
590
- return maybeStega(await (await request(buildUrl(`/cms/v1/schema/${encodeURIComponent(schemaIdentifier)}/entry/${encodeURIComponent(entryId)}`, query))).json(), query?.locale ?? null);
673
+ return maybeStega(await (await cmsRequest(`/cms/v1/schema/${encodeURIComponent(schemaIdentifier)}/entry/${encodeURIComponent(entryId)}`, query)).json(), query?.locale ?? null);
591
674
  },
592
675
  async getEntryByUniqueField(schemaIdentifier, fieldId, value, query) {
593
- return maybeStega(await (await request(buildUrl(`/cms/v1/schema/${encodeURIComponent(schemaIdentifier)}/entry/unique/${encodeURIComponent(fieldId)}/${encodeURIComponent(value)}`, query))).json(), query?.locale ?? null);
676
+ return maybeStega(await (await cmsRequest(`/cms/v1/schema/${encodeURIComponent(schemaIdentifier)}/entry/unique/${encodeURIComponent(fieldId)}/${encodeURIComponent(value)}`, query)).json(), query?.locale ?? null);
594
677
  },
595
678
  async resolveEntryListField(entryId, fieldId, query) {
596
- return await (await request(buildUrl(`/cms/v1/entry/${encodeURIComponent(entryId)}/list/${encodeURIComponent(fieldId)}`, query))).json();
679
+ return await (await cmsRequest(`/cms/v1/entry/${encodeURIComponent(entryId)}/list/${encodeURIComponent(fieldId)}`, query)).json();
597
680
  },
598
681
  async resolveEntryList(body, query) {
599
- return await (await request(buildUrl("/cms/v1/entry-list/resolve", query), {
682
+ return await (await cmsRequest("/cms/v1/entry-list/resolve", query, {
600
683
  method: "POST",
601
684
  headers: { "content-type": "application/json" },
602
685
  body: JSON.stringify(body)
@@ -619,6 +702,13 @@ function createEldraClient(opts) {
619
702
  get previewEnabled() {
620
703
  return previewToken !== null;
621
704
  },
705
+ enableSessionPreview(options) {
706
+ sessionProxyBase = sameOriginProxyBase(options);
707
+ },
708
+ get sessionPreviewEnabled() {
709
+ return sessionProxyBase !== null;
710
+ },
711
+ getSiteSetting: siteSetting,
622
712
  onRequestError(listener) {
623
713
  requestErrorListeners.add(listener);
624
714
  return () => {
@@ -629,6 +719,33 @@ function createEldraClient(opts) {
629
719
  };
630
720
  }
631
721
  /**
722
+ * The session proxy's base, checked: absolute, on the page's own origin (when there is a page), with
723
+ * no query or fragment, trailing slashes stripped. The reads it serves carry the session cookie, so
724
+ * a base anywhere else is a mistake that must fail loudly rather than send them there.
725
+ */
726
+ function sameOriginProxyBase(options) {
727
+ let url;
728
+ try {
729
+ url = new URL(options.proxyBase);
730
+ } catch {
731
+ throw new TypeError("[eldra] enableSessionPreview: proxyBase must be an absolute URL");
732
+ }
733
+ const pageOrigin = globalThis.location?.origin;
734
+ if (typeof pageOrigin === "string" && pageOrigin !== "null" && url.origin !== pageOrigin) throw new TypeError("[eldra] enableSessionPreview: proxyBase must be on the page's own origin");
735
+ if (url.search !== "" || url.hash !== "") throw new TypeError("[eldra] enableSessionPreview: proxyBase takes no query or fragment");
736
+ return stripTrailingSlashes(`${url.origin}${url.pathname}`);
737
+ }
738
+ /** A refusal's `errorId` from its `application/problem+json` body, or `null`. Never throws. */
739
+ async function readErrorId(res) {
740
+ try {
741
+ const body = await res.json();
742
+ const errorId = typeof body === "object" && body !== null ? body.errorId : null;
743
+ return typeof errorId === "string" && errorId !== "" ? errorId : null;
744
+ } catch {
745
+ return null;
746
+ }
747
+ }
748
+ /**
632
749
  * Normalise a catalog list response. The gateway serialises an empty page as
633
750
  * `"data": null`, and a caller that pages through the list must not have to
634
751
  * guess whether a missing `meta` means "one page" or "keep asking" — an absent
@@ -1046,7 +1163,10 @@ function buildNode(node, options, cursor, pos) {
1046
1163
  }] : kids;
1047
1164
  const textblockElement = (tag, attrs = {}) => [{
1048
1165
  tag,
1049
- attrs: stamp(attrs),
1166
+ attrs: stamp(holdsUnresolvedPrice(node.content, options) ? {
1167
+ ...attrs,
1168
+ hidden: ""
1169
+ } : attrs),
1050
1170
  children: padIfEmpty(children())
1051
1171
  }];
1052
1172
  switch (node.type) {
@@ -1079,12 +1199,25 @@ function buildNode(node, options, cursor, pos) {
1079
1199
  case "tableRow": return element("tr");
1080
1200
  case "tableHeader": return element("th", tableCellAttrs(node));
1081
1201
  case "tableCell": return element("td", tableCellAttrs(node));
1202
+ case "price": {
1203
+ const written = options.resolvePrice?.(node.attrs) ?? null;
1204
+ return [{
1205
+ tag: "span",
1206
+ attrs: stamp({}),
1207
+ children: written === null ? [] : [written]
1208
+ }];
1209
+ }
1082
1210
  case "image": return buildImage(node, options, stamp);
1083
1211
  case "embed": return buildEmbed(node, options, stamp);
1084
1212
  case "doc": return element("span");
1085
1213
  default: return element("span");
1086
1214
  }
1087
1215
  }
1216
+ /** Whether a textblock holds a `price` node its theme cannot write: the block is then hidden. */
1217
+ function holdsUnresolvedPrice(content, options) {
1218
+ if (!Array.isArray(content)) return false;
1219
+ return content.some((child) => isNode(child) && child.type === "price" && (options.resolvePrice?.(child.attrs) ?? null) === null);
1220
+ }
1088
1221
  function buildCodeBlock(node, attrs, children) {
1089
1222
  const language = typeof node.attrs?.language === "string" ? node.attrs.language : null;
1090
1223
  return [{
@@ -1866,4 +1999,4 @@ function countryFromHeader(value) {
1866
1999
  const code = (value ?? "").trim().toUpperCase();
1867
2000
  return /^[A-Z]{2}$/.test(code) && code !== "XX" ? code : null;
1868
2001
  }
1869
- export { ANALYTICS_MAX_KEY_BYTES, ANALYTICS_MAX_NAME_BYTES, ANALYTICS_MAX_PROPS, ANALYTICS_MAX_VALUE_BYTES, ANALYTICS_QUEUE_LIMIT, DEFAULT_HOME_TITLE_PATTERN, DEFAULT_IMAGE_FRAMING, DEFAULT_LAYOUT_BREAKPOINTS, DEFAULT_TITLE_PATTERN, DesignTokenValidationError, EDIT_MODE_HIDDEN_OPACITY, EldraClientError, IMAGE_FRAMING_MAX_ZOOM, IMAGE_FRAMING_MIN_ZOOM, LAYOUT_BREAKPOINTS, LD_DESCRIPTION_MAX, LayoutValidationError, MAX_DYNAMIC_ROUTE_PATTERN_BYTES, PREVIEW_ROUTER_MESSAGE_TYPES, RESERVED_THEME_IDS, RICH_TEXT_LEAF_TYPES, RICH_TEXT_MARK_ELEMENTS, RICH_TEXT_PAD_ATTR, RICH_TEXT_TOOLBAR_CONTROLS, ReusableComponentSnapshotCache, SELLING_CURRENCIES, SEO_SYNTAX, SITEMAP_MAX_BYTES, SITEMAP_MAX_URLS, STRUCTURED_DATA_TYPES, THEME_ID_PATTERN, VISITOR_COUNTRY_PATH, activeLayoutBreakpoint, applyDesignTokenOverrides, applyStructuredDataPolicy, blockApiIdOf, buildAlternates, buildBreadcrumbLd, buildDynamicRoutePath, buildItemListLd, buildOrganizationLd, buildProductLd, buildRichTextTree, buildRobots, buildSitemap, buildTemplateBlockRenames, buildWebSiteLd, catalogRouteTarget, clampFocal, clampImageFraming, classifyBeforeInput, computeRichTextPositions, countryFromHeader, createAnalytics, createEldraClient, createLayoutRenderModel, createOverlayRuntime, createPreviewMessageRouter, createProjectionResolver, createReusableLayoutRenderModel, createTemplateLayoutRenderModel, currencyForCountry, decodeStega, defaultCurrencyOf, describeSelectionContext, designTokenRevisionHash, domRangeToPositions, encodeEntryDataStega, encodeStega, escapeXml, focalBand, framingDrag, framingZoom, generateDesignTokenCss, generateLayoutCss, generateTailwindThemeCss, getRegisteredThemeId, hiddenLayoutBreakpoints, imageFramingAttrs, imageFramingStyle, isBlockFieldLocalized, layoutIdentityOf, layoutNodeClass, layoutRenderNodeId, ldPlainText, ldPrice, matchDynamicRoutePattern, normalizeAnalyticsProps, normalizeColorSelection, normalizeImageFraming, normalizeLayoutDocument, normalizeSiteDesignTokenOverrides, normalizeThemeDesignTokens, offeredCurrencies, parseDynamicRoutePattern, parseImageFramingValueAttr, pickSeoLocale, projectEntryDataLocale, registerBlockFields, registerThemeId, renderSeoTitle, resolveColorSelection, resolveDesignTokenCatalog, resolveDomPoint, resolveDomPosition, resolveLayoutBreakpoints, resolveLayoutDocument, resolvePagePath, resolveRoute, resolveSeo, resolveVisitorCurrency, responsiveValue, restampRichTextPositions, richTextMarkNameOf, richTextNodeSize, richTextText, safeHref, serializeLd, siteOrigin, sitemapLastmod, stripStega, substituteSeoPattern, themeSchemaApiId, tidySeoTitle, truncateUtf8, unscaledFrameRect, validGtin, validateLayoutDocument };
2002
+ export { ANALYTICS_MAX_KEY_BYTES, ANALYTICS_MAX_NAME_BYTES, ANALYTICS_MAX_PROPS, ANALYTICS_MAX_VALUE_BYTES, ANALYTICS_QUEUE_LIMIT, DEFAULT_HOME_TITLE_PATTERN, DEFAULT_IMAGE_FRAMING, DEFAULT_LAYOUT_BREAKPOINTS, DEFAULT_TITLE_PATTERN, DesignTokenValidationError, EDIT_MODE_HIDDEN_OPACITY, EldraClientError, IMAGE_FRAMING_MAX_ZOOM, IMAGE_FRAMING_MIN_ZOOM, LAYOUT_BREAKPOINTS, LD_DESCRIPTION_MAX, LayoutValidationError, MAX_DYNAMIC_ROUTE_PATTERN_BYTES, PREVIEW_ROUTER_MESSAGE_TYPES, RESERVED_THEME_IDS, RICH_TEXT_LEAF_TYPES, RICH_TEXT_MARK_ELEMENTS, RICH_TEXT_PAD_ATTR, RICH_TEXT_TOOLBAR_CONTROLS, ReusableComponentSnapshotCache, SELLING_CURRENCIES, SEO_SYNTAX, SITEMAP_MAX_BYTES, SITEMAP_MAX_URLS, STRUCTURED_DATA_TYPES, THEME_ID_PATTERN, VISITOR_COUNTRY_PATH, activeLayoutBreakpoint, applyDesignTokenOverrides, applyStructuredDataPolicy, asPublicRead, blockApiIdOf, buildAlternates, buildBreadcrumbLd, buildDynamicRoutePath, buildItemListLd, buildOrganizationLd, buildProductLd, buildRichTextTree, buildRobots, buildSitemap, buildTemplateBlockRenames, buildWebSiteLd, catalogRouteTarget, clampFocal, clampImageFraming, classifyBeforeInput, computeRichTextPositions, countryFromHeader, createAnalytics, createEldraClient, createLayoutRenderModel, createOverlayRuntime, createPreviewMessageRouter, createProjectionResolver, createReusableLayoutRenderModel, createTemplateLayoutRenderModel, currencyForCountry, decodeStega, defaultCurrencyOf, describeSelectionContext, designTokenRevisionHash, domRangeToPositions, encodeEntryDataStega, encodeStega, escapeXml, expandReusableLayout, focalBand, framingDrag, framingZoom, generateDesignTokenCss, generateLayoutCss, generateTailwindThemeCss, getRegisteredThemeId, hiddenLayoutBreakpoints, imageFramingAttrs, imageFramingStyle, isBlockFieldLocalized, layoutIdentityOf, layoutNodeClass, layoutRenderNodeId, ldPlainText, ldPrice, matchDynamicRoutePattern, normalizeAnalyticsProps, normalizeColorSelection, normalizeImageFraming, normalizeLayoutDocument, normalizeSiteDesignTokenOverrides, normalizeThemeDesignTokens, offeredCurrencies, parseDynamicRoutePattern, parseImageFramingValueAttr, pickSeoLocale, projectEntryDataLocale, registerBlockFields, registerThemeId, renderSeoTitle, resolveColorSelection, resolveDesignTokenCatalog, resolveDomPoint, resolveDomPosition, resolveLayoutBreakpoints, resolveLayoutDocument, resolvePagePath, resolveRoute, resolveSeo, resolveVisitorCurrency, responsiveValue, restampRichTextPositions, richTextMarkNameOf, richTextNodeSize, richTextText, safeHref, serializeLd, siteOrigin, sitemapLastmod, stripStega, substituteSeoPattern, themeSchemaApiId, tidySeoTitle, truncateUtf8, unscaledFrameRect, validGtin, validateLayoutDocument };
package/dist/links.d.ts CHANGED
@@ -21,8 +21,25 @@ export interface LinkValue {
21
21
  openInNewTab?: boolean;
22
22
  /** A column heading; meaningful on a child of a mega-menu item. */
23
23
  group?: string;
24
- /** One level deep, never two. */
24
+ /** One level deep, never two. Served to a theme that declares no `sections`. */
25
25
  children?: LinkValue[];
26
+ /** The second level in columns, served to a theme that declares `sections`; never together with `children`. */
27
+ sections?: LinkSectionValue[];
28
+ /** A promotional card or a plain link; a link's own value overrides its section's. */
29
+ display?: 'card' | 'link';
30
+ /** The media URL of a card's own image. */
31
+ imageUrl?: string;
32
+ }
33
+ /** One column of a link's `sections`, as a public read serves it. */
34
+ export interface LinkSectionValue {
35
+ heading?: string;
36
+ headingLink?: LinkValue;
37
+ display?: 'card' | 'link';
38
+ links?: LinkValue[];
39
+ seeAll?: {
40
+ label?: string;
41
+ link?: LinkValue;
42
+ };
26
43
  }
27
44
  /** What a site knows about one link target, keyed by `${_type}:${id}`. The
28
45
  * slug builds the path, the title fills in a label the author left empty,
@@ -43,6 +60,10 @@ export interface LinkTargetInfo {
43
60
  * path, which on a canonical-only route is a 404 dressed as a link.
44
61
  */
45
62
  path?: string;
63
+ /** The target's own picture URL: a product's `thumbnail`, a collection's `image`. A card's fallback when its own image is absent. */
64
+ image?: string;
65
+ /** A product's lowest price as the catalog read serves it (major units, no currency: the store's own). Shown on a product card. */
66
+ price?: number;
46
67
  }
47
68
  export interface LinkRouteContext {
48
69
  pages: readonly PageLike[];
@@ -59,6 +80,32 @@ export interface ResolvedLink {
59
80
  newTab: boolean;
60
81
  group: string | null;
61
82
  children: ResolvedLink[];
83
+ /** Present only on a link the read served sections for; `children` is empty then. */
84
+ sections?: ResolvedSection[];
85
+ /** How the link is presented: its own `display`, else its section's. `link` when a card could not be resolved. */
86
+ display?: 'card' | 'link';
87
+ /** The link's own card image, as served. */
88
+ imageUrl?: string;
89
+ /** Present only when `display` is `card` and the card has a picture and a title; without it the link is a plain link. */
90
+ card?: ResolvedCard;
91
+ }
92
+ /** A resolved card: the picture (the override, else the target's own), the title and, for a product, its price. */
93
+ export interface ResolvedCard {
94
+ image: string;
95
+ title: string;
96
+ /** A product's lowest price in **major units** (the /web product list's `minPrice`, `28` for 28 kr.), with no currency: format it with the store's. */
97
+ price?: number;
98
+ }
99
+ /** One resolved column of a link's `sections`. */
100
+ export interface ResolvedSection {
101
+ /** Unstripped, like every label, so a preview can edit it inline. Falls back to the heading link's label; null when both are blank. */
102
+ heading: string | null;
103
+ /** The heading as a link, when the author made it one. */
104
+ headingLink: ResolvedLink | null;
105
+ display?: 'card' | 'link';
106
+ links: ResolvedLink[];
107
+ /** The trailing "see all" link: its own label when set, else its target's. Null when it has neither. */
108
+ seeAll: ResolvedLink | null;
62
109
  }
63
110
  /**
64
111
  * An href a theme may render, or null.
@@ -106,6 +153,8 @@ export declare function linkTargetKeys(value: unknown): string[];
106
153
  * simply is not a link until the page is published.
107
154
  *
108
155
  * Children resolve one level; a child's own `children` are ignored, matching
109
- * the depth the grammar allows.
156
+ * the depth the grammar allows. `sections` (a theme that declares them is served
157
+ * those instead of `children`) resolve the same way: each section's links, its
158
+ * heading link and its see-all link are links of that one level.
110
159
  */
111
160
  export declare function resolveLink(value: unknown, context: LinkRouteContext): ResolvedLink | null;
package/dist/links.js CHANGED
@@ -91,8 +91,16 @@ function collectTargetKeys(value, keys, seen, depth) {
91
91
  seen.add(key);
92
92
  keys.push(key);
93
93
  }
94
- if (depth > 0 || !Array.isArray(link.children)) return;
95
- for (const child of link.children) collectTargetKeys(child, keys, seen, depth + 1);
94
+ if (depth > 0) return;
95
+ if (Array.isArray(link.children)) for (const child of link.children) collectTargetKeys(child, keys, seen, depth + 1);
96
+ if (!Array.isArray(link.sections)) return;
97
+ for (const section of link.sections) {
98
+ const record = asRecord(section);
99
+ if (record === null) continue;
100
+ collectTargetKeys(record.headingLink, keys, seen, depth + 1);
101
+ if (Array.isArray(record.links)) for (const child of record.links) collectTargetKeys(child, keys, seen, depth + 1);
102
+ collectTargetKeys(asRecord(record.seeAll)?.link, keys, seen, depth + 1);
103
+ }
96
104
  }
97
105
  function targetKey(target) {
98
106
  if (typeof target !== "object" || target === null || Array.isArray(target)) return null;
@@ -114,25 +122,88 @@ function targetKey(target) {
114
122
  * simply is not a link until the page is published.
115
123
  *
116
124
  * Children resolve one level; a child's own `children` are ignored, matching
117
- * the depth the grammar allows.
125
+ * the depth the grammar allows. `sections` (a theme that declares them is served
126
+ * those instead of `children`) resolve the same way: each section's links, its
127
+ * heading link and its see-all link are links of that one level.
118
128
  */
119
129
  function resolveLink(value, context) {
120
130
  return resolveOne(value, context, 0);
121
131
  }
122
- function resolveOne(value, context, depth) {
132
+ function resolveOne(value, context, depth, card) {
123
133
  const link = asLinkValue(value);
124
134
  if (link === null) return null;
125
135
  const info = targetInfo(link.target, context);
126
136
  const ownLabel = typeof link.label === "string" ? link.label : "";
127
137
  const targetTitle = typeof info?.title === "string" ? info.title : "";
128
138
  const group = typeof link.group === "string" ? link.group : "";
129
- return {
139
+ const resolved = {
130
140
  href: resolveHref(plain(link.kind), link, info, context),
131
141
  label: plain(ownLabel) !== "" ? ownLabel : plain(targetTitle) !== "" ? targetTitle : null,
132
142
  newTab: link.openInNewTab === true,
133
143
  group: plain(group) === "" ? null : group,
134
- children: depth > 0 || !Array.isArray(link.children) ? [] : link.children.map((child) => resolveOne(child, context, depth + 1)).filter((child) => child !== null)
144
+ children: depth > 0 || !Array.isArray(link.children) ? [] : link.children.map((child) => resolveOne(child, context, depth + 1, {})).filter((child) => child !== null)
145
+ };
146
+ if (depth === 0 && Array.isArray(link.sections)) resolved.sections = link.sections.map((section) => resolveSection(section, context)).filter((section) => section !== null);
147
+ if (typeof link.imageUrl === "string" && plain(link.imageUrl) !== "") resolved.imageUrl = link.imageUrl;
148
+ if (card !== void 0) {
149
+ const display = cardDisplay(link.display) ?? card.display;
150
+ if (display !== void 0) resolved.display = display;
151
+ }
152
+ if (card !== void 0 && resolved.display === "card") {
153
+ const resolvedCard = resolveCard(plain(link.kind), link, info, resolved.label);
154
+ if (resolvedCard === null) resolved.display = "link";
155
+ else resolved.card = resolvedCard;
156
+ }
157
+ return resolved;
158
+ }
159
+ /** A card needs a picture and a title, else it is a plain link. A product or collection card falls back to the target's own picture. */
160
+ function resolveCard(kind, link, info, title) {
161
+ const own = typeof link.imageUrl === "string" && plain(link.imageUrl) !== "" ? link.imageUrl : "";
162
+ const targetImage = (kind === "product" || kind === "collection") && typeof info?.image === "string" ? info.image : "";
163
+ const image = own !== "" ? own : targetImage;
164
+ if (plain(image) === "" || title === null) return null;
165
+ const card = {
166
+ image,
167
+ title
135
168
  };
169
+ if (kind === "product" && typeof info?.price === "number" && Number.isFinite(info.price)) card.price = info.price;
170
+ return card;
171
+ }
172
+ function resolveSection(value, context) {
173
+ const section = asRecord(value);
174
+ if (section === null) return null;
175
+ const heading = typeof section.heading === "string" ? section.heading : "";
176
+ const headingLink = resolveOne(section.headingLink, context, 1);
177
+ const sectionDisplay = cardDisplay(section.display);
178
+ const resolved = {
179
+ heading: plain(heading) !== "" ? heading : headingLink?.label ?? null,
180
+ headingLink,
181
+ links: (Array.isArray(section.links) ? section.links : []).map((link) => resolveOne(link, context, 1, { display: sectionDisplay })).filter((link) => link !== null),
182
+ seeAll: resolveSeeAll(section.seeAll, context)
183
+ };
184
+ if (sectionDisplay !== void 0) resolved.display = sectionDisplay;
185
+ return resolved;
186
+ }
187
+ function resolveSeeAll(value, context) {
188
+ const seeAll = asRecord(value);
189
+ if (seeAll === null) return null;
190
+ const link = resolveOne(seeAll.link, context, 1);
191
+ const label = typeof seeAll.label === "string" ? seeAll.label : "";
192
+ if (plain(label) !== "") return link === null ? {
193
+ href: null,
194
+ label,
195
+ newTab: false,
196
+ group: null,
197
+ children: []
198
+ } : {
199
+ ...link,
200
+ label
201
+ };
202
+ return link !== null && link.label !== null ? link : null;
203
+ }
204
+ function cardDisplay(value) {
205
+ const display = plain(value);
206
+ return display === "card" || display === "link" ? display : void 0;
136
207
  }
137
208
  function resolveHref(kind, link, info, context) {
138
209
  if (kind === "none") return null;
@@ -172,6 +243,9 @@ function targetInfo(target, context) {
172
243
  const key = targetKey(target);
173
244
  return key === null ? void 0 : context.targets.get(key);
174
245
  }
246
+ function asRecord(value) {
247
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
248
+ }
175
249
  function asLinkValue(value) {
176
250
  if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
177
251
  const record = value;