@eldrajs/theme-core 0.1.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,16 @@ Release-please writes the generated notes from commit messages and does not repl
5
5
 
6
6
  ## Unreleased
7
7
 
8
+ - New `themeId` helpers, framework-free: `blockApiIdOf(schemaApiId, themeId)` (the wire spelling
9
+ `<themeId>:<apiId>` to the bare block id, stripping only the given theme's own prefix, so
10
+ `catalog:product` and another theme's `starter:hero` pass through) and
11
+ `themeSchemaApiId(blockApiId, themeId)` (the reverse, idempotent), plus `THEME_ID_PATTERN`,
12
+ `RESERVED_THEME_IDS`, `registerThemeId`/`getRegisteredThemeId`. **Breaking:** `registerBlockFields(fields,
13
+ themeId)` now requires the theme's own id and registers it, so `isBlockFieldLocalized`,
14
+ `isBlockFieldSelect` (and the select unwrap and stega skip that use it) and a template block's
15
+ entry/placement match resolve a block entry whose `schemaApiId` is `<themeId>:<apiId>`. Bare ids
16
+ keep working. The bridge's `theme:ready` reports `manifestVersion: 2`.
17
+
8
18
  - New subpath, `@eldrajs/theme-core/i18n`, framework-free: `flattenMessages`/`unflattenMessages`
9
19
  (nested vue-i18n JSON ↔ the manifest's own flat dotted keys), `mergeMessageCatalogues(themeDefaults,
10
20
  platform)` (the platform's theme-message overrides win per key; a locale the theme never shipped
@@ -250,7 +250,7 @@ function createThemeBridge(opts) {
250
250
  }
251
251
  function sendReady() {
252
252
  deliver(makeEnvelope("theme:ready", {
253
- manifestVersion: 1,
253
+ manifestVersion: 2,
254
254
  themeVersion: readMeta("eldra-theme-version"),
255
255
  sdkVersion: readMeta("eldra-sdk-version"),
256
256
  path: window.location.pathname,
package/dist/bridge.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as BRIDGE_PROTOCOL, c as KNOWN_MESSAGE_TYPES, i as parseEnvelope, l as RICH_TEXT_COMMAND_NAMES, n as createEditorBridge, o as BRIDGE_VERSION, r as makeEnvelope, s as EDITOR_CAPABILITIES, t as createThemeBridge, u as THEME_CAPABILITIES } from "./bridge-DfNINXLL.js";
1
+ import { a as BRIDGE_PROTOCOL, c as KNOWN_MESSAGE_TYPES, i as parseEnvelope, l as RICH_TEXT_COMMAND_NAMES, n as createEditorBridge, o as BRIDGE_VERSION, r as makeEnvelope, s as EDITOR_CAPABILITIES, t as createThemeBridge, u as THEME_CAPABILITIES } from "./bridge-CLi2P6Wh.js";
2
2
  export { BRIDGE_PROTOCOL, BRIDGE_VERSION, EDITOR_CAPABILITIES, KNOWN_MESSAGE_TYPES, RICH_TEXT_COMMAND_NAMES, THEME_CAPABILITIES, createEditorBridge, createThemeBridge, makeEnvelope, parseEnvelope };
package/dist/index.d.ts CHANGED
@@ -388,8 +388,12 @@ type BlockFieldsMap = Record<string, BlockFieldDefinition[]>;
388
388
  * equivalent entry for another adapter) imports `virtual:eldra/block-fields`
389
389
  * and calls this once at startup with the resolved map; call it again (e.g.
390
390
  * on the plugin's HMR rescan) to replace the registered map.
391
+ *
392
+ * `themeId` is the theme's own id (the manifest's `theme.id`). Core spells a
393
+ * block entry's schema `<themeId>:<apiId>` on the wire while this map is keyed
394
+ * by the bare `apiId`, so the lookups below strip that one prefix.
391
395
  */
392
- export declare function registerBlockFields(fields: BlockFieldsMap): void;
396
+ export declare function registerBlockFields(fields: BlockFieldsMap, themeId: string): void;
393
397
  /**
394
398
  * Whether the manifest marks this block field `localized`. A rich-text
395
399
  * renderer uses it to default an omitted `locale` to the preview's active
@@ -404,4 +408,42 @@ export declare function registerBlockFields(fields: BlockFieldsMap): void;
404
408
  */
405
409
  export declare function isBlockFieldLocalized(apiId: string | undefined, fieldId: string): boolean;
406
410
  //#endregion
411
+ //#region src/themeId.d.ts
412
+ /**
413
+ * Theme ownership of block schemas, as the kit sees it.
414
+ *
415
+ * Core stores a theme's block schemas under `<themeId>:<blockApiId>`
416
+ * (`soley:hero`), so two themes in one organisation never clash and a
417
+ * merchant's own schemas can never shadow a theme's. Everything the theme
418
+ * itself authors stays **bare**: `block.json`, the manifest's block ids, a
419
+ * layout node's `apiId`, a slot allowlist, `data-eldra-schema` and the
420
+ * overlay's `theme:block-clicked`. Only the wire spelling of an entry's
421
+ * `schemaApiId` carries the prefix, so these two helpers are the whole
422
+ * boundary.
423
+ *
424
+ * The prefix stripped is the one of the theme *this build is for* (injected at
425
+ * build from the manifest's `theme.id`), never "any prefix": `catalog:product`
426
+ * and another theme's `starter:hero` are not this theme's blocks and pass
427
+ * through untouched.
428
+ */
429
+ /** The grammar of a theme id (and of a block apiId): lower-case, 2 to 49 characters. */
430
+ export declare const THEME_ID_PATTERN: RegExp;
431
+ /**
432
+ * Ids a theme may not use. Core reserves `catalog:` for catalog route targets,
433
+ * so a theme called `catalog` would claim that namespace for its block schemas.
434
+ */
435
+ export declare const RESERVED_THEME_IDS: readonly string[];
436
+ /** Wire to bare: `soley:hero` to `hero` for theme `soley`; anything else is returned as given. */
437
+ export declare function blockApiIdOf(schemaApiId: string, themeId: string | undefined | null): string;
438
+ /**
439
+ * Bare to wire: `hero` to `soley:hero` for theme `soley`. A value that already
440
+ * carries a colon (the wire spelling, or `catalog:product`) is returned as
441
+ * given, so the call is idempotent.
442
+ */
443
+ export declare function themeSchemaApiId(blockApiId: string, themeId: string | undefined | null): string;
444
+ /** Registers the theme's own id for the lookups inside theme-core. See `registerBlockFields`. */
445
+ export declare function registerThemeId(themeId: string | undefined): void;
446
+ /** The registered theme id, if the app registered one. */
447
+ export declare function getRegisteredThemeId(): string | undefined;
448
+ //#endregion
407
449
  export { type BeforeInputClassification, type BlockFieldDefinition, type BlockFieldsMap, BlockSlotDefinition, type BuildRichTextTreeOptions, CatalogDoc, CatalogList, CatalogQuery, ColorLiteral, ColorSelection, ContainerOverride, ContainerPreset, CssLength, CssTokenLength, DEFAULT_IMAGE_FRAMING, DEFAULT_LAYOUT_BREAKPOINTS, DesignTokenCatalog, DesignTokenId, DesignTokenValidationCode, DesignTokenValidationError, DynamicRouteResolution, EDIT_MODE_HIDDEN_OPACITY, EldraCatalogReader, EldraClient, EldraClientError, EldraClientOptions, EldraRetryOptions, EntryDoc, EntryList, EntryQuery, FrameRect, IMAGE_FRAMING_MAX_ZOOM, IMAGE_FRAMING_MIN_ZOOM, ImageFraming, LAYOUT_BREAKPOINTS, LayoutBlockNode, LayoutBreakpoint, LayoutBreakpoints, LayoutContainerNode, LayoutDocument, LayoutNode, LayoutRenderBlockNode, LayoutRenderModel, LayoutRenderNode, LayoutStyle, LayoutValidationCode, LayoutValidationError, LayoutValidationIssue, MAX_DYNAMIC_ROUTE_PATTERN_BYTES, type NegotiatedEditorCapabilities, NormalizedLayoutResult, type OverlayRuntime, type OverlayRuntimeOptions, PREVIEW_ROUTER_MESSAGE_TYPES, PageLayoutDocument, PageLayoutNode, type PageLike, PageMeta, ParsedDynamicRoutePattern, type PreviewMessageRouter, type PreviewRouterMessageType, ResolveEntryListBody, ResolvedLayoutDocument, ResolvedLayoutNode, ResolvedLayoutStyle, Responsive, ResponsiveTokenValue, type ReusableComponentBinding, type ReusableComponentPlacement, type ReusableComponentProjection, type ReusableComponentResolver, type ReusableComponentRevision, ReusableComponentSnapshotCache, ReusableLayoutOptions, ReusableLayoutRenderModel, ReusableLayoutRenderNode, ReusablePerspective, type ReusableRenderIdentity, type RichTextDomPoint, type RichTextFieldIdentity, type RichTextMark, type RichTextNode, type RichTextPositionNode, type RichTextPositions, type RichTextRenderChild, type RichTextRenderNode, type RichTextRenderStateChange, type RichTextSelectionContext, type RichTextToolbarControl, RouteTemplateLike, SiteDesignTokenOverrides, SizingLength, SlotValidationContext, Spacing, type StegaMeta, TemplateBlockDefinition, TemplateBlockFieldDefinition, TemplateBlockNode, TemplateLayoutContext, TemplateLayoutDocument, TemplateLayoutNode, TemplateLayoutRenderModel, TemplateLayoutRenderNode, ThemeColorToken, ThemeDesignTokens, WidthLength, activeLayoutBreakpoint, applyDesignTokenOverrides, buildDynamicRoutePath, buildTemplateBlockRenames, catalogRouteTarget, clampFocal, clampImageFraming, classifyBeforeInput, createLayoutRenderModel, createOverlayRuntime, createPreviewMessageRouter, createProjectionResolver, createReusableLayoutRenderModel, createTemplateLayoutRenderModel, decodeStega, designTokenRevisionHash, encodeStega, focalBand, framingDrag, framingZoom, generateDesignTokenCss, generateLayoutCss, generateTailwindThemeCss, hiddenLayoutBreakpoints, imageFramingAttrs, imageFramingStyle, layoutNodeClass, layoutRenderNodeId, matchDynamicRoutePattern, normalizeColorSelection, normalizeImageFraming, normalizeLayoutDocument, normalizeSiteDesignTokenOverrides, normalizeThemeDesignTokens, parseDynamicRoutePattern, parseImageFramingValueAttr, resolveColorSelection, resolveDesignTokenCatalog, resolveLayoutBreakpoints, resolveLayoutDocument, resolvePagePath, resolveRoute, responsiveValue, stripStega, unscaledFrameRect, validateLayoutDocument };
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;
@@ -1133,4 +1138,4 @@ function buildFileAttachmentMark(mark, options, child) {
1133
1138
  };
1134
1139
  }
1135
1140
  //#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 };
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 };
@@ -1,5 +1,5 @@
1
1
  import { decodeStega, stripStega } from "./stega.js";
2
- import { l as RICH_TEXT_COMMAND_NAMES } from "./bridge-DfNINXLL.js";
2
+ import { l as RICH_TEXT_COMMAND_NAMES } from "./bridge-CLi2P6Wh.js";
3
3
  import { framingDrag, framingZoom, imageFramingStyle, parseImageFramingValueAttr, unscaledFrameRect } from "./image-framing.js";
4
4
  import { activeLayoutBreakpoint } from "./layout.js";
5
5
  //#region src/layoutIdentity.ts
package/dist/overlay.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import "./stega.js";
2
2
  import "./image-framing.js";
3
- import { n as createOverlayRuntime, t as classifyBeforeInput } from "./overlay-BvkEOiMB.js";
3
+ import { n as createOverlayRuntime, t as classifyBeforeInput } from "./overlay-C8-F1jzU.js";
4
4
  import "./layout.js";
5
5
  import { PREVIEW_ROUTER_MESSAGE_TYPES, createPreviewMessageRouter } from "./preview-router.js";
6
6
  export { PREVIEW_ROUTER_MESSAGE_TYPES, classifyBeforeInput, createOverlayRuntime, createPreviewMessageRouter };
@@ -1,328 +1,3 @@
1
- import { LayoutValidationError, generateLayoutCss, layoutNodeClass, normalizeLayoutDocument } from "./layout.js";
2
- import { a as expandReusablePlacements, i as decorateReusableIdentity } from "./reusableExpansion-Bqm83nCJ.js";
3
- //#region src/templateLayout.ts
4
- /**
5
- * Flattens a block's `migrations` array (each step's `renames: [{ from, to
6
- * }]`) into one `from -> to` map, applied in ascending `version` order with
7
- * chains resolved: a step renaming `a -> b` followed by one renaming `b -> c`
8
- * yields `{ a: 'c', b: 'c' }`, so every historical name for a field resolves
9
- * straight to its current one. `migrations` is untrusted input (a manifest
10
- * read at runtime) — any entry that is not a well-formed `{ version: number,
11
- * renames: Array<{ from: string, to: string }> }` step is ignored rather than
12
- * thrown on, and malformed rename pairs within an otherwise valid step are
13
- * skipped the same way.
14
- */
15
- function buildTemplateBlockRenames(migrations) {
16
- const renames = {};
17
- if (!Array.isArray(migrations)) return renames;
18
- const steps = migrations.filter((step) => isRecord(step) && typeof step.version === "number" && Array.isArray(step.renames)).sort((a, b) => a.version - b.version);
19
- for (const step of steps) for (const entry of step.renames) {
20
- if (!isRecord(entry)) continue;
21
- const { from, to } = entry;
22
- if (typeof from !== "string" || typeof to !== "string" || from === "" || to === "") continue;
23
- for (const key of Object.keys(renames)) if (renames[key] === from) renames[key] = to;
24
- renames[from] = to;
25
- }
26
- return renames;
27
- }
28
- const API_ID = /^[a-z][a-z0-9-]{1,48}$/;
29
- const FIELD_ID = /^[a-z][a-zA-Z0-9]{0,48}$/;
30
- const LIST_INDEX = /^(?:0|[1-9][0-9]*)$/;
31
- const TARGET_FIELD_PATH = /^[a-z][a-zA-Z0-9]{0,48}(?:\.(?:[a-z][a-zA-Z0-9]{0,48}|0|[1-9][0-9]*))*$/;
32
- const MAX_BINDINGS = 100;
33
- const MAX_TEMPLATE_BYTES = 2048;
34
- const MAX_TEMPLATE_TOKENS = 32;
35
- const TEMPLATE_TOKEN = /\{\{\s*([a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*)*)\s*\}\}/g;
36
- function createTemplateLayoutRenderModel(value, context) {
37
- if (!isRecord(value) || value.version !== 1) fail("/version", "INVALID_VALUE");
38
- const placements = /* @__PURE__ */ new Map();
39
- let sequence = 0;
40
- const transformed = transformNode(value.root, "/root", context, placements, () => {
41
- sequence += 1;
42
- return `00000000-0000-4000-8000-${String(sequence).padStart(12, "0")}`;
43
- });
44
- if (transformed.type === "block") fail("/root/type", "INVALID_VALUE");
45
- const expansion = expandReusablePlacements({
46
- root: transformed,
47
- path: "/root",
48
- projection: context.reusableComponentProjection ?? {
49
- bindings: [],
50
- revisions: []
51
- },
52
- allowReusable: true,
53
- ...context.allowedContainerIds === void 0 ? {} : { allowedContainerIds: context.allowedContainerIds }
54
- });
55
- const expanded = expansion.root;
56
- const normalized = normalizeLayoutDocument({
57
- version: 1,
58
- root: expanded
59
- }, new Set(collectEntryIds(expanded)), context.allowedContainerIds);
60
- const document = restoreTemplateDocument(normalized.document.root, placements);
61
- return {
62
- document: {
63
- version: 1,
64
- root: document
65
- },
66
- root: decorateReusableIdentity(renderTemplateNode(document, placements), expansion.identities),
67
- css: generateLayoutCss(normalized.document, void 0, void 0, context.breakpoints)
68
- };
69
- }
70
- function transformNode(value, path, context, placements, nextEntryId) {
71
- if (!isRecord(value)) fail(path, "INVALID_TYPE");
72
- if (value.type === "template-block") {
73
- exactKeys(value, [
74
- "id",
75
- "type",
76
- "apiId",
77
- "entryId",
78
- "bindings",
79
- "templates"
80
- ], path);
81
- if (typeof value.id !== "string") fail(`${path}/id`, "INVALID_TYPE");
82
- if (typeof value.apiId !== "string" || !API_ID.test(value.apiId)) fail(`${path}/apiId`, "INVALID_VALUE");
83
- const definition = context.blockCatalog[value.apiId];
84
- if (definition === void 0) fail(`${path}/apiId`, "BLOCK_NOT_FOUND");
85
- const declared = new Set(definition.fields.map((field) => field.fieldId));
86
- const renames = definition.renames ?? {};
87
- const bindings = normalizeBindings(resolveRenamedKeys(value.bindings, path, "bindings", declared, renames), path, definition, context.entry);
88
- const templates = normalizeTemplates(resolveRenamedKeys(value.templates, path, "templates", declared, renames), path, definition, context.entry, bindings);
89
- const entryId = value.entryId;
90
- if (entryId !== void 0 && typeof entryId !== "string") fail(`${path}/entryId`, "INVALID_TYPE");
91
- const baseEntry = entryId === void 0 ? void 0 : context.blockEntries?.find((candidate) => candidate.id === entryId);
92
- if (entryId !== void 0 && baseEntry === void 0) fail(`${path}/entryId`, "BLOCK_NOT_FOUND");
93
- const schemaApiId = baseEntry?.schemaApiId;
94
- if (typeof schemaApiId === "string" && schemaApiId !== value.apiId) fail(`${path}/entryId`, "BLOCK_NOT_FOUND");
95
- const data = baseEntry === void 0 ? {} : cloneContentRecord(baseEntry.data);
96
- for (const field of definition.fields) if (baseEntry === void 0 && Object.hasOwn(field, "default")) data[field.fieldId] = cloneContent(field.default);
97
- for (const [targetPath, binding] of Object.entries(bindings)) {
98
- const resolved = readBindingPath(context.entry.data, binding);
99
- const issuePath = `${path}/bindings/${pointerToken(targetPath)}`;
100
- if (!resolved.found || !writeTargetPath(data, targetPath, resolved.value)) fail(issuePath, "INVALID_VALUE");
101
- }
102
- for (const [targetPath, template] of Object.entries(templates)) {
103
- const issuePath = `${path}/templates/${pointerToken(targetPath)}`;
104
- if (!writeTargetPath(data, targetPath, renderTextTemplate(template, context.entry, issuePath))) fail(issuePath, "INVALID_VALUE");
105
- }
106
- placements.set(value.id, {
107
- apiId: value.apiId,
108
- ...entryId === void 0 ? {} : { entryId },
109
- bindings,
110
- templates,
111
- entry: baseEntry === void 0 ? {
112
- ...context.entry,
113
- schemaApiId: value.apiId,
114
- data
115
- } : {
116
- ...baseEntry,
117
- schemaApiId: value.apiId,
118
- data
119
- }
120
- });
121
- return {
122
- id: value.id,
123
- type: "block",
124
- entryId: nextEntryId()
125
- };
126
- }
127
- if (value.type === "reusable") {
128
- if (path === "/root") fail(`${path}/type`, "INVALID_VALUE");
129
- exactKeys(value, [
130
- "id",
131
- "type",
132
- "componentId"
133
- ], path);
134
- return value;
135
- }
136
- if (value.type !== "flex" && value.type !== "grid") return value;
137
- if (!Array.isArray(value.children)) return value;
138
- return {
139
- ...value,
140
- children: value.children.map((child, index) => transformNode(child, `${path}/children/${index}`, context, placements, nextEntryId))
141
- };
142
- }
143
- function resolveRenamedKeys(value, path, container, declared, renames) {
144
- if (!isRecord(value)) return value;
145
- const rewritten = {};
146
- const sourcesByTarget = /* @__PURE__ */ new Map();
147
- for (const key of Object.keys(value)) {
148
- const dot = key.indexOf(".");
149
- const head = dot === -1 ? key : key.slice(0, dot);
150
- const rest = dot === -1 ? "" : key.slice(dot);
151
- const renamed = !declared.has(head) && Object.hasOwn(renames, head) ? renames[head] : void 0;
152
- const newKey = renamed === void 0 ? key : renamed + rest;
153
- rewritten[newKey] = value[key];
154
- const sources = sourcesByTarget.get(newKey);
155
- if (sources === void 0) sourcesByTarget.set(newKey, [key]);
156
- else sources.push(key);
157
- }
158
- for (const [newKey, sources] of sourcesByTarget) if (sources.length > 1) fail(`${path}/${container}/${pointerToken(newKey)}`, "INVALID_VALUE");
159
- return rewritten;
160
- }
161
- function normalizeTemplates(value, path, definition, entry, bindings) {
162
- if (value === void 0) return {};
163
- if (!isRecord(value)) fail(`${path}/templates`, "INVALID_TYPE");
164
- const keys = Object.keys(value);
165
- if (keys.length > MAX_BINDINGS || keys.length + Object.keys(bindings).length > MAX_BINDINGS) fail(`${path}/templates`, "LIMIT_EXCEEDED");
166
- const declared = new Set(definition.fields.map((field) => field.fieldId));
167
- const templates = {};
168
- for (const key of keys.sort()) {
169
- const template = value[key];
170
- const issuePath = `${path}/templates/${pointerToken(key)}`;
171
- if (!validTargetPath(key, declared) || Object.hasOwn(bindings, key)) fail(issuePath, "INVALID_VALUE");
172
- if (typeof template !== "string") fail(issuePath, "INVALID_TYPE");
173
- const paths = templatePaths(template);
174
- if (paths === null || paths.some((binding) => !readBindingPath(entry.data, binding).found)) fail(issuePath, "INVALID_VALUE");
175
- templates[key] = template;
176
- }
177
- return templates;
178
- }
179
- function templatePaths(value) {
180
- if (value === "" || new TextEncoder().encode(value).byteLength > MAX_TEMPLATE_BYTES) return null;
181
- const paths = [...value.matchAll(TEMPLATE_TOKEN)].map((match) => match[1]);
182
- if (paths.length === 0 || paths.length > MAX_TEMPLATE_TOKENS) return null;
183
- const remainder = value.replace(TEMPLATE_TOKEN, "");
184
- return remainder.includes("{{") || remainder.includes("}}") ? null : paths;
185
- }
186
- function renderTextTemplate(value, entry, path) {
187
- return value.replace(TEMPLATE_TOKEN, (_token, binding) => {
188
- const resolved = readBindingPath(entry.data, binding);
189
- if (!resolved.found || typeof resolved.value !== "string") fail(path, "INVALID_VALUE");
190
- return resolved.value;
191
- });
192
- }
193
- function normalizeBindings(value, path, definition, entry) {
194
- if (value === void 0) return {};
195
- if (!isRecord(value)) fail(`${path}/bindings`, "INVALID_TYPE");
196
- const keys = Object.keys(value);
197
- if (keys.length > MAX_BINDINGS) fail(`${path}/bindings`, "LIMIT_EXCEEDED");
198
- const declared = new Set(definition.fields.map((field) => field.fieldId));
199
- const bindings = {};
200
- for (const key of keys.sort()) {
201
- const binding = value[key];
202
- if (!validTargetPath(key, declared)) fail(`${path}/bindings/${pointerToken(key)}`, "INVALID_VALUE");
203
- if (typeof binding !== "string" || !validBindingPath(binding)) fail(`${path}/bindings/${pointerToken(key)}`, typeof binding === "string" ? "INVALID_VALUE" : "INVALID_TYPE");
204
- if (!readBindingPath(entry.data, binding).found) fail(`${path}/bindings/${pointerToken(key)}`, "INVALID_VALUE");
205
- bindings[key] = binding;
206
- }
207
- return bindings;
208
- }
209
- function restoreTemplateDocument(node, placements) {
210
- const restore = (current) => {
211
- if (current.type === "block") {
212
- const placement = placements.get(current.id);
213
- if (placement === void 0) return current;
214
- return {
215
- id: current.id,
216
- type: "template-block",
217
- apiId: placement.apiId,
218
- ...placement.entryId === void 0 ? {} : { entryId: placement.entryId },
219
- ...Object.keys(placement.bindings).length === 0 ? {} : { bindings: placement.bindings },
220
- ...Object.keys(placement.templates).length === 0 ? {} : { templates: placement.templates }
221
- };
222
- }
223
- return {
224
- ...current,
225
- children: current.children.map(restore)
226
- };
227
- };
228
- return restore(node);
229
- }
230
- function renderTemplateNode(node, placements) {
231
- if (node.type === "template-block") {
232
- const placement = placements.get(node.id);
233
- if (placement === void 0) fail("", "INVALID_VALUE");
234
- return {
235
- ...node,
236
- entry: placement.entry,
237
- className: layoutNodeClass(node.id)
238
- };
239
- }
240
- if (node.type === "flex" || node.type === "grid") return {
241
- ...node,
242
- className: layoutNodeClass(node.id),
243
- children: node.children.map((child) => renderTemplateNode(child, placements))
244
- };
245
- return {
246
- ...node,
247
- className: layoutNodeClass(node.id)
248
- };
249
- }
250
- function collectEntryIds(node) {
251
- if (node.type === "block") return [node.entryId];
252
- return node.children.flatMap(collectEntryIds);
253
- }
254
- function readBindingPath(root, path) {
255
- let current = root;
256
- for (const segment of path.split(".")) {
257
- if (LIST_INDEX.test(segment)) {
258
- if (!Array.isArray(current)) return { found: false };
259
- const index = Number(segment);
260
- if (index >= current.length) return { found: false };
261
- current = current[index];
262
- continue;
263
- }
264
- if (!isRecord(current)) return { found: false };
265
- if (!Object.hasOwn(current, segment) && isRecord(current.data)) current = current.data;
266
- if (!isRecord(current) || !Object.hasOwn(current, segment)) return { found: false };
267
- current = current[segment];
268
- }
269
- return {
270
- found: true,
271
- value: current
272
- };
273
- }
274
- function validBindingPath(path) {
275
- return path !== "" && new TextEncoder().encode(path).byteLength <= 255 && path.split(".").every((segment) => FIELD_ID.test(segment) || LIST_INDEX.test(segment));
276
- }
277
- function validTargetPath(path, declaredRoots) {
278
- return TARGET_FIELD_PATH.test(path) && declaredRoots.has(path.split(".")[0]);
279
- }
280
- function writeTargetPath(root, path, value) {
281
- const segments = path.split(".");
282
- let current = root;
283
- for (let index = 0; index < segments.length - 1; index += 1) {
284
- const segment = segments[index];
285
- if (Array.isArray(current)) {
286
- const itemIndex = Number(segment);
287
- if (!Number.isSafeInteger(itemIndex) || itemIndex < 0 || itemIndex >= current.length) return false;
288
- current = current[itemIndex];
289
- continue;
290
- }
291
- if (!isRecord(current) || !Object.hasOwn(current, segment)) return false;
292
- current = current[segment];
293
- }
294
- const finalSegment = segments.at(-1);
295
- if (Array.isArray(current)) {
296
- const itemIndex = Number(finalSegment);
297
- if (!Number.isSafeInteger(itemIndex) || itemIndex < 0 || itemIndex >= current.length) return false;
298
- current[itemIndex] = value;
299
- return true;
300
- }
301
- if (!isRecord(current) || !FIELD_ID.test(finalSegment)) return false;
302
- current[finalSegment] = value;
303
- return true;
304
- }
305
- function exactKeys(value, allowed, path) {
306
- for (const key of Object.keys(value)) if (!allowed.includes(key)) fail(`${path}/${pointerToken(key)}`, "UNKNOWN_KEY");
307
- }
308
- function cloneContent(value) {
309
- if (Array.isArray(value)) return value.map(cloneContent);
310
- return isRecord(value) ? cloneContentRecord(value) : value;
311
- }
312
- function cloneContentRecord(value) {
313
- return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, cloneContent(child)]));
314
- }
315
- function isRecord(value) {
316
- return typeof value === "object" && value !== null && !Array.isArray(value);
317
- }
318
- function pointerToken(value) {
319
- return value.replaceAll("~", "~0").replaceAll("/", "~1");
320
- }
321
- function fail(path, code) {
322
- throw new LayoutValidationError({
323
- path,
324
- code
325
- });
326
- }
327
- //#endregion
1
+ import { n as createTemplateLayoutRenderModel, t as buildTemplateBlockRenames } from "./templateLayout-CpZb6EEg.js";
2
+ import "./layout.js";
328
3
  export { buildTemplateBlockRenames, createTemplateLayoutRenderModel };
@@ -0,0 +1,382 @@
1
+ import { LayoutValidationError, generateLayoutCss, layoutNodeClass, normalizeLayoutDocument } from "./layout.js";
2
+ import { a as expandReusablePlacements, i as decorateReusableIdentity } from "./reusableExpansion-Bqm83nCJ.js";
3
+ //#region src/themeId.ts
4
+ /**
5
+ * Theme ownership of block schemas, as the kit sees it.
6
+ *
7
+ * Core stores a theme's block schemas under `<themeId>:<blockApiId>`
8
+ * (`soley:hero`), so two themes in one organisation never clash and a
9
+ * merchant's own schemas can never shadow a theme's. Everything the theme
10
+ * itself authors stays **bare**: `block.json`, the manifest's block ids, a
11
+ * layout node's `apiId`, a slot allowlist, `data-eldra-schema` and the
12
+ * overlay's `theme:block-clicked`. Only the wire spelling of an entry's
13
+ * `schemaApiId` carries the prefix, so these two helpers are the whole
14
+ * boundary.
15
+ *
16
+ * The prefix stripped is the one of the theme *this build is for* (injected at
17
+ * build from the manifest's `theme.id`), never "any prefix": `catalog:product`
18
+ * and another theme's `starter:hero` are not this theme's blocks and pass
19
+ * through untouched.
20
+ */
21
+ /** The grammar of a theme id (and of a block apiId): lower-case, 2 to 49 characters. */
22
+ const THEME_ID_PATTERN = /^[a-z][a-z0-9-]{1,48}$/;
23
+ /**
24
+ * Ids a theme may not use. Core reserves `catalog:` for catalog route targets,
25
+ * so a theme called `catalog` would claim that namespace for its block schemas.
26
+ */
27
+ const RESERVED_THEME_IDS = ["catalog"];
28
+ /** Wire to bare: `soley:hero` to `hero` for theme `soley`; anything else is returned as given. */
29
+ function blockApiIdOf(schemaApiId, themeId) {
30
+ if (typeof themeId !== "string" || themeId === "") return schemaApiId;
31
+ const prefix = `${themeId}:`;
32
+ return schemaApiId.startsWith(prefix) && schemaApiId.length > prefix.length ? schemaApiId.slice(prefix.length) : schemaApiId;
33
+ }
34
+ /**
35
+ * Bare to wire: `hero` to `soley:hero` for theme `soley`. A value that already
36
+ * carries a colon (the wire spelling, or `catalog:product`) is returned as
37
+ * given, so the call is idempotent.
38
+ */
39
+ function themeSchemaApiId(blockApiId, themeId) {
40
+ if (typeof themeId !== "string" || themeId === "" || blockApiId.includes(":")) return blockApiId;
41
+ return `${themeId}:${blockApiId}`;
42
+ }
43
+ let registeredThemeId;
44
+ /** Registers the theme's own id for the lookups inside theme-core. See `registerBlockFields`. */
45
+ function registerThemeId(themeId) {
46
+ registeredThemeId = themeId;
47
+ }
48
+ /** The registered theme id, if the app registered one. */
49
+ function getRegisteredThemeId() {
50
+ return registeredThemeId;
51
+ }
52
+ /** `blockApiIdOf` for the registered theme id; a no-op before one is registered. */
53
+ function registeredBlockApiId(schemaApiId) {
54
+ return blockApiIdOf(schemaApiId, registeredThemeId);
55
+ }
56
+ //#endregion
57
+ //#region src/templateLayout.ts
58
+ /**
59
+ * Flattens a block's `migrations` array (each step's `renames: [{ from, to
60
+ * }]`) into one `from -> to` map, applied in ascending `version` order with
61
+ * chains resolved: a step renaming `a -> b` followed by one renaming `b -> c`
62
+ * yields `{ a: 'c', b: 'c' }`, so every historical name for a field resolves
63
+ * straight to its current one. `migrations` is untrusted input (a manifest
64
+ * read at runtime) — any entry that is not a well-formed `{ version: number,
65
+ * renames: Array<{ from: string, to: string }> }` step is ignored rather than
66
+ * thrown on, and malformed rename pairs within an otherwise valid step are
67
+ * skipped the same way.
68
+ */
69
+ function buildTemplateBlockRenames(migrations) {
70
+ const renames = {};
71
+ if (!Array.isArray(migrations)) return renames;
72
+ const steps = migrations.filter((step) => isRecord(step) && typeof step.version === "number" && Array.isArray(step.renames)).sort((a, b) => a.version - b.version);
73
+ for (const step of steps) for (const entry of step.renames) {
74
+ if (!isRecord(entry)) continue;
75
+ const { from, to } = entry;
76
+ if (typeof from !== "string" || typeof to !== "string" || from === "" || to === "") continue;
77
+ for (const key of Object.keys(renames)) if (renames[key] === from) renames[key] = to;
78
+ renames[from] = to;
79
+ }
80
+ return renames;
81
+ }
82
+ const API_ID = /^[a-z][a-z0-9-]{1,48}$/;
83
+ const FIELD_ID = /^[a-z][a-zA-Z0-9]{0,48}$/;
84
+ const LIST_INDEX = /^(?:0|[1-9][0-9]*)$/;
85
+ const TARGET_FIELD_PATH = /^[a-z][a-zA-Z0-9]{0,48}(?:\.(?:[a-z][a-zA-Z0-9]{0,48}|0|[1-9][0-9]*))*$/;
86
+ const MAX_BINDINGS = 100;
87
+ const MAX_TEMPLATE_BYTES = 2048;
88
+ const MAX_TEMPLATE_TOKENS = 32;
89
+ const TEMPLATE_TOKEN = /\{\{\s*([a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*)*)\s*\}\}/g;
90
+ function createTemplateLayoutRenderModel(value, context) {
91
+ if (!isRecord(value) || value.version !== 1) fail("/version", "INVALID_VALUE");
92
+ const placements = /* @__PURE__ */ new Map();
93
+ let sequence = 0;
94
+ const transformed = transformNode(value.root, "/root", context, placements, () => {
95
+ sequence += 1;
96
+ return `00000000-0000-4000-8000-${String(sequence).padStart(12, "0")}`;
97
+ });
98
+ if (transformed.type === "block") fail("/root/type", "INVALID_VALUE");
99
+ const expansion = expandReusablePlacements({
100
+ root: transformed,
101
+ path: "/root",
102
+ projection: context.reusableComponentProjection ?? {
103
+ bindings: [],
104
+ revisions: []
105
+ },
106
+ allowReusable: true,
107
+ ...context.allowedContainerIds === void 0 ? {} : { allowedContainerIds: context.allowedContainerIds }
108
+ });
109
+ const expanded = expansion.root;
110
+ const normalized = normalizeLayoutDocument({
111
+ version: 1,
112
+ root: expanded
113
+ }, new Set(collectEntryIds(expanded)), context.allowedContainerIds);
114
+ const document = restoreTemplateDocument(normalized.document.root, placements);
115
+ return {
116
+ document: {
117
+ version: 1,
118
+ root: document
119
+ },
120
+ root: decorateReusableIdentity(renderTemplateNode(document, placements), expansion.identities),
121
+ css: generateLayoutCss(normalized.document, void 0, void 0, context.breakpoints)
122
+ };
123
+ }
124
+ function transformNode(value, path, context, placements, nextEntryId) {
125
+ if (!isRecord(value)) fail(path, "INVALID_TYPE");
126
+ if (value.type === "template-block") {
127
+ exactKeys(value, [
128
+ "id",
129
+ "type",
130
+ "apiId",
131
+ "entryId",
132
+ "bindings",
133
+ "templates"
134
+ ], path);
135
+ if (typeof value.id !== "string") fail(`${path}/id`, "INVALID_TYPE");
136
+ if (typeof value.apiId !== "string" || !API_ID.test(value.apiId)) fail(`${path}/apiId`, "INVALID_VALUE");
137
+ const definition = context.blockCatalog[value.apiId];
138
+ if (definition === void 0) fail(`${path}/apiId`, "BLOCK_NOT_FOUND");
139
+ const declared = new Set(definition.fields.map((field) => field.fieldId));
140
+ const renames = definition.renames ?? {};
141
+ const bindings = normalizeBindings(resolveRenamedKeys(value.bindings, path, "bindings", declared, renames), path, definition, context.entry);
142
+ const templates = normalizeTemplates(resolveRenamedKeys(value.templates, path, "templates", declared, renames), path, definition, context.entry, bindings);
143
+ const entryId = value.entryId;
144
+ if (entryId !== void 0 && typeof entryId !== "string") fail(`${path}/entryId`, "INVALID_TYPE");
145
+ const baseEntry = entryId === void 0 ? void 0 : context.blockEntries?.find((candidate) => candidate.id === entryId);
146
+ if (entryId !== void 0 && baseEntry === void 0) fail(`${path}/entryId`, "BLOCK_NOT_FOUND");
147
+ const schemaApiId = baseEntry?.schemaApiId;
148
+ if (typeof schemaApiId === "string" && registeredBlockApiId(schemaApiId) !== value.apiId) fail(`${path}/entryId`, "BLOCK_NOT_FOUND");
149
+ const data = baseEntry === void 0 ? {} : cloneContentRecord(baseEntry.data);
150
+ for (const field of definition.fields) if (baseEntry === void 0 && Object.hasOwn(field, "default")) data[field.fieldId] = cloneContent(field.default);
151
+ for (const [targetPath, binding] of Object.entries(bindings)) {
152
+ const resolved = readBindingPath(context.entry.data, binding);
153
+ const issuePath = `${path}/bindings/${pointerToken(targetPath)}`;
154
+ if (!resolved.found || !writeTargetPath(data, targetPath, resolved.value)) fail(issuePath, "INVALID_VALUE");
155
+ }
156
+ for (const [targetPath, template] of Object.entries(templates)) {
157
+ const issuePath = `${path}/templates/${pointerToken(targetPath)}`;
158
+ if (!writeTargetPath(data, targetPath, renderTextTemplate(template, context.entry, issuePath))) fail(issuePath, "INVALID_VALUE");
159
+ }
160
+ placements.set(value.id, {
161
+ apiId: value.apiId,
162
+ ...entryId === void 0 ? {} : { entryId },
163
+ bindings,
164
+ templates,
165
+ entry: baseEntry === void 0 ? {
166
+ ...context.entry,
167
+ schemaApiId: value.apiId,
168
+ data
169
+ } : {
170
+ ...baseEntry,
171
+ schemaApiId: value.apiId,
172
+ data
173
+ }
174
+ });
175
+ return {
176
+ id: value.id,
177
+ type: "block",
178
+ entryId: nextEntryId()
179
+ };
180
+ }
181
+ if (value.type === "reusable") {
182
+ if (path === "/root") fail(`${path}/type`, "INVALID_VALUE");
183
+ exactKeys(value, [
184
+ "id",
185
+ "type",
186
+ "componentId"
187
+ ], path);
188
+ return value;
189
+ }
190
+ if (value.type !== "flex" && value.type !== "grid") return value;
191
+ if (!Array.isArray(value.children)) return value;
192
+ return {
193
+ ...value,
194
+ children: value.children.map((child, index) => transformNode(child, `${path}/children/${index}`, context, placements, nextEntryId))
195
+ };
196
+ }
197
+ function resolveRenamedKeys(value, path, container, declared, renames) {
198
+ if (!isRecord(value)) return value;
199
+ const rewritten = {};
200
+ const sourcesByTarget = /* @__PURE__ */ new Map();
201
+ for (const key of Object.keys(value)) {
202
+ const dot = key.indexOf(".");
203
+ const head = dot === -1 ? key : key.slice(0, dot);
204
+ const rest = dot === -1 ? "" : key.slice(dot);
205
+ const renamed = !declared.has(head) && Object.hasOwn(renames, head) ? renames[head] : void 0;
206
+ const newKey = renamed === void 0 ? key : renamed + rest;
207
+ rewritten[newKey] = value[key];
208
+ const sources = sourcesByTarget.get(newKey);
209
+ if (sources === void 0) sourcesByTarget.set(newKey, [key]);
210
+ else sources.push(key);
211
+ }
212
+ for (const [newKey, sources] of sourcesByTarget) if (sources.length > 1) fail(`${path}/${container}/${pointerToken(newKey)}`, "INVALID_VALUE");
213
+ return rewritten;
214
+ }
215
+ function normalizeTemplates(value, path, definition, entry, bindings) {
216
+ if (value === void 0) return {};
217
+ if (!isRecord(value)) fail(`${path}/templates`, "INVALID_TYPE");
218
+ const keys = Object.keys(value);
219
+ if (keys.length > MAX_BINDINGS || keys.length + Object.keys(bindings).length > MAX_BINDINGS) fail(`${path}/templates`, "LIMIT_EXCEEDED");
220
+ const declared = new Set(definition.fields.map((field) => field.fieldId));
221
+ const templates = {};
222
+ for (const key of keys.sort()) {
223
+ const template = value[key];
224
+ const issuePath = `${path}/templates/${pointerToken(key)}`;
225
+ if (!validTargetPath(key, declared) || Object.hasOwn(bindings, key)) fail(issuePath, "INVALID_VALUE");
226
+ if (typeof template !== "string") fail(issuePath, "INVALID_TYPE");
227
+ const paths = templatePaths(template);
228
+ if (paths === null || paths.some((binding) => !readBindingPath(entry.data, binding).found)) fail(issuePath, "INVALID_VALUE");
229
+ templates[key] = template;
230
+ }
231
+ return templates;
232
+ }
233
+ function templatePaths(value) {
234
+ if (value === "" || new TextEncoder().encode(value).byteLength > MAX_TEMPLATE_BYTES) return null;
235
+ const paths = [...value.matchAll(TEMPLATE_TOKEN)].map((match) => match[1]);
236
+ if (paths.length === 0 || paths.length > MAX_TEMPLATE_TOKENS) return null;
237
+ const remainder = value.replace(TEMPLATE_TOKEN, "");
238
+ return remainder.includes("{{") || remainder.includes("}}") ? null : paths;
239
+ }
240
+ function renderTextTemplate(value, entry, path) {
241
+ return value.replace(TEMPLATE_TOKEN, (_token, binding) => {
242
+ const resolved = readBindingPath(entry.data, binding);
243
+ if (!resolved.found || typeof resolved.value !== "string") fail(path, "INVALID_VALUE");
244
+ return resolved.value;
245
+ });
246
+ }
247
+ function normalizeBindings(value, path, definition, entry) {
248
+ if (value === void 0) return {};
249
+ if (!isRecord(value)) fail(`${path}/bindings`, "INVALID_TYPE");
250
+ const keys = Object.keys(value);
251
+ if (keys.length > MAX_BINDINGS) fail(`${path}/bindings`, "LIMIT_EXCEEDED");
252
+ const declared = new Set(definition.fields.map((field) => field.fieldId));
253
+ const bindings = {};
254
+ for (const key of keys.sort()) {
255
+ const binding = value[key];
256
+ if (!validTargetPath(key, declared)) fail(`${path}/bindings/${pointerToken(key)}`, "INVALID_VALUE");
257
+ if (typeof binding !== "string" || !validBindingPath(binding)) fail(`${path}/bindings/${pointerToken(key)}`, typeof binding === "string" ? "INVALID_VALUE" : "INVALID_TYPE");
258
+ if (!readBindingPath(entry.data, binding).found) fail(`${path}/bindings/${pointerToken(key)}`, "INVALID_VALUE");
259
+ bindings[key] = binding;
260
+ }
261
+ return bindings;
262
+ }
263
+ function restoreTemplateDocument(node, placements) {
264
+ const restore = (current) => {
265
+ if (current.type === "block") {
266
+ const placement = placements.get(current.id);
267
+ if (placement === void 0) return current;
268
+ return {
269
+ id: current.id,
270
+ type: "template-block",
271
+ apiId: placement.apiId,
272
+ ...placement.entryId === void 0 ? {} : { entryId: placement.entryId },
273
+ ...Object.keys(placement.bindings).length === 0 ? {} : { bindings: placement.bindings },
274
+ ...Object.keys(placement.templates).length === 0 ? {} : { templates: placement.templates }
275
+ };
276
+ }
277
+ return {
278
+ ...current,
279
+ children: current.children.map(restore)
280
+ };
281
+ };
282
+ return restore(node);
283
+ }
284
+ function renderTemplateNode(node, placements) {
285
+ if (node.type === "template-block") {
286
+ const placement = placements.get(node.id);
287
+ if (placement === void 0) fail("", "INVALID_VALUE");
288
+ return {
289
+ ...node,
290
+ entry: placement.entry,
291
+ className: layoutNodeClass(node.id)
292
+ };
293
+ }
294
+ if (node.type === "flex" || node.type === "grid") return {
295
+ ...node,
296
+ className: layoutNodeClass(node.id),
297
+ children: node.children.map((child) => renderTemplateNode(child, placements))
298
+ };
299
+ return {
300
+ ...node,
301
+ className: layoutNodeClass(node.id)
302
+ };
303
+ }
304
+ function collectEntryIds(node) {
305
+ if (node.type === "block") return [node.entryId];
306
+ return node.children.flatMap(collectEntryIds);
307
+ }
308
+ function readBindingPath(root, path) {
309
+ let current = root;
310
+ for (const segment of path.split(".")) {
311
+ if (LIST_INDEX.test(segment)) {
312
+ if (!Array.isArray(current)) return { found: false };
313
+ const index = Number(segment);
314
+ if (index >= current.length) return { found: false };
315
+ current = current[index];
316
+ continue;
317
+ }
318
+ if (!isRecord(current)) return { found: false };
319
+ if (!Object.hasOwn(current, segment) && isRecord(current.data)) current = current.data;
320
+ if (!isRecord(current) || !Object.hasOwn(current, segment)) return { found: false };
321
+ current = current[segment];
322
+ }
323
+ return {
324
+ found: true,
325
+ value: current
326
+ };
327
+ }
328
+ function validBindingPath(path) {
329
+ return path !== "" && new TextEncoder().encode(path).byteLength <= 255 && path.split(".").every((segment) => FIELD_ID.test(segment) || LIST_INDEX.test(segment));
330
+ }
331
+ function validTargetPath(path, declaredRoots) {
332
+ return TARGET_FIELD_PATH.test(path) && declaredRoots.has(path.split(".")[0]);
333
+ }
334
+ function writeTargetPath(root, path, value) {
335
+ const segments = path.split(".");
336
+ let current = root;
337
+ for (let index = 0; index < segments.length - 1; index += 1) {
338
+ const segment = segments[index];
339
+ if (Array.isArray(current)) {
340
+ const itemIndex = Number(segment);
341
+ if (!Number.isSafeInteger(itemIndex) || itemIndex < 0 || itemIndex >= current.length) return false;
342
+ current = current[itemIndex];
343
+ continue;
344
+ }
345
+ if (!isRecord(current) || !Object.hasOwn(current, segment)) return false;
346
+ current = current[segment];
347
+ }
348
+ const finalSegment = segments.at(-1);
349
+ if (Array.isArray(current)) {
350
+ const itemIndex = Number(finalSegment);
351
+ if (!Number.isSafeInteger(itemIndex) || itemIndex < 0 || itemIndex >= current.length) return false;
352
+ current[itemIndex] = value;
353
+ return true;
354
+ }
355
+ if (!isRecord(current) || !FIELD_ID.test(finalSegment)) return false;
356
+ current[finalSegment] = value;
357
+ return true;
358
+ }
359
+ function exactKeys(value, allowed, path) {
360
+ for (const key of Object.keys(value)) if (!allowed.includes(key)) fail(`${path}/${pointerToken(key)}`, "UNKNOWN_KEY");
361
+ }
362
+ function cloneContent(value) {
363
+ if (Array.isArray(value)) return value.map(cloneContent);
364
+ return isRecord(value) ? cloneContentRecord(value) : value;
365
+ }
366
+ function cloneContentRecord(value) {
367
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, cloneContent(child)]));
368
+ }
369
+ function isRecord(value) {
370
+ return typeof value === "object" && value !== null && !Array.isArray(value);
371
+ }
372
+ function pointerToken(value) {
373
+ return value.replaceAll("~", "~0").replaceAll("/", "~1");
374
+ }
375
+ function fail(path, code) {
376
+ throw new LayoutValidationError({
377
+ path,
378
+ code
379
+ });
380
+ }
381
+ //#endregion
382
+ export { blockApiIdOf as a, registeredBlockApiId as c, THEME_ID_PATTERN as i, themeSchemaApiId as l, createTemplateLayoutRenderModel as n, getRegisteredThemeId as o, RESERVED_THEME_IDS as r, registerThemeId as s, buildTemplateBlockRenames as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eldrajs/theme-core",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Framework-free core of the Eldra theme SDK: the Studio preview bridge, stega encoding, the overlay runtime, layout CSS, rich-text positions, design tokens and image framing.",
5
5
  "keywords": [
6
6
  "cms",