@eldrajs/theme-core 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import { decodeStega, encodeStega, stripStega } from "./stega.js";
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-CpZb6EEg.js";
2
3
  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-CxXY-Y_8.js";
3
4
  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";
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-BvkEOiMB.js";
5
+ 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-C8-F1jzU.js";
5
6
  import { DEFAULT_LAYOUT_BREAKPOINTS, EDIT_MODE_HIDDEN_OPACITY, LAYOUT_BREAKPOINTS, LayoutValidationError, activeLayoutBreakpoint, createLayoutRenderModel, generateLayoutCss, hiddenLayoutBreakpoints, layoutNodeClass, layoutRenderNodeId, normalizeLayoutDocument, resolveLayoutBreakpoints, resolveLayoutDocument, validateLayoutDocument } from "./layout.js";
6
7
  import { PREVIEW_ROUTER_MESSAGE_TYPES, createPreviewMessageRouter } from "./preview-router.js";
7
8
  import { r as createProjectionResolver } from "./reusableExpansion-Bqm83nCJ.js";
8
- import { buildTemplateBlockRenames, createTemplateLayoutRenderModel } from "./template-layout.js";
9
9
  import { ReusableComponentSnapshotCache, createReusableLayoutRenderModel } from "./reusable.js";
10
10
  import { DesignTokenValidationError, applyDesignTokenOverrides, designTokenRevisionHash, generateDesignTokenCss, generateTailwindThemeCss, normalizeColorSelection, normalizeSiteDesignTokenOverrides, normalizeThemeDesignTokens, resolveColorSelection, resolveDesignTokenCatalog, responsiveValue } from "./design-tokens.js";
11
11
  //#region src/blockFields.ts
@@ -19,9 +19,14 @@ let registeredBlockFields = {};
19
19
  * equivalent entry for another adapter) imports `virtual:eldra/block-fields`
20
20
  * and calls this once at startup with the resolved map; call it again (e.g.
21
21
  * on the plugin's HMR rescan) to replace the registered map.
22
+ *
23
+ * `themeId` is the theme's own id (the manifest's `theme.id`). Core spells a
24
+ * block entry's schema `<themeId>:<apiId>` on the wire while this map is keyed
25
+ * by the bare `apiId`, so the lookups below strip that one prefix.
22
26
  */
