@eldrajs/theme-core 0.0.0 → 0.2.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +311 -0
  2. package/LICENSE +21 -0
  3. package/README.md +68 -1
  4. package/dist/bridge-CLi2P6Wh.js +314 -0
  5. package/dist/bridge.d.ts +2 -0
  6. package/dist/bridge.js +2 -0
  7. package/dist/design-tokens.d.ts +68 -0
  8. package/dist/design-tokens.js +486 -0
  9. package/dist/dynamic-route.d.ts +2 -0
  10. package/dist/dynamic-route.js +3 -0
  11. package/dist/dynamicRoute-CxXY-Y_8.js +126 -0
  12. package/dist/dynamicRoute-pRTBoYT6.d.ts +55 -0
  13. package/dist/i18n.d.ts +107 -0
  14. package/dist/i18n.js +192 -0
  15. package/dist/image-framing.d.ts +2 -0
  16. package/dist/image-framing.js +109 -0
  17. package/dist/imageFraming-BUZ-yqho.d.ts +51 -0
  18. package/dist/index-DxrkKyG4.d.ts +488 -0
  19. package/dist/index.d.ts +449 -0
  20. package/dist/index.js +1141 -0
  21. package/dist/layout-CWq_v6ws.d.ts +244 -0
  22. package/dist/layout.d.ts +2 -0
  23. package/dist/layout.js +930 -0
  24. package/dist/links.d.ts +113 -0
  25. package/dist/links.js +184 -0
  26. package/dist/overlay-Bgi0tIbN.d.ts +201 -0
  27. package/dist/overlay-C8-F1jzU.js +2908 -0
  28. package/dist/overlay.d.ts +2 -0
  29. package/dist/overlay.js +6 -0
  30. package/dist/preview-router.d.ts +2 -0
  31. package/dist/preview-router.js +130 -0
  32. package/dist/reusable.d.ts +66 -0
  33. package/dist/reusable.js +92 -0
  34. package/dist/reusableExpansion-Bqm83nCJ.js +229 -0
  35. package/dist/reusableExpansion-CXvs_ckx.d.ts +42 -0
  36. package/dist/stega.d.ts +17 -0
  37. package/dist/stega.js +69 -0
  38. package/dist/template-layout.d.ts +3 -0
  39. package/dist/template-layout.js +3 -0
  40. package/dist/templateLayout-CpZb6EEg.js +382 -0
  41. package/dist/templateLayout-MjNs0gbF.d.ts +254 -0
  42. package/package.json +89 -2
