@eldrajs/theme-core 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.3.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",