23
- function registerBlockFields(fields) {
27
+ function registerBlockFields(fields, themeId) {
24
28
  registeredBlockFields = fields;
29
+ registerThemeId(themeId);
25
30
  }
26
31
  /**
27
32
  * Whether the manifest marks this block field `localized`. A rich-text
@@ -37,7 +42,7 @@ function registerBlockFields(fields) {
37
42
  */
38
43
  function isBlockFieldLocalized(apiId, fieldId) {
39
44
  if (apiId === void 0) return false;
40
- return registeredBlockFields[apiId]?.find((field) => field.fieldId === fieldId)?.localized === true;
45
+ return registeredBlockFields[registeredBlockApiId(apiId)]?.find((field) => field.fieldId === fieldId)?.localized === true;
41
46
  }
42
47
  /**
43
48
  * Resolves the manifest `type` of a block field from its dot-separated data
@@ -96,7 +101,7 @@ function resolveBlockFieldType(fields, segments) {
96
101
  */
97
102
  function isBlockFieldSelect(apiId, path) {
98
103
  if (apiId === void 0) return false;
99
- return resolveBlockFieldType(registeredBlockFields[apiId], path.split(".")) === "select";
104
+ return resolveBlockFieldType(registeredBlockFields[registeredBlockApiId(apiId)], path.split(".")) === "select";
100
105
  }
101
106
  /** Ceiling on the *computed* backoff. A `Retry-After` is honoured beyond it. */
102
107
  const DEFAULT_RETRY_MAX_DELAY_MS = 5e3;
@@ -805,6 +810,80 @@ function projectLocalizedLeaves(data, locale, defaultLocale, apiId) {
805
810
  return projectLocalizedValue(data, locale, defaultLocale, apiId, "");
806
811
  }
807
812
  //#endregion
813
+ //#region src/analytics.ts
814
+ /** Core's ingest limits (`SanitizeProps`): 30 entries, keys up to 60 bytes, values 300 bytes. */
815
+ const ANALYTICS_MAX_PROPS = 30;
816
+ const ANALYTICS_MAX_KEY_BYTES = 60;
817
+ const ANALYTICS_MAX_VALUE_BYTES = 300;
818
+ /** Core cuts an event name at 120 bytes. */
819
+ const ANALYTICS_MAX_NAME_BYTES = 120;
820
+ /** Events held back before the tracker script has loaded; the oldest are dropped past this. */
821
+ const ANALYTICS_QUEUE_LIMIT = 50;
822
+ /** Cuts a string to at most `maxBytes` of UTF-8 without splitting a character. */
823
+ function truncateUtf8(value, maxBytes) {
824
+ const encoder = new TextEncoder();
825
+ if (encoder.encode(value).length <= maxBytes) return value;
826
+ let out = "";
827
+ let size = 0;
828
+ for (const char of value) {
829
+ const next = encoder.encode(char).length;
830
+ if (size + next > maxBytes) break;
831
+ out += char;
832
+ size += next;
833
+ }
834
+ return out;
835
+ }
836
+ /**
837
+ * Coerces a theme's props to what Core stores: strings only, `null`/`undefined`/non-finite numbers
838
+ * dropped, keys and values cut to the ingest limits, at most 30 entries.
839
+ */
840
+ function normalizeAnalyticsProps(props) {
841
+ const out = {};
842
+ if (props === void 0) return out;
843
+ for (const [rawKey, raw] of Object.entries(props)) {
844
+ if (Object.keys(out).length >= 30) break;
845
+ if (raw === null || raw === void 0) continue;
846
+ if (typeof raw === "number" && !Number.isFinite(raw)) continue;
847
+ const key = truncateUtf8(rawKey, 60);
848
+ if (key === "") continue;
849
+ out[key] = truncateUtf8(String(raw), 300);
850
+ }
851
+ return out;
852
+ }
853
+ function createAnalytics(options) {
854
+ const queue = [];
855
+ function send(sender, name, props) {
856
+ try {
857
+ sender("event", name, { props });
858
+ } catch {}
859
+ }
860
+ return {
861
+ enabled: options.enabled,
862
+ track(rawName, props) {
863
+ if (!options.enabled) return;
864
+ const name = truncateUtf8(rawName.trim(), 120);
865
+ if (name === "" || name === "pageview") return;
866
+ const normalized = normalizeAnalyticsProps(props);
867
+ const sender = options.sender();
868
+ if (sender === void 0) {
869
+ queue.push({
870
+ name,
871
+ props: normalized
872
+ });
873
+ if (queue.length > 50) queue.shift();
874
+ return;
875
+ }
876
+ send(sender, name, normalized);
877
+ },
878
+ flush() {
879
+ if (!options.enabled) return;
880
+ const sender = options.sender();
881
+ if (sender === void 0) return;
882
+ for (const event of queue.splice(0)) send(sender, event.name, event.props);
883
+ }
884
+ };
885
+ }
886
+ //#endregion
808
887
  //#region src/richText.ts
809
888
  /**
810
889
  * Ordered ids of every rich-text toolbar control a `block.json` may request
@@ -1133,4 +1212,553 @@ function buildFileAttachmentMark(mark, options, child) {
1133
1212
  };
1134
1213
  }
1135
1214
  //#endregion
1136
- export { DEFAULT_IMAGE_FRAMING, DEFAULT_LAYOUT_BREAKPOINTS, DesignTokenValidationError, EDIT_MODE_HIDDEN_OPACITY, EldraClientError, IMAGE_FRAMING_MAX_ZOOM, IMAGE_FRAMING_MIN_ZOOM, LAYOUT_BREAKPOINTS, LayoutValidationError, MAX_DYNAMIC_ROUTE_PATTERN_BYTES, PREVIEW_ROUTER_MESSAGE_TYPES, RICH_TEXT_LEAF_TYPES, RICH_TEXT_MARK_ELEMENTS, RICH_TEXT_PAD_ATTR, RICH_TEXT_TOOLBAR_CONTROLS, ReusableComponentSnapshotCache, activeLayoutBreakpoint, applyDesignTokenOverrides, buildDynamicRoutePath, buildRichTextTree, buildTemplateBlockRenames, catalogRouteTarget, clampFocal, clampImageFraming, classifyBeforeInput, computeRichTextPositions, createEldraClient, createLayoutRenderModel, createOverlayRuntime, createPreviewMessageRouter, createProjectionResolver, createReusableLayoutRenderModel, createTemplateLayoutRenderModel, decodeStega, describeSelectionContext, designTokenRevisionHash, domRangeToPositions, encodeEntryDataStega, encodeStega, focalBand, framingDrag, framingZoom, generateDesignTokenCss, generateLayoutCss, generateTailwindThemeCss, hiddenLayoutBreakpoints, imageFramingAttrs, imageFramingStyle, isBlockFieldLocalized, layoutIdentityOf, layoutNodeClass, layoutRenderNodeId, matchDynamicRoutePattern, normalizeColorSelection, normalizeImageFraming, normalizeLayoutDocument, normalizeSiteDesignTokenOverrides, normalizeThemeDesignTokens, parseDynamicRoutePattern, parseImageFramingValueAttr, projectEntryDataLocale, registerBlockFields, resolveColorSelection, resolveDesignTokenCatalog, resolveDomPoint, resolveDomPosition, resolveLayoutBreakpoints, resolveLayoutDocument, resolvePagePath, resolveRoute, responsiveValue, restampRichTextPositions, richTextMarkNameOf, richTextNodeSize, richTextText, safeHref, stripStega, unscaledFrameRect, validateLayoutDocument };
1215
+ //#region src/seo.ts
1216
+ /** The only pattern syntax version this resolver understands. */
1217
+ const SEO_SYNTAX = 1;
1218
+ const PLACEHOLDER = /\{\{([^{}]+)\}\}/g;
1219
+ const SEPARATORS = /* @__PURE__ */ new Set([
1220
+ "·",
1221
+ "|",
1222
+ "–",
1223
+ "—",
1224
+ "-"
1225
+ ]);
1226
+ /** The title pattern used when neither the context nor the site sets one. */
1227
+ const DEFAULT_TITLE_PATTERN = "{{page.title}} · {{site.name}}";
1228
+ /** The home page's default: the site's name alone. */
1229
+ const DEFAULT_HOME_TITLE_PATTERN = "{{site.name}}";
1230
+ /** Looks `path` up in `data`: first as a flat key, then walking nested objects. */
1231
+ function lookup(data, path) {
1232
+ let value = Object.prototype.hasOwnProperty.call(data, path) ? data[path] : void 0;
1233
+ if (value === void 0) {
1234
+ value = data;
1235
+ for (const part of path.split(".")) {
1236
+ if (typeof value !== "object" || value === null || !Object.hasOwn(value, part)) return "";
1237
+ value = value[part];
1238
+ }
1239
+ }
1240
+ if (typeof value === "string") return value;
1241
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
1242
+ return "";
1243
+ }
1244
+ /** One pass of `{{path}}` substitution; unknown and empty values become `''`. No tidying. */
1245
+ function substituteSeoPattern(pattern, data) {
1246
+ return pattern.replace(PLACEHOLDER, (_match, path) => lookup(data, path.trim()));
1247
+ }
1248
+ /** Collapses whitespace and drops leading, trailing and doubled separators. */
1249
+ function tidySeoTitle(value) {
1250
+ const tokens = value.split(/\s+/).filter((token) => token !== "");
1251
+ const kept = [];
1252
+ for (const token of tokens) {
1253
+ if (SEPARATORS.has(token) && (kept.length === 0 || SEPARATORS.has(kept[kept.length - 1]))) continue;
1254
+ kept.push(token);
1255
+ }
1256
+ while (kept.length > 0 && SEPARATORS.has(kept[kept.length - 1])) kept.pop();
1257
+ return kept.join(" ");
1258
+ }
1259
+ /** Substitutes, then tidies: the title rule the shared vectors pin down. */
1260
+ function renderSeoTitle(pattern, data) {
1261
+ return tidySeoTitle(substituteSeoPattern(pattern, data));
1262
+ }
1263
+ function renderSeoText(pattern, data) {
1264
+ return substituteSeoPattern(pattern, data).replace(/\s+/g, " ").trim();
1265
+ }
1266
+ /**
1267
+ * One locale's string out of a string or a locale map: the exact tag, the same language, the
1268
+ * default locale, then `''`.
1269
+ */
1270
+ function pickSeoLocale(value, locale, defaultLocale) {
1271
+ if (typeof value === "string") return value;
1272
+ if (typeof value !== "object" || value === null) return "";
1273
+ const own = (key) => {
1274
+ if (key === null || key === void 0 || !Object.hasOwn(value, key)) return "";
1275
+ const text = value[key];
1276
+ return typeof text === "string" ? text : "";
1277
+ };
1278
+ const language = locale?.split("-")[0]?.toLowerCase();
1279
+ const sameLanguage = language === void 0 ? "" : own(Object.keys(value).find((key) => key.split("-")[0]?.toLowerCase() === language));
1280
+ return [
1281
+ own(locale),
1282
+ sameLanguage,
1283
+ own(defaultLocale)
1284
+ ].find((text) => text.trim() !== "") ?? "";
1285
+ }
1286
+ function absolute(url, siteUrl) {
1287
+ const value = url?.trim();
1288
+ if (value === void 0 || value === "") return null;
1289
+ try {
1290
+ const resolved = siteUrl === null ? new URL(value) : new URL(value, siteUrl);
1291
+ return resolved.protocol === "https:" || resolved.protocol === "http:" ? resolved.href : null;
1292
+ } catch {
1293
+ return null;
1294
+ }
1295
+ }
1296
+ function originOf(siteUrl) {
1297
+ const value = siteUrl?.trim();
1298
+ if (value === void 0 || value === "") return null;
1299
+ try {
1300
+ const url = new URL(value);
1301
+ return url.protocol === "https:" || url.protocol === "http:" ? url.origin : null;
1302
+ } catch {
1303
+ return null;
1304
+ }
1305
+ }
1306
+ /** Resolves every SEO value one route needs. Pure; never throws on malformed content. */
1307
+ function resolveSeo(input) {
1308
+ const { locale, context, site } = input;
1309
+ const pick = (value) => pickSeoLocale(value, locale, input.defaultLocale);
1310
+ const origin = originOf(input.siteUrl);
1311
+ const siteName = site?.site.name?.trim() || input.siteName?.trim() || "";
1312
+ const data = {
1313
+ ...input.data,
1314
+ "site.name": siteName,
1315
+ "site.url": origin ?? "",
1316
+ "site.locale": locale ?? ""
1317
+ };
1318
+ const entry = input.entry ?? null;
1319
+ const template = input.template ?? null;
1320
+ const patterns = site?.templates[context];
1321
+ const titleOverride = pick(entry?.title) || pick(template?.title);
1322
+ let title = "";
1323
+ if (titleOverride.trim() !== "") title = renderSeoTitle(titleOverride, data);
1324
+ if (title === "") title = renderSeoTitle(pick(patterns?.titlePattern) || pick(site?.site.titlePattern) || (context === "home" ? "{{site.name}}" : "{{page.title}} · {{site.name}}"), data);
1325
+ if (title === "") title = renderSeoTitle("{{page.title}}", data) || siteName;
1326
+ const description = renderSeoText(pick(entry?.description) || pick(template?.description) || pick(patterns?.descriptionPattern) || pick(site?.site.description), data);
1327
+ const ogTitle = renderSeoText(pick(entry?.ogTitle) || pick(template?.ogTitle), data) || title;
1328
+ const ogDescription = renderSeoText(pick(entry?.ogDescription) || pick(template?.ogDescription), data) || description;
1329
+ const image = absolute(entry?.imageUrl, origin) ?? absolute(template?.imageUrl, origin) ?? absolute(input.contentImage, origin) ?? absolute(site?.site.imageUrl, origin);
1330
+ let canonical = null;
1331
+ const canonicalPattern = pick(entry?.canonicalUrl) || pick(template?.canonicalUrl);
1332
+ let useOwnPath = canonicalPattern.trim() === "";
1333
+ if (!useOwnPath) {
1334
+ const rendered = renderSeoText(canonicalPattern, data);
1335
+ if (/[{}]/.test(rendered)) useOwnPath = true;
1336
+ else canonical = absolute(rendered, origin);
1337
+ }
1338
+ if (useOwnPath && origin !== null && input.path !== void 0 && input.path !== null) try {
1339
+ const url = new URL(input.path, origin);
1340
+ canonical = `${url.origin}${url.pathname}`;
1341
+ } catch {
1342
+ canonical = null;
1343
+ }
1344
+ const handle = site?.site.twitterHandle?.trim().replace(/^@+/, "") ?? "";
1345
+ return {
1346
+ title,
1347
+ description,
1348
+ ogTitle,
1349
+ ogDescription,
1350
+ image,
1351
+ canonical,
1352
+ noindex: input.isPreview === true || entry?.noindex === true || template?.noindex === true,
1353
+ ogType: context === "catalog:product" ? "product" : "website",
1354
+ twitterSite: handle === "" ? null : `@${handle}`
1355
+ };
1356
+ }
1357
+ //#endregion
1358
+ //#region src/sitemap.ts
1359
+ const SITEMAP_MAX_URLS = 5e4;
1360
+ const SITEMAP_MAX_BYTES = 52428800;
1361
+ const URLSET_OPEN = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\n";
1362
+ const URLSET_CLOSE = "</urlset>\n";
1363
+ const byteLength = (text) => new TextEncoder().encode(text).length;
1364
+ /** The absolute origin of `siteUrl` (`https://shop.example`, no trailing slash), or `null`. */
1365
+ function siteOrigin(siteUrl) {
1366
+ const value = siteUrl?.trim();
1367
+ if (value === void 0 || value === "") return null;
1368
+ try {
1369
+ const url = new URL(value);
1370
+ return url.protocol === "https:" || url.protocol === "http:" ? url.origin : null;
1371
+ } catch {
1372
+ return null;
1373
+ }
1374
+ }
1375
+ function escapeXml(value) {
1376
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1377
+ }
1378
+ /** A W3C datetime (`2026-01-02T03:04:05.000Z`), or `null` for anything that is not a date. */
1379
+ function sitemapLastmod(value) {
1380
+ if (value === null || value === void 0 || value === "") return null;
1381
+ const date = value instanceof Date ? value : new Date(value);
1382
+ return Number.isNaN(date.getTime()) ? null : date.toISOString();
1383
+ }
1384
+ /**
1385
+ * The URL a variant is listed under: its own canonical when that is on this site's origin, else
1386
+ * the path-derived URL. A canonical on another host is not a page of this site and must not put
1387
+ * a foreign URL in this site's sitemap.
1388
+ */
1389
+ function locOf(variant, origin) {
1390
+ const canonical = variant.canonical?.trim();
1391
+ if (canonical !== void 0 && canonical !== "") try {
1392
+ const url = new URL(canonical, origin);
1393
+ if (url.origin === origin) return `${url.origin}${url.pathname}${url.search}`;
1394
+ } catch {}
1395
+ try {
1396
+ const url = new URL(variant.path, origin);
1397
+ return `${url.origin}${url.pathname}${url.search}`;
1398
+ } catch {
1399
+ return null;
1400
+ }
1401
+ }
1402
+ /** The `<url>` blocks of every indexable page, one per variant, in input order, deduplicated by `loc`. */
1403
+ function urlBlocks(pages, origin) {
1404
+ const seen = /* @__PURE__ */ new Set();
1405
+ const blocks = [];
1406
+ for (const page of pages) {
1407
+ if (page.noindex === true) continue;
1408
+ const located = page.variants.map((variant) => ({
1409
+ variant,
1410
+ loc: locOf(variant, origin)
1411
+ })).filter((entry) => entry.loc !== null);
1412
+ const lastmod = sitemapLastmod(page.lastmod);
1413
+ const alternates = [];
1414
+ if (located.length > 1) {
1415
+ for (const { variant, loc } of located) {
1416
+ if (variant.locale === null) continue;
1417
+ alternates.push(linkTag(variant.locale, loc));
1418
+ }
1419
+ const fallback = located.find((entry) => entry.variant.isDefault === true);
1420
+ if (fallback !== void 0) alternates.push(linkTag("x-default", fallback.loc));
1421
+ }
1422
+ for (const { loc } of located) {
1423
+ if (seen.has(loc)) continue;
1424
+ seen.add(loc);
1425
+ blocks.push(` <url>\n <loc>${escapeXml(loc)}</loc>\n` + (lastmod === null ? "" : ` <lastmod>${lastmod}</lastmod>\n`) + alternates.map((tag) => ` ${tag}\n`).join("") + " </url>\n");
1426
+ }
1427
+ }
1428
+ return blocks;
1429
+ }
1430
+ function linkTag(hreflang, href) {
1431
+ return `<xhtml:link rel="alternate" hreflang="${escapeXml(hreflang)}" href="${escapeXml(href)}"/>`;
1432
+ }
1433
+ /**
1434
+ * The sitemap files for `pages`: one `sitemap.xml` (a `urlset`), or, when the URLs do not fit the
1435
+ * limits, a `sitemap.xml` that is a `sitemapindex` over `sitemap-1.xml`, `sitemap-2.xml`, ...
1436
+ *
1437
+ * Empty when `siteUrl` is not an absolute http(s) URL (a sitemap of relative URLs is invalid) and
1438
+ * when no page is indexable.
1439
+ */
1440
+ function buildSitemap(input) {
1441
+ const origin = siteOrigin(input.siteUrl);
1442
+ if (origin === null) return [];
1443
+ const blocks = urlBlocks(input.pages, origin);
1444
+ if (blocks.length === 0) return [];
1445
+ const maxUrls = Math.max(1, input.limits?.maxUrls ?? 5e4);
1446
+ const maxBytes = input.limits?.maxBytes ?? 52428800;
1447
+ const envelope = byteLength(URLSET_OPEN) + byteLength(URLSET_CLOSE);
1448
+ const chunks = [];
1449
+ let current = [];
1450
+ let size = envelope;
1451
+ for (const block of blocks) {
1452
+ const blockSize = byteLength(block);
1453
+ if (current.length > 0 && (current.length >= maxUrls || size + blockSize > maxBytes)) {
1454
+ chunks.push(current);
1455
+ current = [];
1456
+ size = envelope;
1457
+ }
1458
+ current.push(block);
1459
+ size += blockSize;
1460
+ }
1461
+ chunks.push(current);
1462
+ const urlset = (chunk) => `${URLSET_OPEN}${chunk.join("")}${URLSET_CLOSE}`;
1463
+ if (chunks.length === 1) return [{
1464
+ name: "sitemap.xml",
1465
+ xml: urlset(chunks[0])
1466
+ }];
1467
+ const files = chunks.map((chunk, index) => ({
1468
+ name: `sitemap-${index + 1}.xml`,
1469
+ xml: urlset(chunk)
1470
+ }));
1471
+ return [{
1472
+ name: "sitemap.xml",
1473
+ xml: "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n" + files.map((file) => ` <sitemap>\n <loc>${escapeXml(`${origin}/${file.name}`)}</loc>\n </sitemap>\n`).join("") + "</sitemapindex>\n"
1474
+ }, ...files];
1475
+ }
1476
+ /**
1477
+ * The `robots.txt` body.
1478
+ *
1479
+ * A **preview** build disallows everything and names no sitemap. A production build allows
1480
+ * everything, adds the merchant's own lines (`extra`), and names the sitemap when there is one.
1481
+ * `extra` is untrusted text: control characters are dropped, every line is trimmed, and a line
1482
+ * that opens a second `User-agent` group is kept as the merchant wrote it (that is the point of
1483
+ * the field), after the platform's group.
1484
+ */
1485
+ function buildRobots(input) {
1486
+ if (input.target !== "production") return "User-agent: *\nDisallow: /\n";
1487
+ const lines = ["User-agent: *", "Allow: /"];
1488
+ const extra = (input.extra ?? "").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "").split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== "");
1489
+ lines.push(...extra);
1490
+ const origin = siteOrigin(input.siteUrl);
1491
+ if (input.sitemap === true && origin !== null) lines.push("", `Sitemap: ${origin}/sitemap.xml`);
1492
+ return `${lines.join("\n")}\n`;
1493
+ }
1494
+ /**
1495
+ * The `<link rel="alternate" hreflang>` set for one page, for the head: one per locale plus
1496
+ * `x-default`. `pathFor(locale)` spells the page under that locale (`undefined`: the one
1497
+ * served at `/`, for `x-default`). Absolute when `siteUrl` is known, otherwise the paths as given. Empty for fewer
1498
+ * than two locales: a single-locale site has no alternates.
1499
+ */
1500
+ function buildAlternates(input) {
1501
+ if (input.locales.length < 2) return [];
1502
+ const origin = siteOrigin(input.siteUrl);
1503
+ const href = (path) => origin === null ? path : `${origin}${path}`;
1504
+ return [...input.locales.map((locale) => ({
1505
+ rel: "alternate",
1506
+ hreflang: locale,
1507
+ href: href(input.pathFor(locale))
1508
+ })), {
1509
+ rel: "alternate",
1510
+ hreflang: "x-default",
1511
+ href: href(input.pathFor(void 0))
1512
+ }];
1513
+ }
1514
+ //#endregion
1515
+ //#region src/structuredData.ts
1516
+ const STRUCTURED_DATA_TYPES = [
1517
+ "product",
1518
+ "breadcrumb",
1519
+ "itemList",
1520
+ "organization",
1521
+ "website"
1522
+ ];
1523
+ const SCHEMA = "https://schema.org";
1524
+ const AVAILABILITY_URL = {
1525
+ InStock: `${SCHEMA}/InStock`,
1526
+ OutOfStock: `${SCHEMA}/OutOfStock`,
1527
+ PreOrder: `${SCHEMA}/PreOrder`,
1528
+ LimitedAvailability: `${SCHEMA}/LimitedAvailability`
1529
+ };
1530
+ /** Which availability wins when one price covers variants that differ: the most buyable one. */
1531
+ const AVAILABILITY_RANK = {
1532
+ InStock: 3,
1533
+ LimitedAvailability: 2,
1534
+ PreOrder: 1,
1535
+ OutOfStock: 0
1536
+ };
1537
+ /** Drops every empty value, recursively. Numbers (including `0`) and booleans are kept. */
1538
+ function clean(value) {
1539
+ if (value === null || value === void 0) return void 0;
1540
+ if (typeof value === "string") return value.trim() === "" ? void 0 : value;
1541
+ if (Array.isArray(value)) {
1542
+ const items = value.map((item) => clean(item)).filter((item) => item !== void 0);
1543
+ return items.length === 0 ? void 0 : items;
1544
+ }
1545
+ if (typeof value === "object") {
1546
+ const entries = Object.entries(value).map(([key, item]) => [key, clean(item)]).filter(([, item]) => item !== void 0);
1547
+ return entries.length === 0 ? void 0 : Object.fromEntries(entries);
1548
+ }
1549
+ return value;
1550
+ }
1551
+ function node(type, fields) {
1552
+ return clean({
1553
+ "@context": SCHEMA,
1554
+ "@type": type,
1555
+ ...fields
1556
+ }) ?? {};
1557
+ }
1558
+ /** Fraction digits of a currency; `2` for a code `Intl` does not know. */
1559
+ function fractionDigits(currency) {
1560
+ try {
1561
+ return new Intl.NumberFormat("en", {
1562
+ style: "currency",
1563
+ currency
1564
+ }).resolvedOptions().maximumFractionDigits ?? 2;
1565
+ } catch {
1566
+ return 2;
1567
+ }
1568
+ }
1569
+ /** The amount as the number written in an offer: rounded to the currency's own digits. */
1570
+ function ldPrice(amount, currency) {
1571
+ return Number(amount.toFixed(fractionDigits(currency)));
1572
+ }
1573
+ /**
1574
+ * The GTIN if `value` is a valid GTIN-8/12/13/14 (digits only, GS1 check digit correct), else
1575
+ * `null`. A barcode field is free text, so anything else (an internal code, a mistyped digit) is
1576
+ * left out rather than sent to a crawler as an identifier.
1577
+ */
1578
+ function validGtin(value) {
1579
+ const digits = (value ?? "").replace(/[\s-]/g, "");
1580
+ if (!/^\d+$/.test(digits) || ![
1581
+ 8,
1582
+ 12,
1583
+ 13,
1584
+ 14
1585
+ ].includes(digits.length)) return null;
1586
+ let sum = 0;
1587
+ for (let i = digits.length - 2, weight = 3; i >= 0; i--, weight = weight === 3 ? 1 : 3) sum += Number(digits[i]) * weight;
1588
+ return (10 - sum % 10) % 10 === Number(digits[digits.length - 1]) ? digits : null;
1589
+ }
1590
+ function offerOf(variant, currency, extra = {}) {
1591
+ const price = ldPrice(variant.price, currency);
1592
+ const listPrice = variant.compareAt === null || variant.compareAt === void 0 ? void 0 : ldPrice(variant.compareAt, currency);
1593
+ return {
1594
+ "@type": "Offer",
1595
+ url: variant.url,
1596
+ price,
1597
+ priceCurrency: currency,
1598
+ availability: AVAILABILITY_URL[variant.availability],
1599
+ priceValidUntil: variant.priceValidUntil,
1600
+ ...listPrice !== void 0 && listPrice > price ? { priceSpecification: {
1601
+ "@type": "UnitPriceSpecification",
1602
+ priceType: `${SCHEMA}/ListPrice`,
1603
+ price: listPrice,
1604
+ priceCurrency: currency
1605
+ } } : {},
1606
+ ...extra
1607
+ };
1608
+ }
1609
+ /**
1610
+ * A `Product`. One variant, or several at one price, is an `Offer`; variants at different prices
1611
+ * are an `AggregateOffer` (`lowPrice`, `highPrice`, `offerCount`, one `Offer` each). With no
1612
+ * currency or no variants the node carries no offers at all.
1613
+ */
1614
+ function buildProductLd(input) {
1615
+ const currency = (input.currency ?? "").trim();
1616
+ const variants = input.variants.filter((variant) => Number.isFinite(variant.price));
1617
+ const single = variants.length === 1 ? variants[0] : void 0;
1618
+ const identity = (variant) => ({
1619
+ sku: variant.sku,
1620
+ gtin: validGtin(variant.gtin)
1621
+ });
1622
+ let offers;
1623
+ if (currency !== "" && variants.length > 0) {
1624
+ const prices = variants.map((variant) => ldPrice(variant.price, currency));
1625
+ const low = Math.min(...prices);
1626
+ const high = Math.max(...prices);
1627
+ if (low === high) offers = offerOf(variants.reduce((a, b) => AVAILABILITY_RANK[b.availability] > AVAILABILITY_RANK[a.availability] ? b : a), currency, single === void 0 ? {} : identity(single));
1628
+ else offers = {
1629
+ "@type": "AggregateOffer",
1630
+ lowPrice: low,
1631
+ highPrice: high,
1632
+ priceCurrency: currency,
1633
+ offerCount: variants.length,
1634
+ offers: variants.map((variant) => offerOf(variant, currency, identity(variant)))
1635
+ };
1636
+ }
1637
+ const ratings = input.ratings !== null && input.ratings !== void 0 && input.ratings.count > 0 && Number.isFinite(input.ratings.value) ? {
1638
+ "@type": "AggregateRating",
1639
+ ratingValue: input.ratings.value,
1640
+ reviewCount: input.ratings.count
1641
+ } : void 0;
1642
+ return node("Product", {
1643
+ name: input.name,
1644
+ url: input.url,
1645
+ description: input.description,
1646
+ image: input.images,
1647
+ brand: input.brand ? {
1648
+ "@type": "Brand",
1649
+ name: input.brand
1650
+ } : void 0,
1651
+ ...single === void 0 ? {} : identity(single),
1652
+ offers,
1653
+ aggregateRating: ratings
1654
+ });
1655
+ }
1656
+ /** A `BreadcrumbList`, root first. Every level carries its URL, the last one included. */
1657
+ function buildBreadcrumbLd(items) {
1658
+ return node("BreadcrumbList", { itemListElement: items.filter((item) => item.name.trim() !== "").map((item, index) => ({
1659
+ "@type": "ListItem",
1660
+ position: index + 1,
1661
+ name: item.name,
1662
+ item: item.url
1663
+ })) });
1664
+ }
1665
+ /** An `ItemList` of the things a listing page shows, in the order shown. */
1666
+ function buildItemListLd(items) {
1667
+ return node("ItemList", { itemListElement: items.map((item, index) => ({
1668
+ "@type": "ListItem",
1669
+ position: index + 1,
1670
+ url: item.url,
1671
+ name: item.name
1672
+ })) });
1673
+ }
1674
+ function buildOrganizationLd(input) {
1675
+ const contact = input.contact;
1676
+ return node("Organization", {
1677
+ name: input.name,
1678
+ url: input.url,
1679
+ logo: input.logo,
1680
+ sameAs: input.sameAs,
1681
+ contactPoint: contact && (contact.email || contact.telephone) ? {
1682
+ "@type": "ContactPoint",
1683
+ contactType: "customer service",
1684
+ email: contact.email,
1685
+ telephone: contact.telephone
1686
+ } : void 0
1687
+ });
1688
+ }
1689
+ function buildWebSiteLd(input) {
1690
+ const search = (input.searchPath ?? "").trim();
1691
+ return node("WebSite", {
1692
+ name: input.name,
1693
+ url: input.url,
1694
+ potentialAction: search === "" ? void 0 : {
1695
+ "@type": "SearchAction",
1696
+ target: {
1697
+ "@type": "EntryPoint",
1698
+ urlTemplate: `${trimTrailingSlashes(input.url)}${search.startsWith("/") ? "" : "/"}${search}?q={search_term_string}`
1699
+ },
1700
+ "query-input": "required name=search_term_string"
1701
+ }
1702
+ });
1703
+ }
1704
+ /**
1705
+ * The text of `<script type="application/ld+json">`. One node is written as itself, several as an
1706
+ * array. `<` is written as its JSON escape (so `<\/script>` and `<!--` cannot occur) and U+2028/U+2029 are
1707
+ * escaped; the result is still plain JSON.
1708
+ */
1709
+ function serializeLd(nodes) {
1710
+ return JSON.stringify(nodes.length === 1 ? nodes[0] : nodes).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1711
+ }
1712
+ const LD_DESCRIPTION_MAX = 5e3;
1713
+ /**
1714
+ * A description as plain text for `description`: a string with its HTML tags dropped, or a rich-text
1715
+ * document (nodes with `text`/`content`) flattened, whitespace collapsed, cut at `max` characters
1716
+ * on a word boundary.
1717
+ */
1718
+ function ldPlainText(value, max = LD_DESCRIPTION_MAX) {
1719
+ const plain = (typeof value === "string" ? stripTags(value) : flatten(value)).replace(/\s+/g, " ").trim();
1720
+ if (plain.length <= max) return plain;
1721
+ const cut = plain.slice(0, max);
1722
+ const space = cut.lastIndexOf(" ");
1723
+ return (space > max * .8 ? cut.slice(0, space) : cut).trim();
1724
+ }
1725
+ function trimTrailingSlashes(url) {
1726
+ let end = url.length;
1727
+ while (end > 0 && url[end - 1] === "/") end--;
1728
+ return url.slice(0, end);
1729
+ }
1730
+ /** Drops `<…>` tags in one pass (a linear scan; an unclosed `<` keeps the rest as text). */
1731
+ function stripTags(html) {
1732
+ let out = "";
1733
+ let i = 0;
1734
+ while (i < html.length) {
1735
+ const open = html.indexOf("<", i);
1736
+ if (open === -1) break;
1737
+ const close = html.indexOf(">", open + 1);
1738
+ if (close === -1) break;
1739
+ out += `${html.slice(i, open)} `;
1740
+ i = close + 1;
1741
+ }
1742
+ return out + html.slice(i);
1743
+ }
1744
+ function flatten(value) {
1745
+ if (typeof value !== "object" || value === null) return "";
1746
+ const { type, text, content } = value;
1747
+ if (type === "text") return typeof text === "string" ? text : "";
1748
+ return Array.isArray(content) ? content.map(flatten).join(" ") : "";
1749
+ }
1750
+ /** Applies the theme's opt-out and extender to the nodes a page built. Pure. */
1751
+ function applyStructuredDataPolicy(entries, policy, context) {
1752
+ const disable = policy.disable;
1753
+ if (disable === true) return [];
1754
+ const off = new Set(Array.isArray(disable) ? disable : []);
1755
+ const out = [];
1756
+ for (const entry of entries) {
1757
+ if (off.has(entry.type) || Object.keys(entry.node).length === 0) continue;
1758
+ const next = policy.extend ? policy.extend(entry.type, entry.node, context) : entry.node;
1759
+ if (next !== null && Object.keys(next).length > 0) out.push(next);
1760
+ }
1761
+ return out;
1762
+ }
1763
+ //#endregion
1764
+ 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, SEO_SYNTAX, SITEMAP_MAX_BYTES, SITEMAP_MAX_URLS, STRUCTURED_DATA_TYPES, THEME_ID_PATTERN, activeLayoutBreakpoint, applyDesignTokenOverrides, applyStructuredDataPolicy, blockApiIdOf, buildAlternates, buildBreadcrumbLd, buildDynamicRoutePath, buildItemListLd, buildOrganizationLd, buildProductLd, buildRichTextTree, buildRobots, buildSitemap, buildTemplateBlockRenames, buildWebSiteLd, catalogRouteTarget, clampFocal, clampImageFraming, classifyBeforeInput, computeRichTextPositions, createAnalytics, createEldraClient, createLayoutRenderModel, createOverlayRuntime, createPreviewMessageRouter, createProjectionResolver, createReusableLayoutRenderModel, createTemplateLayoutRenderModel, decodeStega, 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, parseDynamicRoutePattern, parseImageFramingValueAttr, pickSeoLocale, projectEntryDataLocale, registerBlockFields, registerThemeId, renderSeoTitle, resolveColorSelection, resolveDesignTokenCatalog, resolveDomPoint, resolveDomPosition, resolveLayoutBreakpoints, resolveLayoutDocument, resolvePagePath, resolveRoute, resolveSeo, responsiveValue, restampRichTextPositions, richTextMarkNameOf, richTextNodeSize, richTextText, safeHref, serializeLd, siteOrigin, sitemapLastmod, stripStega, substituteSeoPattern, themeSchemaApiId, tidySeoTitle, truncateUtf8, unscaledFrameRect, validGtin, validateLayoutDocument };