package/dist/index.js ADDED
@@ -0,0 +1,1141 @@
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";
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";
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";
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";
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";
7
+ import { PREVIEW_ROUTER_MESSAGE_TYPES, createPreviewMessageRouter } from "./preview-router.js";
8
+ import { r as createProjectionResolver } from "./reusableExpansion-Bqm83nCJ.js";
9
+ import { ReusableComponentSnapshotCache, createReusableLayoutRenderModel } from "./reusable.js";
10
+ import { DesignTokenValidationError, applyDesignTokenOverrides, designTokenRevisionHash, generateDesignTokenCss, generateTailwindThemeCss, normalizeColorSelection, normalizeSiteDesignTokenOverrides, normalizeThemeDesignTokens, resolveColorSelection, resolveDesignTokenCatalog, responsiveValue } from "./design-tokens.js";
11
+ //#region src/blockFields.ts
12
+ let registeredBlockFields = {};
13
+ /**
14
+ * Registers the theme's block field metadata so `isBlockFieldLocalized` can
15
+ * resolve it without importing a virtual module id — the SDK packages are
16
+ * published plain and cannot resolve `virtual:eldra/block-fields` at their
17
+ * own build time the way an app entry bundled by `@eldrajs/vite-plugin-theme`
18
+ * can. The themed app's bootstrap (theme-nuxt's runtime plugin, or an
19
+ * equivalent entry for another adapter) imports `virtual:eldra/block-fields`
20
+ * and calls this once at startup with the resolved map; call it again (e.g.
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.
26
+ */
27
+ function registerBlockFields(fields, themeId) {
28
+ registeredBlockFields = fields;
29
+ registerThemeId(themeId);
30
+ }
31
+ /**
32
+ * Whether the manifest marks this block field `localized`. A rich-text
33
+ * renderer uses it to default an omitted `locale` to the preview's active
34
+ * content locale — a localized field's draft is keyed per locale, so the
35
+ * marking attributes (and therefore every §18 v3 rich-text report) must carry
36
+ * the locale the render actually used. Returns false for an unknown
37
+ * block/field and outside a themed build.
38
+ *
39
+ * `metadata.toolbar` is deliberately not read here: §18 v3 keeps the toolbar
40
+ * to Studio, which gets the control list from Core's field definitions. The
41
+ * vite plugin still validates the ids at build time.
42
+ */
43
+ function isBlockFieldLocalized(apiId, fieldId) {
44
+ if (apiId === void 0) return false;
45
+ return registeredBlockFields[registeredBlockApiId(apiId)]?.find((field) => field.fieldId === fieldId)?.localized === true;
46
+ }
47
+ /**
48
+ * Resolves the manifest `type` of a block field from its dot-separated data
49
+ * path, descending into `list` (via `metadata.item`, projected verbatim by
50
+ * `blockFieldsModuleSource`) and `composite` (via `metadata.fields`) field
51
+ * definitions as the path requires. A path segment that is purely digits
52
+ * (`"0"`, `"12"`, ...) is a list array index, not a field id, and is skipped
53
+ * rather than matched — `"items.0.variant"` resolves `variant` inside the
54
+ * `items` list's item definition, the same shape `stegaWalk.ts`'s `walk`
55
+ * produces for a `select` nested inside a `list`'s composite item. Trailing
56
+ * numeric segments past a field of any other type (notably a `multiple`
57
+ * `select`, whose resolved value is an array of `{value,label}` rather than
58
+ * a nested `list` item schema) resolve to that field's own type — repeated
59
+ * selected values, not a nested field. A path that runs out of matching
60
+ * fields, or that tries to descend through non-numeric segments past a field
61
+ * type other than `list`/`composite`, resolves to `undefined` — never a
62
+ * guess.
63
+ */
64
+ function resolveBlockFieldType(fields, segments) {
65
+ const [head, ...rest] = segments;
66
+ if (head === void 0) return void 0;
67
+ const field = fields?.find((f) => f.fieldId === head);
68
+ if (field === void 0) return void 0;
69
+ if (rest.length === 0) return field.type;
70
+ if (field.type === "list") {
71
+ const item = field.metadata?.item;
72
+ if (item === null || typeof item !== "object" || Array.isArray(item)) return void 0;
73
+ const itemDef = item;
74
+ 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 (itemDef.type !== "composite") return void 0;
77
+ return resolveBlockFieldType(Array.isArray(itemDef.metadata?.fields) ? itemDef.metadata.fields : void 0, afterIndex);
78
+ }
79
+ if (field.type === "composite") {
80
+ const metaFields = field.metadata?.fields;
81
+ return resolveBlockFieldType(Array.isArray(metaFields) ? metaFields : void 0, rest);
82
+ }
83
+ if (rest.every((segment) => /^\d+$/.test(segment))) return field.type;
84
+ }
85
+ /**
86
+ * Whether the manifest marks the block field at `path` (a top-level field
87
+ * id, or a dot-separated data path reaching into a `list`'s composite item —
88
+ * see `resolveBlockFieldType`) `type: "select"`. `encodeEntryDataStega` and
89
+ * the public/preview read path's `{value,label}` unwrap both use this to
90
+ * recognize a select field's resolved value (a plain string like
91
+ * `"primary"`/`"subtle"`, or `{value,label}` before unwrapping): a
92
+ * `Block.vue` compares that value with `===` against literal option
93
+ * strings, so it must never be stega-encoded, and any two-string-key
94
+ * `{value,label}` object that is *not* a registered select (an ordinary
95
+ * composite field a theme author happens to name `value`/`label`) must
96
+ * never be unwrapped. Returns false for an unknown block/field, a path that
97
+ * does not resolve, and outside a themed build (or for any schema with no
98
+ * registered block fields at all, e.g. a non-block entry such as a page) —
99
+ * absence of a registration is never treated as permission to unwrap or to
100
+ * skip encoding.
101
+ */
102
+ function isBlockFieldSelect(apiId, path) {
103
+ if (apiId === void 0) return false;
104
+ return resolveBlockFieldType(registeredBlockFields[registeredBlockApiId(apiId)], path.split(".")) === "select";
105
+ }
106
+ /** Ceiling on the *computed* backoff. A `Retry-After` is honoured beyond it. */
107
+ const DEFAULT_RETRY_MAX_DELAY_MS = 5e3;
108
+ /**
109
+ * Ceiling on a honoured `Retry-After`. The header is the gateway's own answer
110
+ * and is followed as given — but a build must not be hostage to one: a limit
111
+ * counted per minute never needs longer than this, and a header that asks for
112
+ * an hour (a misconfiguration, or a proxy in front of the gateway) would
113
+ * otherwise hang a build with nothing said.
114
+ */
115
+ const MAX_RETRY_AFTER_MS = 6e4;
116
+ /** `429` is the rate limit itself; `503` is a gateway that is not up yet. */
117
+ const RETRYABLE_STATUS = /* @__PURE__ */ new Set([429, 503]);
118
+ /**
119
+ * Methods that may be repeated. Idempotence is the whole test: a `POST` that
120
+ * timed out may well have been applied, so asking again could duplicate it.
121
+ * Every gateway *read* is one of these.
122
+ */
123
+ const IDEMPOTENT_METHODS = /* @__PURE__ */ new Set([
124
+ "GET",
125
+ "HEAD",
126
+ "OPTIONS"
127
+ ]);
128
+ /**
129
+ * Transport failures worth repeating. `fetch` reports a dropped connection as a
130
+ * `TypeError` whose `cause` carries the real code, and a raw socket error
131
+ * carries one of these codes directly.
132
+ */
133
+ const RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
134
+ "ECONNRESET",
135
+ "ECONNREFUSED",
136
+ "ETIMEDOUT",
137
+ "EPIPE",
138
+ "EAI_AGAIN",
139
+ "UND_ERR_SOCKET",
140
+ "UND_ERR_CONNECT_TIMEOUT",
141
+ "UND_ERR_HEADERS_TIMEOUT",
142
+ "UND_ERR_BODY_TIMEOUT"
143
+ ]);
144
+ /**
145
+ * What a runtime says when the *network* failed, lower-cased and matched as a
146
+ * prefix. `fetch` raises a bare `TypeError` for two unrelated things — a
147
+ * connection that failed, and a request that was malformed (an unparseable
148
+ * URL, an invalid header name, a `GET` with a body) — and only the first is
149
+ * worth repeating: a malformed request will fail identically every time, so
150
+ * retrying it spends four waits per read, multiplied by a build's route count,
151
+ * on a bug that cannot succeed. The message is the only thing that separates
152
+ * them when no `code` is attached, so these are the known spellings, and a
153
+ * runtime whose wording is not here simply fails on the first attempt the way
154
+ * it did before any of this existed.
155
+ */
156
+ const NETWORK_ERROR_MESSAGES = [
157
+ "fetch failed",
158
+ "failed to fetch",
159
+ "load failed",
160
+ "networkerror when attempting to fetch",
161
+ "network error",
162
+ "error sending request",
163
+ "terminated"
164
+ ];
165
+ /**
166
+ * The policy a client was built with, with every unset or nonsensical value
167
+ * filled in. `attempts` counts the first try, so `1` — and `0`, which is what a
168
+ * consumer writes to mean "do not retry" — is one request and no waiting.
169
+ */
170
+ function resolveRetryPolicy(options) {
171
+ return {
172
+ attempts: positive(options?.attempts, 5, 1),
173
+ baseDelayMs: positive(options?.baseDelayMs, 250, 0),
174
+ maxDelayMs: positive(options?.maxDelayMs, DEFAULT_RETRY_MAX_DELAY_MS, 0)
175
+ };
176
+ }
177
+ function positive(value, fallback, floor) {
178
+ if (value === void 0 || !Number.isFinite(value)) return fallback;
179
+ return Math.max(floor, value);
180
+ }
181
+ function isIdempotentMethod(method) {
182
+ return IDEMPOTENT_METHODS.has((method ?? "GET").toUpperCase());
183
+ }
184
+ function isRetryableStatus(status) {
185
+ return RETRYABLE_STATUS.has(status);
186
+ }
187
+ /** Whether this rejection is the caller's own abort rather than a failure. */
188
+ function isAbortError(cause) {
189
+ return typeof cause === "object" && cause !== null && cause.name === "AbortError";
190
+ }
191
+ function isRetryableFetchError(cause) {
192
+ if (isAbortError(cause)) return false;
193
+ const code = errorCodeOf(cause);
194
+ if (code !== void 0) return RETRYABLE_ERROR_CODES.has(code);
195
+ if (!(cause instanceof TypeError)) return false;
196
+ const message = cause.message.toLowerCase();
197
+ return NETWORK_ERROR_MESSAGES.some((known) => message.startsWith(known));
198
+ }
199
+ /**
200
+ * The error's own `code`, or the one on its `cause` — `fetch` wraps a socket
201
+ * error in a `TypeError` and puts the code one level down.
202
+ */
203
+ function errorCodeOf(cause) {
204
+ const own = cause?.code;
205
+ if (typeof own === "string") return own;
206
+ const inner = cause?.cause?.code;
207
+ return typeof inner === "string" ? inner : void 0;
208
+ }
209
+ /**
210
+ * `Retry-After` as milliseconds to wait, or `null` when the header is absent or
211
+ * is neither a delay in seconds nor an HTTP-date. An HTTP-date already in the
212
+ * past is "now", never a negative wait.
213
+ */
214
+ function parseRetryAfter(value, nowMs) {
215
+ if (value === null || value === void 0) return null;
216
+ const raw = value.trim();
217
+ if (raw === "") return null;
218
+ if (/^\d+(?:\.\d+)?$/.test(raw)) return clampRetryAfter(Number(raw) * 1e3);
219
+ const date = Date.parse(raw);
220
+ if (!Number.isFinite(date)) return null;
221
+ return clampRetryAfter(date - nowMs);
222
+ }
223
+ function clampRetryAfter(ms) {
224
+ return Math.min(MAX_RETRY_AFTER_MS, Math.max(0, ms));
225
+ }
226
+ /**
227
+ * `baseDelayMs × 2^attempt`, capped, with equal jitter: half the window is
228
+ * fixed and half is random, so several builds (or several reads of one build)
229
+ * throttled by the same burst do not all come back in the same millisecond.
230
+ * `attempt` is zero-based — the index of the try that just failed.
231
+ */
232
+ function backoffDelayMs(attempt, policy, random = Math.random) {
233
+ const window = Math.min(policy.baseDelayMs * 2 ** attempt, policy.maxDelayMs);
234
+ return window / 2 + random() * (window / 2);
235
+ }
236
+ /**
237
+ * `fetch`, repeated while the answer is "not now".
238
+ *
239
+ * The caller's `AbortSignal` ends it immediately, during a wait as much as
240
+ * during a request: the rejection is the signal's own reason, so an aborted
241
+ * read is indistinguishable from one `fetch` aborted itself. A response that is
242
+ * going to be retried has its body released first — an unread body keeps the
243
+ * connection open, and a build makes thousands of these.
244
+ */
245
+ async function fetchWithRetry(doFetch, url, init, policy, deps = {}) {
246
+ const random = deps.random ?? Math.random;
247
+ const now = deps.now ?? Date.now;
248
+ const signal = init.signal ?? void 0;
249
+ const mayRetry = policy.attempts > 1 && isIdempotentMethod(init.method);
250
+ for (let attempt = 0;; attempt += 1) {
251
+ const lastAttempt = attempt >= policy.attempts - 1;
252
+ let response;
253
+ try {
254
+ response = await doFetch(url, init);
255
+ } catch (cause) {
256
+ if (!mayRetry || lastAttempt || !isRetryableFetchError(cause)) throw cause;
257
+ await wait(backoffDelayMs(attempt, policy, random), signal);
258
+ continue;
259
+ }
260
+ if (!mayRetry || lastAttempt || !isRetryableStatus(response.status)) return response;
261
+ const retryAfter = parseRetryAfter(headerOf(response, "retry-after"), now());
262
+ releaseBody(response);
263
+ await wait(retryAfter ?? backoffDelayMs(attempt, policy, random), signal);
264
+ }
265
+ }
266
+ function headerOf(response, name) {
267
+ return response.headers?.get?.(name) ?? null;
268
+ }
269
+ function releaseBody(response) {
270
+ try {
271
+ response.body?.cancel?.().catch(() => {});
272
+ } catch {}
273
+ }
274
+ function wait(ms, signal) {
275
+ return new Promise((resolve, reject) => {
276
+ if (signal?.aborted === true) {
277
+ reject(abortReason(signal));
278
+ return;
279
+ }
280
+ let onAbort;
281
+ const timer = setTimeout(() => {
282
+ if (onAbort !== void 0) signal?.removeEventListener("abort", onAbort);
283
+ resolve();
284
+ }, ms);
285
+ if (signal !== void 0) {
286
+ onAbort = () => {
287
+ clearTimeout(timer);
288
+ reject(abortReason(signal));
289
+ };
290
+ signal.addEventListener("abort", onAbort, { once: true });
291
+ }
292
+ });
293
+ }
294
+ function abortReason(signal) {
295
+ const reason = signal.reason;
296
+ if (reason !== void 0) return reason;
297
+ return new DOMException("This operation was aborted", "AbortError");
298
+ }
299
+ //#endregion
300
+ //#region src/stegaWalk.ts
301
+ const LOCALE_KEY = /^[A-Za-z0-9]{1,8}(?:-[A-Za-z0-9]{1,8})*$/;
302
+ /**
303
+ * A resolved `select` field's public-read shape: the CMS gateway replaces
304
+ * the stored plain string with `{ value, label }` so a schema-blind consumer
305
+ * can show a human label.
306
+ * Themes only ever declare `select` fields as their plain value union
307
+ * (generated from `block.json`), so `Block.vue` compares the field directly
308
+ * against those literals — never against this wrapper. Left unprojected in
309
+ * the live-editing draft, a `select`/`variant` field never matches and a
310
+ * block silently keeps its default/no-variant markup while editing.
311
+ *
312
+ * This shape check alone is not enough to unwrap: a theme-authored composite
313
+ * field can legitimately declare two string sub-fields literally named
314
+ * `value`/`label`. `project` below additionally confirms, via
315
+ * `isBlockFieldSelect`, that the *registered* field at the current path
316
+ * really is `type: "select"` before unwrapping.
317
+ */
318
+ function looksLikeSelectValue$1(value) {
319
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
320
+ const record = value;
321
+ return Object.keys(record).length === 2 && typeof record.value === "string" && typeof record.label === "string";
322
+ }
323
+ /**
324
+ * Projects a complete localized CMS draft into the active-locale shape used
325
+ * by theme renderers. The input is never mutated, so Studio can keep sending
326
+ * and persisting the complete document.
327
+ *
328
+ * `apiId` (the entry's own `schemaApiId`, when known) gates the
329
+ * `{value,label}` select unwrap above on `isBlockFieldSelect`, tracking the
330
+ * dot-separated field path as the walk descends (the same convention
331
+ * `encodeEntryDataStega`'s `walk` uses), so it only fires for a field the
332
+ * theme's manifest actually registered as `type: "select"` — including one
333
+ * nested inside a `list`'s composite item, e.g. `"items.0.variant"`. When
334
+ * `apiId` is omitted, or the schema has no registered block fields at all
335
+ * (a non-block entry, such as a page, never appears in the block-fields
336
+ * registry), `isBlockFieldSelect` returns false for every path and nothing
337
+ * is unwrapped — safe by construction, never a guess.
338
+ *
339
+ * Entering a nested resolved entry doc (`{id, data, schemaApiId, ...}` —
340
+ * the shape a page's embedded `blocks[]` array carries, or any other
341
+ * resolved reference field) re-derives `apiId` from that doc's own
342
+ * `schemaApiId` and resets the path, mirroring `encodeEntryDataStega`'s
343
+ * `walkNode`: a page's own schema is never registered as a block, so
344
+ * threading the outer `apiId` straight through would make every nested
345
+ * block's own select fields silently fail to unwrap forever, exactly the
346
+ * "non-block entry" case above — but the nested doc has its own registered
347
+ * fields once its own `schemaApiId` is used.
348
+ */
349
+ function projectEntryDataLocale(data, locale, apiId) {
350
+ const project = (value, path, currentApiId) => {
351
+ if (Array.isArray(value)) return value.map((item, i) => project(item, path === "" ? String(i) : `${path}.${i}`, currentApiId));
352
+ if (typeof value !== "object" || value === null) return value;
353
+ if (looksLikeSelectValue$1(value) && isBlockFieldSelect(currentApiId, path)) return value.value;
354
+ if (looksLikeCatalogReference(value)) return value;
355
+ if (looksLikeEntryDoc$1(value)) {
356
+ const nestedApiId = typeof value.schemaApiId === "string" ? value.schemaApiId : void 0;
357
+ return {
358
+ ...value,
359
+ data: project(value.data, "", nestedApiId)
360
+ };
361
+ }
362
+ const entries = Object.entries(value);
363
+ if (locale !== null && entries.length > 0 && entries.every(([key]) => LOCALE_KEY.test(key)) && Object.prototype.hasOwnProperty.call(value, locale)) return project(value[locale], path, currentApiId);
364
+ return Object.fromEntries(entries.map(([key, child]) => [key, project(child, path === "" ? key : `${path}.${key}`, currentApiId)]));
365
+ };
366
+ return project(data, "", apiId);
367
+ }
368
+ /** A resolved reference embedded by the gateway looks like an entry doc: { id, data: {...} }. */
369
+ function looksLikeEntryDoc$1(v) {
370
+ return typeof v === "object" && v !== null && typeof v.id === "string" && typeof v.data === "object" && v.data !== null && !Array.isArray(v.data);
371
+ }
372
+ /**
373
+ * A catalog reference — a product or a collection a `reference` field points at
374
+ * (`{ id, _type: 'collection', slug, status, productCount, … }`, resolved, or
375
+ * just `{ id, _type }` at depth 0, for an archived collection, and in a
376
+ * page-builder draft overlay). It
377
+ * carries no `data`, so it is never an entry doc, and every field on it is
378
+ * catalog control data a block looks the thing up by — `slug` above all, which
379
+ * a theme block hands straight to the storefront. Encoding it would send that
380
+ * request after a collection nobody has, exactly like an encoded media URL
381
+ * (`looksLikeMediaAsset`) requests an asset nobody has. `translations` is also
382
+ * locale-keyed without being one of the theme's own localized fields, so the
383
+ * locale projection has to leave it whole too.
384
+ */
385
+ function looksLikeCatalogReference(v) {
386
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
387
+ const record = v;
388
+ return typeof record.id === "string" && (record._type === "collection" || record._type === "product") && record.data === void 0;
389
+ }
390
+ /** An unresolved CMS reference keeps its identity fields as transport metadata. */
391
+ function looksLikeEntryReference(v) {
392
+ return typeof v === "object" && v !== null && typeof v.id === "string" && typeof v._type === "string";
393
+ }
394
+ /** Core's ordered compatibility mirror represents references as
395
+ * `{ position, type: 'entry', value: '<uuid>' }`. These transport fields must
396
+ * remain structural so the preview overlay can resolve them after stega. */
397
+ function looksLikePositionedEntryReference(v) {
398
+ return typeof v === "object" && v !== null && Number.isInteger(v.position) && v.type === "entry" && typeof v.value === "string";
399
+ }
400
+ /** Hydrated media is renderer control data. Encoding its URL (or any other
401
+ * asset metadata) changes the requested resource and makes preview images
402
+ * fail even though the original URL is valid. */
403
+ function looksLikeMediaAsset(v) {
404
+ return typeof v === "object" && v !== null && typeof v.assetId === "string" && typeof v.url === "string";
405
+ }
406
+ /** Deep-copies `data`, stega-encoding every string leaf with its dot path.
407
+ * Entering a nested resolved entry doc re-roots entryId and fieldPath.
408
+ *
409
+ * `apiId` (the entry's own `schemaApiId`, when known) is used only to skip
410
+ * encoding a registered `select` field's resolved value (e.g. `variant`,
411
+ * top-level or nested inside a `list`'s composite item — see
412
+ * `isBlockFieldSelect`): that string is never displayed as editable text,
413
+ * only compared with `===` inside a `Block.vue`, and stega's invisible
414
+ * tracking characters make that comparison silently fail forever. Entering
415
+ * a nested resolved entry doc (a page's embedded block) re-derives `apiId`
416
+ * from that doc's own `schemaApiId`, so a block's own select fields are
417
+ * protected the same way whether it is fetched directly or embedded inside
418
+ * a page. */
419
+ function encodeEntryDataStega(entryId, data, locale, apiId) {
420
+ const cloneStructural = (value) => {
421
+ if (Array.isArray(value)) return value.map(cloneStructural);
422
+ if (typeof value !== "object" || value === null) return value;
423
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, cloneStructural(child)]));
424
+ };
425
+ const walkRichTextNode = (value, ownerId, path) => {
426
+ const out = {};
427
+ for (const [key, child] of Object.entries(value)) {
428
+ const childPath = path === "" ? key : `${path}.${key}`;
429
+ if (key === "type" || key === "attrs" || key === "marks") out[key] = cloneStructural(child);
430
+ else if (key === "content" && Array.isArray(child)) out[key] = child.map((nested, index) => {
431
+ const nestedPath = `${childPath}.${index}`;
432
+ return looksLikeRichTextNode(nested) ? walkRichTextNode(nested, ownerId, nestedPath) : walkNode(nested, ownerId, nestedPath);
433
+ });
434
+ else out[key] = walkNode(child, ownerId, childPath);
435
+ }
436
+ return out;
437
+ };
438
+ const walk = (value, ownerId, path) => {
439
+ if (typeof value === "string") {
440
+ if (isBlockFieldSelect(apiId, path)) return value;
441
+ return encodeStega(value, {
442
+ entryId: ownerId,
443
+ fieldPath: path,
444
+ locale
445
+ });
446
+ }
447
+ if (Array.isArray(value)) return value.map((item, i) => walkNode(item, ownerId, path === "" ? String(i) : `${path}.${i}`));
448
+ if (typeof value === "object" && value !== null) {
449
+ const out = {};
450
+ for (const [key, v] of Object.entries(value)) out[key] = walkNode(v, ownerId, path === "" ? key : `${path}.${key}`);
451
+ return out;
452
+ }
453
+ return value;
454
+ };
455
+ const walkNode = (value, ownerId, path) => {
456
+ if (looksLikeRichTextRoot(value)) return walkRichTextNode(value, ownerId, path);
457
+ if (looksLikeMediaAsset(value)) return cloneStructural(value);
458
+ if (looksLikeEntryDoc$1(value)) {
459
+ const nestedApiId = typeof value.schemaApiId === "string" ? value.schemaApiId : void 0;
460
+ return {
461
+ ...value,
462
+ data: encodeEntryDataStega(value.id, value.data, locale, nestedApiId)
463
+ };
464
+ }
465
+ if (looksLikeCatalogReference(value)) return cloneStructural(value);
466
+ if (looksLikeEntryReference(value)) return {
467
+ ...walk(value, ownerId, path),
468
+ id: value.id,
469
+ _type: value._type
470
+ };
471
+ if (looksLikePositionedEntryReference(value)) return cloneStructural(value);
472
+ return walk(value, ownerId, path);
473
+ };
474
+ const result = {};
475
+ for (const [key, v] of Object.entries(data)) result[key] = key === "layout" ? v : walkNode(v, entryId, key);
476
+ return result;
477
+ }
478
+ function looksLikeRichTextRoot(value) {
479
+ return looksLikeRichTextNode(value) && value.type === "doc";
480
+ }
481
+ function looksLikeRichTextNode(value) {
482
+ return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.type === "string";
483
+ }
484
+ //#endregion
485
+ //#region src/clientTypes.ts
486
+ var EldraClientError = class extends Error {
487
+ status;
488
+ path;
489
+ constructor(status, statusText, path) {
490
+ super(`[eldra] gateway request failed: ${status} ${statusText} for ${path}`);
491
+ this.name = "EldraClientError";
492
+ this.status = status;
493
+ this.path = path;
494
+ }
495
+ };
496
+ //#endregion
497
+ //#region src/client.ts
498
+ /**
499
+ * Strips every trailing `/` from a URL (`https://x///` → `https://x`). A regex
500
+ * equivalent (`/\/+$/`) backtracks polynomially on a long run of slashes
501
+ * because the engine re-tries every split of the repeated group before
502
+ * failing to match past the string's end; this walks the string once from
503
+ * the end instead, which is linear regardless of how many slashes it finds.
504
+ */
505
+ function stripTrailingSlashes(value) {
506
+ let end = value.length;
507
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end--;
508
+ return value.slice(0, end);
509
+ }
510
+ function createEldraClient(opts) {
511
+ const gatewayUrl = stripTrailingSlashes(opts.gatewayUrl);
512
+ const doFetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
513
+ const retryPolicy = resolveRetryPolicy(opts.retry);
514
+ const stegaEnabled = opts.stega === true;
515
+ const defaultLocale = opts.defaultLocale ?? null;
516
+ let previewToken = null;
517
+ const requestErrorListeners = /* @__PURE__ */ new Set();
518
+ function buildUrl(path, query, extra) {
519
+ const url = new URL(gatewayUrl + path);
520
+ if (query?.locale !== void 0) url.searchParams.set("locale", query.locale);
521
+ if (query?.depth !== void 0) url.searchParams.set("depth", String(query.depth));
522
+ if (query?.page !== void 0) url.searchParams.set("page", String(query.page));
523
+ if (query?.pageSize !== void 0) url.searchParams.set("pageSize", String(query.pageSize));
524
+ if (query?.sort?.length) url.searchParams.set("sort", query.sort.join(","));
525
+ if (query?.fields?.length) url.searchParams.set("fields", query.fields.join(","));
526
+ for (const f of query?.filter ?? []) url.searchParams.append("filter", f);
527
+ for (const [k, v] of Object.entries(extra ?? {})) url.searchParams.set(k, v);
528
+ return url;
529
+ }
530
+ async function request(url, init) {
531
+ const headers = new Headers(init?.headers);
532
+ headers.set("X-Org-Id", opts.orgId);
533
+ if (previewToken !== null) headers.set("X-Preview-Token", previewToken);
534
+ const merged = {
535
+ ...init,
536
+ headers
537
+ };
538
+ if (previewToken !== null) merged.cache = "no-store";
539
+ const tokenAtRequest = previewToken;
540
+ const res = await fetchWithRetry(doFetch, url.toString(), merged, retryPolicy);
541
+ if (!res.ok) {
542
+ const error = new EldraClientError(res.status, res.statusText, url.pathname);
543
+ if (previewToken === tokenAtRequest) notifyRequestError(error);
544
+ throw error;
545
+ }
546
+ return res;
547
+ }
548
+ function notifyRequestError(error) {
549
+ for (const listener of [...requestErrorListeners]) try {
550
+ listener(error);
551
+ } catch {}
552
+ }
553
+ function maybeStega(entry, locale) {
554
+ const apiId = typeof entry.schemaApiId === "string" ? entry.schemaApiId : void 0;
555
+ const projected = {
556
+ ...entry,
557
+ data: projectLocalizedLeaves(entry.data, locale, defaultLocale, apiId)
558
+ };
559
+ if (!stegaEnabled || previewToken === null) return projected;
560
+ return {
561
+ ...projected,
562
+ data: encodeEntryDataStega(entry.id, projected.data, locale, apiId)
563
+ };
564
+ }
565
+ return {
566
+ catalog: {
567
+ async getProduct(productIdOrSlug, query) {
568
+ return await (await request(buildUrl(`/catalog/v1/products/${encodeURIComponent(productIdOrSlug)}`, query))).json();
569
+ },
570
+ async listProducts(query) {
571
+ return toCatalogList(await (await request(buildUrl("/catalog/v1/products/list", query))).json());
572
+ },
573
+ async getCollection(slug, query) {
574
+ return await (await request(buildUrl(`/catalog/v1/collections/${encodeURIComponent(slug)}`, query))).json();
575
+ },
576
+ async listCollections(query) {
577
+ return toCatalogList(await (await request(buildUrl("/catalog/v1/collections", query))).json());
578
+ },
579
+ async listCategories(query) {
580
+ return toCatalogList(await (await request(buildUrl("/catalog/v1/categories", query))).json());
581
+ }
582
+ },
583
+ async getEntries(schemaIdentifier, query) {
584
+ const list = await (await request(buildUrl(`/cms/v1/schema/${encodeURIComponent(schemaIdentifier)}/entry`, query))).json();
585
+ if (list.data !== void 0 && list.data !== null && !Array.isArray(list.data)) throw new TypeError("[eldra] gateway entry list data must be an array");
586
+ return {
587
+ ...list,
588
+ data: (list.data ?? []).map((e) => maybeStega(e, query?.locale ?? null))
589
+ };
590
+ },
591
+ async getEntry(schemaIdentifier, entryId, query) {
592
+ return maybeStega(await (await request(buildUrl(`/cms/v1/schema/${encodeURIComponent(schemaIdentifier)}/entry/${encodeURIComponent(entryId)}`, query))).json(), query?.locale ?? null);
593
+ },
594
+ async getEntryByUniqueField(schemaIdentifier, fieldId, value, query) {
595
+ return maybeStega(await (await request(buildUrl(`/cms/v1/schema/${encodeURIComponent(schemaIdentifier)}/entry/unique/${encodeURIComponent(fieldId)}/${encodeURIComponent(value)}`, query))).json(), query?.locale ?? null);
596
+ },
597
+ async resolveEntryListField(entryId, fieldId, query) {
598
+ return await (await request(buildUrl(`/cms/v1/entry/${encodeURIComponent(entryId)}/list/${encodeURIComponent(fieldId)}`, query))).json();
599
+ },
600
+ async resolveEntryList(body, query) {
601
+ return await (await request(buildUrl("/cms/v1/entry-list/resolve", query), {
602
+ method: "POST",
603
+ headers: { "content-type": "application/json" },
604
+ body: JSON.stringify(body)
605
+ })).json();
606
+ },
607
+ async getTypeScriptDefinitions(tsOpts) {
608
+ const url = new URL(`${gatewayUrl}/cms/v1/typescript-definitions`);
609
+ if (tsOpts?.schemas?.length) url.searchParams.set("schemas", tsOpts.schemas.join(","));
610
+ if (tsOpts?.maxDepth !== void 0) url.searchParams.set("maxDepth", String(tsOpts.maxDepth));
611
+ if (tsOpts?.moduleName !== void 0) url.searchParams.set("moduleName", tsOpts.moduleName);
612
+ return await (await request(url)).text();
613
+ },
614
+ enablePreview(token) {
615
+ previewToken = token;
616
+ },
617
+ disablePreview() {
618
+ previewToken = null;
619
+ },
620
+ get previewEnabled() {
621
+ return previewToken !== null;
622
+ },
623
+ onRequestError(listener) {
624
+ requestErrorListeners.add(listener);
625
+ return () => {
626
+ requestErrorListeners.delete(listener);
627
+ };
628
+ },
629
+ encodeEntryDataStega
630
+ };
631
+ }
632
+ /**
633
+ * Normalise a catalog list response. The gateway serialises an empty page as
634
+ * `"data": null`, and a caller that pages through the list must not have to
635
+ * guess whether a missing `meta` means "one page" or "keep asking" — an absent
636
+ * meta is reported as a single, final page.
637
+ *
638
+ * **A bare array is a list too.** `GET /catalog/v1/categories` answers the whole
639
+ * tree as a top-level array rather than a `{data, meta}` page — the categories
640
+ * are a handful of rows and the endpoint takes no paging — and reading that as
641
+ * "an object with no `data`" made every category read answer *nothing*: no
642
+ * category target for a `link` field to resolve, and no category route for a
643
+ * build to generate, with no error anywhere to say so. The two paged endpoints
644
+ * are unaffected: they answer an object, and an object still has to carry an
645
+ * array under `data` or this throws.
646
+ */
647
+ function toCatalogList(value) {
648
+ if (Array.isArray(value)) return toCatalogList({ data: value });
649
+ const raw = value ?? {};
650
+ if (raw.data !== void 0 && raw.data !== null && !Array.isArray(raw.data)) throw new TypeError("[eldra] gateway catalog list data must be an array");
651
+ const data = raw.data ?? [];
652
+ return {
653
+ data,
654
+ meta: raw.meta ?? {
655
+ hasNext: false,
656
+ hasPrev: false,
657
+ page: 1,
658
+ pageSize: data.length,
659
+ rows: data.length,
660
+ total: data.length,
661
+ totalPages: 1
662
+ }
663
+ };
664
+ }
665
+ const localeKey = /^[a-z]{2}(?:-[A-Za-z0-9]{2,8})*$/;
666
+ /**
667
+ * A resolved `select` field's public-read shape: the CMS gateway replaces
668
+ * the stored plain string with `{ value, label }` so a schema-blind consumer
669
+ * can show a human label.
670
+ * Themes only ever declare `select` fields as their plain value union
671
+ * (`variant?: 'primary' | 'subtle' | 'split'`, generated from `block.json`),
672
+ * so every `Block.vue` compares `data.variant` against those literals
673
+ * directly — never against this wrapper. Left unprojected, every variant
674
+ * (and any other select-typed) field always fails that comparison and a
675
+ * block silently renders its default/no-variant markup forever, in preview
676
+ * and in production alike.
677
+ *
678
+ * This shape check alone is not enough to unwrap: a theme-authored composite
679
+ * field can legitimately declare two string sub-fields literally named
680
+ * `value`/`label` (a stat/metric field, a generic chip). Every call site
681
+ * must additionally confirm, via `isBlockFieldSelect`, that the *registered*
682
+ * field at this path really is `type: "select"` before unwrapping.
683
+ */
684
+ function looksLikeSelectValue(value) {
685
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
686
+ const record = value;
687
+ return Object.keys(record).length === 2 && typeof record.value === "string" && typeof record.label === "string";
688
+ }
689
+ /**
690
+ * Public CMS reads normally resolve localized fields server-side. Older content
691
+ * can still contain locale maps below list/composite fields because those
692
+ * leaves were persisted before recursive localization extraction existed.
693
+ * Project only objects whose every key is a locale tag, leaving ordinary
694
+ * records (including media and references) untouched.
695
+ *
696
+ * `apiId` (the entry's own `schemaApiId`, when known) and `path` (the
697
+ * dot-separated field path built as this walk descends, matching
698
+ * `stegaWalk.ts`'s path convention) gate the `{value,label}` select unwrap
699
+ * above on `isBlockFieldSelect`, so it only ever fires for a field the
700
+ * theme's manifest actually registered as `type: "select"` — including one
701
+ * nested inside a `list`'s composite item, e.g. `"items.0.variant"`. When
702
+ * `apiId` is undefined, or the schema has no registered block fields at all
703
+ * (a non-block entry, such as a page, never appears in the block-fields
704
+ * registry), `isBlockFieldSelect` returns false for every path and nothing
705
+ * is unwrapped — safe by construction, never a guess.
706
+ *
707
+ * Entering a nested resolved entry doc (`{id, data, schemaApiId, ...}` — the
708
+ * shape a page's embedded `blocks[]` array carries, or any other resolved
709
+ * reference field) re-derives `apiId` from that doc's own `schemaApiId` and
710
+ * resets `path`, mirroring `stegaWalk.ts`'s `encodeEntryDataStega`. Without
711
+ * this, every `getEntry`/`getEntries` call that embeds referenced entries
712
+ * (a page fetched with `depth` > 0, most visibly) threads the *outer*
713
+ * entry's `apiId` — a page's own schema is never a registered block — into
714
+ * every nested block, so none of their `select` fields ever unwrap: exactly
715
+ * the "non-block entry" case above, but for every block a page renders.
716
+ */
717
+ function looksLikeEntryDoc(v) {
718
+ return typeof v === "object" && v !== null && typeof v.id === "string" && typeof v.data === "object" && v.data !== null && !Array.isArray(v.data);
719
+ }
720
+ /**
721
+ * Whether a localized field's value counts as "translated", mirroring the
722
+ * gateway's own server-side rule for a localization row
723
+ * (`entry_read.go`'s `isTranslatedValue`): present and not null, not an empty
724
+ * string after trimming whitespace, not an empty array or object, and a
725
+ * rich-text document only when it carries actual text content. Every other
726
+ * value (including `0`/`false`) counts as translated.
727
+ *
728
+ * Exported so the per-field link fallback below (and a theme, if it ever
729
+ * needs the same call) has one definition of "untranslated" rather than a
730
+ * second copy that can drift from it.
731
+ */
732
+ function isTranslatedValue(value) {
733
+ if (value === null || value === void 0) return false;
734
+ if (typeof value === "string") return value.trim() !== "";
735
+ if (Array.isArray(value)) return value.length > 0;
736
+ if (typeof value === "object") {
737
+ const record = value;
738
+ if (Object.keys(record).length === 0) return false;
739
+ if (record.type === "doc") return richTextDocHasText(record);
740
+ return true;
741
+ }
742
+ return true;
743
+ }
744
+ /** Whether a TipTap-shaped rich-text node carries any non-whitespace text in
745
+ * one of its `text` leaves. Used only to decide whether a whole rich-text
746
+ * document counts as "translated" — never a renderer. */
747
+ function richTextDocHasText(node) {
748
+ if (node === null || typeof node !== "object") return false;
749
+ const { type, text, content } = node;
750
+ if (type === "text") return typeof text === "string" && text.trim() !== "";
751
+ if (!Array.isArray(content)) return false;
752
+ return content.some(richTextDocHasText);
753
+ }
754
+ function isPlainRecord(value) {
755
+ return value !== null && typeof value === "object" && !Array.isArray(value);
756
+ }
757
+ /**
758
+ * Per-field fallback for one locale's chosen node against the default
759
+ * locale's node, for the record-shaped sub-fields of a `link` field (and any
760
+ * other locale-keyed composite). Composite records (not a rich-text
761
+ * document) are merged **per field**: a key `chosen` leaves untranslated is
762
+ * copied from `defaultValue`, and every other key of `chosen` (including one
763
+ * `defaultValue` does not have) is kept. A leaf value — a string, an array,
764
+ * a rich-text document — is replaced only as a whole when `chosen` itself is
765
+ * untranslated.
766
+ *
767
+ * `children` needs no special case: an untranslated (missing/empty) array
768
+ * already falls back to the default's whole array under the same per-field
769
+ * rule, and a translated one is kept outright — never merged by index.
770
+ */
771
+ function mergeLocalizedFallback(chosen, defaultValue) {
772
+ const isComposite = (value) => isPlainRecord(value) && value.type !== "doc";
773
+ if (isComposite(chosen) && isComposite(defaultValue)) {
774
+ const merged = { ...chosen };
775
+ for (const key of Object.keys(defaultValue)) merged[key] = isTranslatedValue(merged[key]) ? mergeLocalizedFallback(merged[key], defaultValue[key]) : defaultValue[key];
776
+ return merged;
777
+ }
778
+ if (Array.isArray(chosen) && Array.isArray(defaultValue)) {
779
+ if (chosen.length === 0) return defaultValue;
780
+ if (chosen.length !== defaultValue.length) return chosen;
781
+ return chosen.map((item, i) => mergeLocalizedFallback(item, defaultValue[i]));
782
+ }
783
+ return isTranslatedValue(chosen) ? chosen : defaultValue;
784
+ }
785
+ function projectLocalizedValue(value, locale, defaultLocale, apiId, path) {
786
+ if (Array.isArray(value)) return value.map((item, i) => projectLocalizedValue(item, locale, defaultLocale, apiId, path === "" ? String(i) : `${path}.${i}`));
787
+ if (value === null || typeof value !== "object") return value;
788
+ if (looksLikeSelectValue(value) && isBlockFieldSelect(apiId, path)) return value.value;
789
+ if (looksLikeEntryDoc(value)) {
790
+ const nestedApiId = typeof value.schemaApiId === "string" ? value.schemaApiId : void 0;
791
+ return {
792
+ ...value,
793
+ data: projectLocalizedValue(value.data, locale, defaultLocale, nestedApiId, "")
794
+ };
795
+ }
796
+ const record = value;
797
+ const keys = Object.keys(record);
798
+ if (keys.length > 0 && keys.every((key) => localeKey.test(key))) {
799
+ const exactKey = locale && record[locale] !== void 0 ? locale : void 0;
800
+ const language = locale?.split("-")[0]?.toLowerCase();
801
+ const languageKey = language ? keys.find((key) => key.split("-")[0]?.toLowerCase() === language) : void 0;
802
+ const chosenKey = exactKey ?? languageKey ?? keys[0];
803
+ const chosen = record[chosenKey];
804
+ const defaultValue = defaultLocale != null && chosenKey !== defaultLocale ? record[defaultLocale] : void 0;
805
+ return projectLocalizedValue(defaultValue !== void 0 ? mergeLocalizedFallback(chosen, defaultValue) : chosen, locale, defaultLocale, apiId, path);
806
+ }
807
+ return Object.fromEntries(Object.entries(record).map(([key, item]) => [key, projectLocalizedValue(item, locale, defaultLocale, apiId, path === "" ? key : `${path}.${key}`)]));
808
+ }
809
+ function projectLocalizedLeaves(data, locale, defaultLocale, apiId) {
810
+ return projectLocalizedValue(data, locale, defaultLocale, apiId, "");
811
+ }
812
+ //#endregion
813
+ //#region src/richText.ts
814
+ /**
815
+ * Ordered ids of every rich-text toolbar control a `block.json` may request
816
+ * in `metadata.toolbar`. §18 v3: the theme no longer renders a toolbar —
817
+ * Studio's overlay editor does — but the list stays here as the single
818
+ * source of truth for the vite-plugin-theme scanner's build-time
819
+ * `metadata.toolbar` validation and theme-vue's block field lookup, so Theme
820
+ * Kit never carries two copies of it.
821
+ *
822
+ * Must stay in sync with the `metadata.toolbar` control ids Core's
823
+ * `richtext.go` validator accepts; a theme whose manifest names an id Core
824
+ * rejects fails ingest.
825
+ */
826
+ const RICH_TEXT_TOOLBAR_CONTROLS = [
827
+ "heading",
828
+ "bold",
829
+ "italic",
830
+ "strike",
831
+ "underline",
832
+ "link",
833
+ "bulletList",
834
+ "orderedList",
835
+ "blockquote",
836
+ "code",
837
+ "codeBlock",
838
+ "hardBreak",
839
+ "horizontalRule",
840
+ "image",
841
+ "embed",
842
+ "highlight",
843
+ "textColor",
844
+ "undo",
845
+ "redo",
846
+ "table"
847
+ ];
848
+ /**
849
+ * Allow ordinary site links while rejecting executable and opaque URL
850
+ * schemes. Framework-neutral so both the theme-vue rich-text renderer and
851
+ * hand-rolled theme code can share one link/asset-src allowlist. Values are
852
+ * stega-stripped before validation since a themed link target can carry the
853
+ * click-tracking payload from `encodeStega`.
854
+ */
855
+ function safeHref(value) {
856
+ if (typeof value !== "string") return null;
857
+ const href = stripStega(value).trim();
858
+ if (href.length === 0 || href.length > 2048 || href.includes("\\") || Array.from(href).some((character) => {
859
+ const codePoint = character.codePointAt(0) ?? 0;
860
+ return codePoint <= 31 || codePoint === 127;
861
+ })) return null;
862
+ if (href.startsWith("/")) return href.startsWith("//") ? null : href;
863
+ if (href.startsWith("#")) return href;
864
+ try {
865
+ const protocol = new URL(href).protocol;
866
+ return [
867
+ "https:",
868
+ "http:",
869
+ "mailto:",
870
+ "tel:"
871
+ ].includes(protocol) ? href : null;
872
+ } catch {
873
+ return null;
874
+ }
875
+ }
876
+ //#endregion
877
+ //#region src/richTextTree.ts
878
+ /**
879
+ * Framework-neutral read renderer for a §18 rich-text field's TipTap JSON
880
+ * document. Produces a plain element tree; each framework binding maps that
881
+ * tree onto its own vnode factory (`@eldrajs/theme-vue`'s `renderRichTextDoc`
882
+ * is ~20 lines of `h()`), so the node/mark rules, the URL gating and the
883
+ * attribute whitelist exist exactly once for every adapter.
884
+ *
885
+ * Read mode only — the theme renders rich text, Studio owns the document and
886
+ * the one headless editor that writes it.
887
+ *
888
+ * §18 v3: every **node** element carries `data-eldra-node="<type>"` and
889
+ * `data-eldra-pos="<open position>"` (see `richTextPositions.ts`), so the
890
+ * overlay can map a DOM selection to a ProseMirror document position without
891
+ * a schema. **Mark** elements (`strong`, `em`, `s`, `u`, `code`, `mark`,
892
+ * `span[style]`, `a`) carry no stamps, and neither do the wrappers that are
893
+ * not nodes: a `codeBlock` stamps its `pre`, not the `code` inside it, and a
894
+ * `table` stamps the `table`, not the `tbody`. The stamps are computed from
895
+ * the document, not from the tree, so a node the sanitiser drops (an unsafe
896
+ * image `src`) still consumes its position and everything after it stays
897
+ * numbered as the document numbers it.
898
+ */
899
+ const HEX_COLOR = /^#[0-9a-fA-F]{3,8}$/;
900
+ const NAMED_COLOR = /^[a-zA-Z]+$/;
901
+ /**
902
+ * Build a TipTap JSON document's content as a render tree. Non-doc input
903
+ * builds an empty tree.
904
+ *
905
+ * Every top-level child is an element: a well-formed document only holds
906
+ * block nodes there, and a malformed one (a text node, or an unknown node
907
+ * wrapping text, directly under `doc`) gets its bare text wrapped in a
908
+ * `span` rather than dropped — so the content survives and a mapper never
909
+ * has to place a text node next to the field root's element children.
910
+ */
911
+ function buildRichTextTree(doc, options) {
912
+ return buildChildren((isDocNode(doc) ? doc : {
913
+ type: "doc",
914
+ content: []
915
+ }).content, options, { pos: 0 }).map((child) => typeof child === "string" ? {
916
+ tag: "span",
917
+ attrs: {},
918
+ children: [child]
919
+ } : child);
920
+ }
921
+ function isDocNode(value) {
922
+ return typeof value === "object" && value !== null && !Array.isArray(value) && value.type === "doc";
923
+ }
924
+ function isNode(value) {
925
+ return typeof value === "object" && value !== null && !Array.isArray(value);
926
+ }
927
+ /** The concatenated, stega-stripped text of every direct text-leaf child of
928
+ * `content` — what `padEmptyBlocks` (see `buildNode`) treats as a
929
+ * textblock's "text". A non-text child (hardBreak, image, embed) contributes
930
+ * no characters. */
931
+ function textContentOf(content) {
932
+ if (!Array.isArray(content)) return "";
933
+ let text = "";
934
+ for (const child of content) if (isNode(child) && child.type === "text") text += richTextText(child);
935
+ return text;
936
+ }
937
+ function buildChildren(nodes, options, cursor) {
938
+ if (!Array.isArray(nodes)) return [];
939
+ const out = [];
940
+ for (const node of nodes) {
941
+ if (!isNode(node)) continue;
942
+ const pos = cursor.pos;
943
+ out.push(...buildNode(node, options, cursor, pos));
944
+ cursor.pos = pos + richTextNodeSize(node);
945
+ }
946
+ return out;
947
+ }
948
+ /** Returns 0..n children: a dropped node (unsafe src, textless text node)
949
+ * contributes nothing, and an unknown node splices its own children in. */
950
+ function buildNode(node, options, cursor, pos) {
951
+ if (node.type === "text") {
952
+ if (typeof node.text !== "string") return [];
953
+ return [applyMarks(richTextText(node), node.marks ?? [], options)];
954
+ }
955
+ cursor.pos = pos + 1;
956
+ const children = () => buildChildren(node.content, options, cursor);
957
+ const stamp = (attrs) => typeof node.type === "string" && node.type !== "" ? {
958
+ ...attrs,
959
+ "data-eldra-node": node.type,
960
+ "data-eldra-pos": String(pos)
961
+ } : attrs;
962
+ const element = (tag, attrs = {}) => [{
963
+ tag,
964
+ attrs: stamp(attrs),
965
+ children: children()
966
+ }];
967
+ const isBlank = /^\s*$/.test(textContentOf(node.content));
968
+ const endsWithHardBreak = (kids) => {
969
+ const last = kids[kids.length - 1];
970
+ return typeof last === "object" && last.tag === "br" && last.attrs["data-eldra-node"] === "hardBreak";
971
+ };
972
+ const padIfEmpty = (kids) => options.padEmptyBlocks === true && (isBlank || endsWithHardBreak(kids)) ? [...kids, {
973
+ tag: "br",
974
+ attrs: { [RICH_TEXT_PAD_ATTR]: "" },
975
+ children: []
976
+ }] : kids;
977
+ const textblockElement = (tag, attrs = {}) => [{
978
+ tag,
979
+ attrs: stamp(attrs),
980
+ children: padIfEmpty(children())
981
+ }];
982
+ switch (node.type) {
983
+ case "paragraph": return textblockElement("p");
984
+ case "heading": return textblockElement(`h${clampHeadingLevel(node.attrs?.level, options.minHeadingLevel)}`);
985
+ case "bulletList": return element("ul");
986
+ case "orderedList": return element("ol");
987
+ case "listItem": return element("li");
988
+ case "blockquote": return element("blockquote");
989
+ case "horizontalRule": return [{
990
+ tag: "hr",
991
+ attrs: stamp({}),
992
+ children: []
993
+ }];
994
+ case "hardBreak": return [{
995
+ tag: "br",
996
+ attrs: stamp({}),
997
+ children: []
998
+ }];
999
+ case "codeBlock": return buildCodeBlock(node, stamp({}), padIfEmpty(children()));
1000
+ case "table": return [{
1001
+ tag: "table",
1002
+ attrs: stamp({}),
1003
+ children: [{
1004
+ tag: "tbody",
1005
+ attrs: {},
1006
+ children: children()
1007
+ }]
1008
+ }];
1009
+ case "tableRow": return element("tr");
1010
+ case "tableHeader": return element("th", tableCellAttrs(node));
1011
+ case "tableCell": return element("td", tableCellAttrs(node));
1012
+ case "image": return buildImage(node, options, stamp);
1013
+ case "embed": return buildEmbed(node, options, stamp);
1014
+ case "doc": return element("span");
1015
+ default: return element("span");
1016
+ }
1017
+ }
1018
+ function buildCodeBlock(node, attrs, children) {
1019
+ const language = typeof node.attrs?.language === "string" ? node.attrs.language : null;
1020
+ return [{
1021
+ tag: "pre",
1022
+ attrs,
1023
+ children: [{
1024
+ tag: "code",
1025
+ attrs: language !== null ? { class: `language-${language}` } : {},
1026
+ children
1027
+ }]
1028
+ }];
1029
+ }
1030
+ function tableCellAttrs(node) {
1031
+ const attrs = {};
1032
+ if (typeof node.attrs?.colspan === "number") attrs.colspan = String(node.attrs.colspan);
1033
+ if (typeof node.attrs?.rowspan === "number") attrs.rowspan = String(node.attrs.rowspan);
1034
+ return attrs;
1035
+ }
1036
+ function buildImage(node, options, stamp) {
1037
+ const src = options.safeHref(node.attrs?.src);
1038
+ if (src === null) return [];
1039
+ const attrs = { src };
1040
+ if (typeof node.attrs?.alt === "string") attrs.alt = node.attrs.alt;
1041
+ if (typeof node.attrs?.title === "string") attrs.title = node.attrs.title;
1042
+ if (typeof node.attrs?.assetId === "string") attrs["data-asset-id"] = node.attrs.assetId;
1043
+ return [{
1044
+ tag: "img",
1045
+ attrs: stamp(attrs),
1046
+ children: []
1047
+ }];
1048
+ }
1049
+ /** No iframe in read mode: an inert div carrying the safe source and provider/title metadata. */
1050
+ function buildEmbed(node, options, stamp) {
1051
+ const src = options.safeHref(node.attrs?.src);
1052
+ if (src === null) return [];
1053
+ const attrs = {
1054
+ class: "eldra-embed",
1055
+ "data-src": src
1056
+ };
1057
+ if (typeof node.attrs?.provider === "string") attrs["data-provider"] = node.attrs.provider;
1058
+ if (typeof node.attrs?.title === "string") attrs.title = node.attrs.title;
1059
+ return [{
1060
+ tag: "div",
1061
+ attrs: stamp(attrs),
1062
+ children: []
1063
+ }];
1064
+ }
1065
+ /**
1066
+ * A heading node's level as a real `h1`-`h6` number, with `minHeadingLevel`
1067
+ * (see `BuildRichTextTreeOptions`) applied as a floor.
1068
+ *
1069
+ * Both arguments are `unknown`-ish input: `value` comes from a document's own
1070
+ * `attrs`, and the floor from a caller's prop, so neither may be trusted to be
1071
+ * an integer in range. Each is normalised on its own before `Math.max` sees
1072
+ * them — a `minHeadingLevel` of `2.5`, `0`, `9` or `'3'` must never turn into
1073
+ * an `<h2.5>`/`<h0>`/`<h9>` — and the result is capped at 6 last, so a floor of
1074
+ * 6 against a level of 6 still reads `h6` rather than overflowing.
1075
+ */
1076
+ function clampHeadingLevel(value, minimum) {
1077
+ return Math.min(6, Math.max(1, typeof value === "number" && Number.isInteger(value) ? value : 1, typeof minimum === "number" && Number.isInteger(minimum) ? minimum : 1));
1078
+ }
1079
+ function colorStyle(property, value) {
1080
+ if (typeof value !== "string") return null;
1081
+ if (!HEX_COLOR.test(value) && !NAMED_COLOR.test(value)) return null;
1082
+ return `${property}: ${value}`;
1083
+ }
1084
+ function applyMarks(text, marks, options) {
1085
+ return marks.reduce((child, mark) => {
1086
+ const wrap = (tag, attrs = {}) => ({
1087
+ tag,
1088
+ attrs,
1089
+ children: [child]
1090
+ });
1091
+ switch (mark.type) {
1092
+ case "bold": return wrap("strong");
1093
+ case "italic": return wrap("em");
1094
+ case "strike": return wrap("s");
1095
+ case "underline": return wrap("u");
1096
+ case "code": return wrap("code");
1097
+ case "highlight": {
1098
+ const style = colorStyle("background-color", mark.attrs?.color);
1099
+ return wrap("mark", style !== null ? { style } : {});
1100
+ }
1101
+ case "textStyle": {
1102
+ const style = colorStyle("color", mark.attrs?.color);
1103
+ return wrap("span", style !== null ? { style } : {});
1104
+ }
1105
+ case "link": return buildLinkMark(mark, options, child);
1106
+ case "fileAttachment": return buildFileAttachmentMark(mark, options, child);
1107
+ default: return child;
1108
+ }
1109
+ }, text);
1110
+ }
1111
+ function buildLinkMark(mark, options, child) {
1112
+ const href = options.safeHref(mark.attrs?.href);
1113
+ if (href === null) return child;
1114
+ const attrs = { href };
1115
+ if (mark.attrs?.target === "_blank") {
1116
+ attrs.target = "_blank";
1117
+ attrs.rel = "noopener noreferrer";
1118
+ }
1119
+ return {
1120
+ tag: "a",
1121
+ attrs,
1122
+ children: [child]
1123
+ };
1124
+ }
1125
+ function buildFileAttachmentMark(mark, options, child) {
1126
+ const href = options.safeHref(mark.attrs?.href);
1127
+ if (href === null) return child;
1128
+ const attrs = {
1129
+ href,
1130
+ "data-file-attachment": ""
1131
+ };
1132
+ if (typeof mark.attrs?.assetId === "string") attrs["data-asset-id"] = mark.attrs.assetId;
1133
+ if (typeof mark.attrs?.filename === "string") attrs.download = mark.attrs.filename;
1134
+ return {
1135
+ tag: "a",
1136
+ attrs,
1137
+ children: [child]
1138
+ };
1139
+ }
1140
+ //#endregion
1141
+ 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, RESERVED_THEME_IDS, RICH_TEXT_LEAF_TYPES, RICH_TEXT_MARK_ELEMENTS, RICH_TEXT_PAD_ATTR, RICH_TEXT_TOOLBAR_CONTROLS, ReusableComponentSnapshotCache, THEME_ID_PATTERN, activeLayoutBreakpoint, applyDesignTokenOverrides, blockApiIdOf, 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, getRegisteredThemeId, hiddenLayoutBreakpoints, imageFramingAttrs, imageFramingStyle, isBlockFieldLocalized, layoutIdentityOf, layoutNodeClass, layoutRenderNodeId, matchDynamicRoutePattern, normalizeColorSelection, normalizeImageFraming, normalizeLayoutDocument, normalizeSiteDesignTokenOverrides, normalizeThemeDesignTokens, parseDynamicRoutePattern, parseImageFramingValueAttr, projectEntryDataLocale, registerBlockFields, registerThemeId, resolveColorSelection, resolveDesignTokenCatalog, resolveDomPoint, resolveDomPosition, resolveLayoutBreakpoints, resolveLayoutDocument, resolvePagePath, resolveRoute, responsiveValue, restampRichTextPositions, richTextMarkNameOf, richTextNodeSize, richTextText, safeHref, stripStega, themeSchemaApiId, unscaledFrameRect, validateLayoutDocument };