@lacecms/content 0.1.0-alpha.3 → 0.1.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,52 @@
1
1
  import * as v from "valibot";
2
+ /** Validates, detaches and freezes optional sibling layout metadata. */
3
+ export function normalizeFormLayout(value, fields, path = "layout") {
4
+ if (value === undefined)
5
+ return undefined;
6
+ const raw = normalizeJsonValue(value, path, new WeakSet());
7
+ if (!isRecord(raw) ||
8
+ Object.keys(raw).some((key) => !["mode", "groups"].includes(key)) ||
9
+ (raw.mode !== "sections" && raw.mode !== "tabs") ||
10
+ !Array.isArray(raw.groups) ||
11
+ raw.groups.length === 0)
12
+ fail(path, "must declare mode sections/tabs and nonempty groups.");
13
+ const keys = new Set();
14
+ const placed = new Set();
15
+ for (const [index, group] of raw.groups.entries()) {
16
+ const at = `${path}.groups.${index}`;
17
+ if (!isRecord(group) ||
18
+ Object.keys(group).some((key) => !["key", "label", "description", "fields"].includes(key)) ||
19
+ typeof group.key !== "string" ||
20
+ !FIELD_KEY_PATTERN.test(group.key) ||
21
+ keys.has(group.key) ||
22
+ typeof group.label !== "string" ||
23
+ !group.label.trim() ||
24
+ (group.description !== undefined && typeof group.description !== "string") ||
25
+ !Array.isArray(group.fields) ||
26
+ group.fields.length === 0)
27
+ fail(at, "must declare a unique key, nonempty label and fields.");
28
+ keys.add(group.key);
29
+ for (const key of group.fields) {
30
+ if (typeof key !== "string" || !Object.hasOwn(fields, key) || placed.has(key))
31
+ fail(at, `contains unknown or repeated field ${String(key)}.`);
32
+ placed.add(key);
33
+ }
34
+ }
35
+ return deepFreeze(raw);
36
+ }
37
+ /** Sibling field order used by rendering and validation summaries. */
38
+ export function formFieldKeys(fields, layout) {
39
+ const placed = layout?.groups.flatMap((group) => group.fields) ?? [];
40
+ return [...placed, ...Object.keys(fields).filter((key) => !placed.includes(key))];
41
+ }
42
+ /** Maximum containers along a descriptor branch. */
43
+ export const MAX_FIELD_CONTAINER_DEPTH = 6;
44
+ /** Maximum directly nested groups. */
45
+ export const MAX_CONSECUTIVE_GROUPS = 2;
46
+ /** Maximum items in any one list. */
47
+ export const MAX_LIST_ITEMS = 100;
48
+ /** Maximum sum of list lengths in a snapshot. */
49
+ export const MAX_SNAPSHOT_LIST_ITEMS = 500;
2
50
  /** Thrown when a field builder receives a non-portable or contradictory option. */
3
51
  export class FieldConfigurationError extends Error {
4
52
  constructor(message) {
@@ -109,6 +157,7 @@ function deepFreeze(value) {
109
157
  }
110
158
  return value;
111
159
  }
160
+ const RENAMED_FROM_PATTERN = /^[A-Za-z][A-Za-z0-9]*$/u;
112
161
  function readOptionalString(options, name) {
113
162
  const value = options[name];
114
163
  if (value === undefined) {
@@ -151,11 +200,22 @@ function addCommonOptions(definition, options) {
151
200
  if (description !== undefined) {
152
201
  definition.description = description;
153
202
  }
203
+ const placeholder = readOptionalString(options, "placeholder");
204
+ if (placeholder !== undefined)
205
+ definition.placeholder = placeholder;
206
+ const renamedFrom = readOptionalString(options, "renamedFrom");
207
+ if (renamedFrom !== undefined) {
208
+ if (!RENAMED_FROM_PATTERN.test(renamedFrom)) {
209
+ fail("options.renamedFrom", "must be a valid field key.");
210
+ }
211
+ definition.renamedFrom = renamedFrom;
212
+ }
154
213
  definition.required = readOptionalBoolean(options, "required") ?? false;
155
214
  }
156
215
  function assertAllowedOptions(options, allowed) {
157
216
  for (const key of Object.keys(options)) {
158
- if (!allowed.includes(key)) {
217
+ // Every field kind accepts the temporary `renamedFrom` hint.
218
+ if (!allowed.includes(key) && key !== "renamedFrom") {
159
219
  fail(`options.${key}`, "is not supported by this field type.");
160
220
  }
161
221
  }
@@ -178,6 +238,7 @@ function buildStringField(type, input) {
178
238
  "label",
179
239
  "maxLength",
180
240
  "minLength",
241
+ "placeholder",
181
242
  "required",
182
243
  ]);
183
244
  const definition = { type };
@@ -194,13 +255,19 @@ function buildStringField(type, input) {
194
255
  definition.maxLength = maxLength;
195
256
  }
196
257
  addDefault(definition, options, (value) => typeof value === "string" &&
197
- (minLength === undefined || value.length >= minLength) &&
198
- (maxLength === undefined || value.length <= maxLength), "must be a string that conforms to the declared length constraints.");
258
+ (minLength === undefined || textLength(value) >= minLength) &&
259
+ (maxLength === undefined || textLength(value) <= maxLength), "must be a string that conforms to the declared length constraints.");
199
260
  return deepFreeze(definition);
200
261
  }
201
262
  function buildStringValueField(type, input) {
202
263
  const options = normalizeOptions(input ?? {});
203
- assertAllowedOptions(options, ["defaultValue", "description", "label", "required"]);
264
+ assertAllowedOptions(options, [
265
+ "defaultValue",
266
+ "description",
267
+ "label",
268
+ "required",
269
+ ...(type === "url" ? ["placeholder"] : []),
270
+ ]);
204
271
  const definition = { type };
205
272
  addCommonOptions(definition, options);
206
273
  addDefault(definition, options, (value) => typeof value === "string", "must be a string.");
@@ -208,6 +275,14 @@ function buildStringValueField(type, input) {
208
275
  }
209
276
  /** Builders for portable Lace field descriptors. */
210
277
  export const field = {
278
+ /** Define named child fields stored as one plain object. */
279
+ group(options) {
280
+ return normalizeCompositeOptions("group", options);
281
+ },
282
+ /** Define an ordered array of scalar or group values. */
283
+ list(options) {
284
+ return normalizeCompositeOptions("list", options);
285
+ },
211
286
  /** Define a single-line text field. */
212
287
  text(options) {
213
288
  return buildStringField("text", options);
@@ -219,7 +294,13 @@ export const field = {
219
294
  /** Define a safe Tiptap JSON field. */
220
295
  richText(options) {
221
296
  const normalized = normalizeOptions(options ?? {});
222
- assertAllowedOptions(normalized, ["defaultValue", "description", "label", "required"]);
297
+ assertAllowedOptions(normalized, [
298
+ "defaultValue",
299
+ "description",
300
+ "label",
301
+ "required",
302
+ "placeholder",
303
+ ]);
223
304
  const definition = { type: "richText" };
224
305
  addCommonOptions(definition, normalized);
225
306
  addDefault(definition, normalized, (value) => isSafeRichTextDocument(value), "must be a safe rich-text document.");
@@ -232,6 +313,7 @@ export const field = {
232
313
  "defaultValue",
233
314
  "description",
234
315
  "label",
316
+ "placeholder",
235
317
  "max",
236
318
  "min",
237
319
  "required",
@@ -280,6 +362,7 @@ export const field = {
280
362
  "description",
281
363
  "label",
282
364
  "options",
365
+ "placeholder",
283
366
  "required",
284
367
  ]);
285
368
  const rawChoices = normalized.options;
@@ -317,11 +400,154 @@ export const field = {
317
400
  * representation. Runtime schemas and callbacks are deliberately absent.
318
401
  */
319
402
  export function toFieldMetadata(definition) {
320
- const normalized = normalizeJsonValue(definition, "definition", new WeakSet());
321
- if (normalized === null || Array.isArray(normalized) || typeof normalized !== "object") {
322
- fail("definition", "must be a field-definition object.");
403
+ return normalizeFieldDefinition(definition);
404
+ }
405
+ /** Reads own data properties without executing configuration accessors. */
406
+ function descriptorRecord(value, path) {
407
+ if (!isRecord(value))
408
+ fail(path, "must be a plain field-definition object.");
409
+ const output = {};
410
+ for (const key of Reflect.ownKeys(value)) {
411
+ if (typeof key !== "string")
412
+ fail(path, "must not contain symbol keys.");
413
+ const property = Object.getOwnPropertyDescriptor(value, key);
414
+ if (!property.enumerable || !("value" in property))
415
+ fail(`${path}.${key}`, "must be an enumerable data property.");
416
+ Object.defineProperty(output, key, { value: property.value, enumerable: true });
417
+ }
418
+ return output;
419
+ }
420
+ function normalizeCompositeOptions(type, value) {
421
+ const options = descriptorRecord(value, "options");
422
+ if (Object.hasOwn(options, "type"))
423
+ fail("options.type", "is not supported.");
424
+ return normalizeFieldDefinition({ ...options, type });
425
+ }
426
+ /** Validates and detaches a descriptor, including forged JSON/configuration input. */
427
+ export function normalizeFieldDefinition(value) {
428
+ return normalizeDescriptor(value, "definition", 0, 0, new WeakSet());
429
+ }
430
+ function normalizeDescriptor(value, path, depth, groups, ancestors) {
431
+ const raw = descriptorRecord(value, path);
432
+ if (ancestors.has(value))
433
+ fail(path, "must not contain a cyclic reference.");
434
+ const { type, ...options } = raw;
435
+ if (type !== "group" && type !== "list") {
436
+ try {
437
+ switch (type) {
438
+ case "boolean":
439
+ return field.boolean(options);
440
+ case "date":
441
+ return field.date(options);
442
+ case "datetime":
443
+ return field.datetime(options);
444
+ case "media":
445
+ return field.media(options);
446
+ case "number":
447
+ return field.number(options);
448
+ case "richText":
449
+ return field.richText(options);
450
+ case "select":
451
+ return field.select(options);
452
+ case "text":
453
+ return field.text(options);
454
+ case "textarea":
455
+ return field.textarea(options);
456
+ case "url":
457
+ return field.url(options);
458
+ default:
459
+ fail(`${path}.type`, "must name a supported field type.");
460
+ }
461
+ }
462
+ catch (error) {
463
+ if (error instanceof FieldConfigurationError)
464
+ fail(path, error.message);
465
+ throw error;
466
+ }
467
+ }
468
+ if (depth >= MAX_FIELD_CONTAINER_DEPTH)
469
+ fail(path, `must not exceed ${MAX_FIELD_CONTAINER_DEPTH} containers.`);
470
+ if (type === "group" && groups >= MAX_CONSECUTIVE_GROUPS)
471
+ fail(path, `must not exceed ${MAX_CONSECUTIVE_GROUPS} consecutive groups.`);
472
+ const allowed = [
473
+ "label",
474
+ "description",
475
+ "required",
476
+ "defaultValue",
477
+ "renamedFrom",
478
+ ...(type === "group" ? ["fields", "layout"] : ["item", "minItems", "maxItems", "itemLabel"]),
479
+ ];
480
+ for (const key of Object.keys(options))
481
+ if (!allowed.includes(key))
482
+ fail(`${path}.${key}`, "is not supported by this field type.");
483
+ const { fields, item, defaultValue, ...common } = options;
484
+ const normalized = normalizeOptions(common);
485
+ const result = { type };
486
+ addCommonOptions(result, normalized);
487
+ ancestors.add(value);
488
+ try {
489
+ if (type === "group") {
490
+ const children = descriptorRecord(fields, `${path}.fields`);
491
+ const output = {};
492
+ for (const [key, child] of Object.entries(children)) {
493
+ if (!FIELD_KEY_PATTERN.test(key))
494
+ fail(`${path}.fields.${key}`, "must be a valid field key.");
495
+ Object.defineProperty(output, key, {
496
+ value: normalizeDescriptor(child, `${path}.fields.${key}`, depth + 1, groups + 1, ancestors),
497
+ enumerable: true,
498
+ });
499
+ }
500
+ result.fields = output;
501
+ const layout = normalizeFormLayout(options.layout, output, `${path}.layout`);
502
+ if (layout !== undefined)
503
+ result.layout = layout;
504
+ }
505
+ else {
506
+ const child = descriptorRecord(item, `${path}.item`);
507
+ if (child.type === "list")
508
+ fail(`${path}.item`, "must not be a direct list of lists.");
509
+ if (Object.hasOwn(child, "renamedFrom"))
510
+ fail(`${path}.item.renamedFrom`, "list item descriptors have no field key and cannot be renamed.");
511
+ result.item = normalizeDescriptor(item, `${path}.item`, depth + 1, 0, ancestors);
512
+ if (Object.hasOwn(options, "itemLabel")) {
513
+ const key = options.itemLabel;
514
+ const itemDefinition = result.item;
515
+ if (typeof key !== "string" ||
516
+ !FIELD_KEY_PATTERN.test(key) ||
517
+ itemDefinition.type !== "group" ||
518
+ !Object.hasOwn(itemDefinition.fields, key) ||
519
+ !["text", "textarea", "select", "url"].includes(itemDefinition.fields[key].type))
520
+ fail(`${path}.itemLabel`, "must name an immediate text, textarea, select or URL group child.");
521
+ result.itemLabel = key;
522
+ }
523
+ const min = readOptionalFiniteNumber(normalized, "minItems", true);
524
+ const max = readOptionalFiniteNumber(normalized, "maxItems", true);
525
+ if ((min ?? 0) > (max ?? MAX_LIST_ITEMS) || (max ?? MAX_LIST_ITEMS) > MAX_LIST_ITEMS)
526
+ fail(path, `list bounds must satisfy 0 ≤ minItems ≤ maxItems ≤ ${MAX_LIST_ITEMS}.`);
527
+ if (min !== undefined)
528
+ result.minItems = min;
529
+ if (max !== undefined)
530
+ result.maxItems = max;
531
+ }
532
+ if (Object.hasOwn(options, "defaultValue")) {
533
+ const portableDefault = normalizeJsonValue(defaultValue, `${path}.defaultValue`, new WeakSet());
534
+ try {
535
+ normalizeFieldValue(result, portableDefault, "draft", [], {
536
+ count: 0,
537
+ });
538
+ }
539
+ catch (error) {
540
+ if (error instanceof ContentValidationError)
541
+ fail(`${path}.defaultValue`, error.message);
542
+ throw error;
543
+ }
544
+ result.defaultValue = portableDefault;
545
+ }
546
+ return deepFreeze(result);
547
+ }
548
+ finally {
549
+ ancestors.delete(value);
323
550
  }
324
- return deepFreeze(normalized);
325
551
  }
326
552
  /** Thrown when submitted content fails a portable validation contract. */
327
553
  export class ContentValidationError extends Error {
@@ -389,7 +615,13 @@ function assertMarks(value, path) {
389
615
  if (!isRecord(mark.attrs)) {
390
616
  invalid([...markPath, "attrs"], "invalid_link_attributes", "must be an object.");
391
617
  }
392
- assertExactKeys(mark.attrs, ["href"], [], [...markPath, "attrs"]);
618
+ assertExactKeys(mark.attrs, ["href"], ["target", "rel"], [...markPath, "attrs"]);
619
+ if (Object.hasOwn(mark.attrs, "target") && mark.attrs.target !== "_blank") {
620
+ invalid([...markPath, "attrs", "target"], "invalid_link_target", 'must be "_blank".');
621
+ }
622
+ if (Object.hasOwn(mark.attrs, "rel") && mark.attrs.rel !== "nofollow") {
623
+ invalid([...markPath, "attrs", "rel"], "invalid_link_rel", 'must be "nofollow".');
624
+ }
393
625
  if (!isSafeUrl(mark.attrs.href)) {
394
626
  invalid([...markPath, "attrs", "href"], "unsafe_url", "must be an approved URL.");
395
627
  }
@@ -430,10 +662,20 @@ function assertRichTextNode(value, path) {
430
662
  }
431
663
  return;
432
664
  }
433
- if (value.type === "hardBreak") {
665
+ if (value.type === "hardBreak" || value.type === "horizontalRule") {
434
666
  assertExactKeys(value, ["type"], [], path);
435
667
  return;
436
668
  }
669
+ if (value.type === "codeBlock") {
670
+ assertExactKeys(value, ["type"], ["content"], path);
671
+ if (Object.hasOwn(value, "content")) {
672
+ assertRichTextChildren(value.content, [...path, "content"], ["text"]);
673
+ for (const [index, child] of value.content.entries()) {
674
+ assertExactKeys(child, ["type", "text"], [], [...path, "content", index]);
675
+ }
676
+ }
677
+ return;
678
+ }
437
679
  if (value.type === "paragraph") {
438
680
  assertExactKeys(value, ["type"], ["content"], path);
439
681
  if (Object.hasOwn(value, "content")) {
@@ -447,8 +689,11 @@ function assertRichTextNode(value, path) {
447
689
  invalid([...path, "attrs"], "invalid_heading_attributes", "must be an object.");
448
690
  }
449
691
  assertExactKeys(value.attrs, ["level"], [], [...path, "attrs"]);
450
- if (value.attrs.level !== 1 && value.attrs.level !== 2 && value.attrs.level !== 3) {
451
- invalid([...path, "attrs", "level"], "invalid_heading_level", "must be 1, 2, or 3.");
692
+ if (value.attrs.level !== 1 &&
693
+ value.attrs.level !== 2 &&
694
+ value.attrs.level !== 3 &&
695
+ value.attrs.level !== 4) {
696
+ invalid([...path, "attrs", "level"], "invalid_heading_level", "must be 1, 2, 3, or 4.");
452
697
  }
453
698
  if (Object.hasOwn(value, "content")) {
454
699
  assertRichTextChildren(value.content, [...path, "content"], ["hardBreak", "text"]);
@@ -462,12 +707,12 @@ function assertRichTextNode(value, path) {
462
707
  }
463
708
  if (value.type === "listItem") {
464
709
  assertExactKeys(value, ["content", "type"], [], path);
465
- assertRichTextChildren(value.content, [...path, "content"], ["bulletList", "orderedList", "paragraph"]);
710
+ assertRichTextChildren(value.content, [...path, "content"], ["bulletList", "orderedList", "paragraph", "horizontalRule", "codeBlock"]);
466
711
  return;
467
712
  }
468
713
  if (value.type === "blockquote") {
469
714
  assertExactKeys(value, ["content", "type"], [], path);
470
- assertRichTextChildren(value.content, [...path, "content"], ["bulletList", "orderedList", "paragraph"]);
715
+ assertRichTextChildren(value.content, [...path, "content"], ["bulletList", "orderedList", "paragraph", "horizontalRule", "codeBlock"]);
471
716
  return;
472
717
  }
473
718
  invalid([...path, "type"], "unknown_node", "is not permitted.");
@@ -478,7 +723,15 @@ export function validateRichTextDocument(value) {
478
723
  invalid([], "invalid_document", "must be a doc node.");
479
724
  }
480
725
  assertExactKeys(value, ["content", "type"], [], []);
481
- assertRichTextChildren(value.content, ["content"], ["blockquote", "bulletList", "heading", "orderedList", "paragraph"]);
726
+ assertRichTextChildren(value.content, ["content"], [
727
+ "blockquote",
728
+ "bulletList",
729
+ "heading",
730
+ "orderedList",
731
+ "paragraph",
732
+ "horizontalRule",
733
+ "codeBlock",
734
+ ]);
482
735
  return value;
483
736
  }
484
737
  function isSafeRichTextDocument(value) {
@@ -496,6 +749,10 @@ function isSafeRichTextDocument(value) {
496
749
  /** Visits a field descriptor exhaustively. */
497
750
  export function visitFieldDefinition(definition, visitor) {
498
751
  switch (definition.type) {
752
+ case "group":
753
+ return visitor.group(definition);
754
+ case "list":
755
+ return visitor.list(definition);
499
756
  case "boolean":
500
757
  return visitor.boolean(definition);
501
758
  case "date":
@@ -536,6 +793,8 @@ function isUtcIsoDatetime(value) {
536
793
  }
537
794
  function isFieldValue(definition, value) {
538
795
  return visitFieldDefinition(definition, {
796
+ group: () => false,
797
+ list: () => false,
539
798
  boolean: () => typeof value === "boolean",
540
799
  date: () => isCalendarDate(value),
541
800
  datetime: () => isUtcIsoDatetime(value),
@@ -547,55 +806,178 @@ function isFieldValue(definition, value) {
547
806
  richText: () => isSafeRichTextDocument(value),
548
807
  select: (fieldDefinition) => typeof value === "string" && fieldDefinition.options.includes(value),
549
808
  text: (fieldDefinition) => typeof value === "string" &&
550
- (fieldDefinition.minLength === undefined || value.length >= fieldDefinition.minLength) &&
551
- (fieldDefinition.maxLength === undefined || value.length <= fieldDefinition.maxLength),
809
+ (fieldDefinition.minLength === undefined || textLength(value) >= fieldDefinition.minLength) &&
810
+ (fieldDefinition.maxLength === undefined || textLength(value) <= fieldDefinition.maxLength),
552
811
  textarea: (fieldDefinition) => typeof value === "string" &&
553
- (fieldDefinition.minLength === undefined || value.length >= fieldDefinition.minLength) &&
554
- (fieldDefinition.maxLength === undefined || value.length <= fieldDefinition.maxLength),
812
+ (fieldDefinition.minLength === undefined || textLength(value) >= fieldDefinition.minLength) &&
813
+ (fieldDefinition.maxLength === undefined || textLength(value) <= fieldDefinition.maxLength),
555
814
  url: () => isSafeUrl(value),
556
815
  });
557
816
  }
558
- /** Compiles a field definition into its Valibot runtime schema. */
559
- export function compileFieldSchema(definition) {
560
- return v.custom((value) => isFieldValue(definition, value));
817
+ /** Compiles a field definition with the same normalization as aggregate validation. */
818
+ export function compileFieldSchema(definition, mode = "publish") {
819
+ return v.pipe(v.custom((value) => {
820
+ try {
821
+ normalizeFieldValue(definition, value, mode, [], { count: 0 });
822
+ return true;
823
+ }
824
+ catch (error) {
825
+ if (error instanceof ContentValidationError)
826
+ return false;
827
+ throw error;
828
+ }
829
+ }), v.transform((value) => normalizeFieldValue(definition, value, mode, [], { count: 0 })));
830
+ }
831
+ /** Validates and normalizes one present value; absence is handled by its field map. */
832
+ export function validateFieldValue(definition, value, path = [], mode = "publish") {
833
+ return normalizeFieldValue(definition, value, mode, path, { count: 0 });
834
+ }
835
+ function addListItems(length, path, budget) {
836
+ budget.count += length;
837
+ if (budget.count > MAX_SNAPSHOT_LIST_ITEMS)
838
+ invalid(path, "too_many_list_items", `must not exceed ${MAX_SNAPSHOT_LIST_ITEMS} list elements per snapshot.`);
561
839
  }
562
- /** Validates a submitted field value and returns its inferred value type. */
563
- export function validateFieldValue(definition, value, path = []) {
564
- const result = v.safeParse(compileFieldSchema(definition), value);
565
- if (!result.success) {
840
+ function normalizeFieldValue(definition, value, mode, path, budget) {
841
+ if (definition.type === "group") {
842
+ if (!isRecord(value))
843
+ invalid(path, "invalid_field_value", "must be a group object.");
844
+ return normalizeFieldMap(definition.fields, value, mode, path, budget);
845
+ }
846
+ if (definition.type === "list") {
847
+ if (!Array.isArray(value))
848
+ invalid(path, "invalid_field_value", "must be a list.");
849
+ if (value.length > (definition.maxItems ?? MAX_LIST_ITEMS))
850
+ invalid(path, "list_too_long", `must contain at most ${definition.maxItems ?? MAX_LIST_ITEMS} items.`);
851
+ if (mode === "publish" && value.length < (definition.minItems ?? 0))
852
+ invalid(path, "list_too_short", `must contain at least ${definition.minItems} items for publication.`);
853
+ addListItems(value.length, path, budget);
854
+ return Array.from({ length: value.length }, (_, index) => {
855
+ if (!Object.hasOwn(value, index))
856
+ invalid([...path, index], "invalid_field_value", "must contain a value.");
857
+ return normalizeFieldValue(definition.item, value[index], mode, [...path, index], budget);
858
+ });
859
+ }
860
+ if (!isFieldValue(definition, value))
566
861
  invalid(path, "invalid_field_value", "does not conform to its field definition.");
567
- }
568
- return result.output;
862
+ return value;
569
863
  }
570
- /** Validates field data for either an incomplete draft or a publish candidate. */
571
- export function validateModelFields(definitions, value, mode, path = []) {
572
- if (!isRecord(value)) {
864
+ function normalizeFieldMap(definitions, value, mode, path, budget) {
865
+ if (!isRecord(value))
573
866
  invalid(path, "invalid_fields", "must be an object.");
574
- }
575
- for (const key of Object.keys(value)) {
576
- if (!Object.hasOwn(definitions, key)) {
867
+ for (const key of Object.keys(value))
868
+ if (!Object.hasOwn(definitions, key))
577
869
  invalid([...path, key], "unknown_field", "is not defined by this model.");
578
- }
579
- }
580
870
  const output = {};
581
871
  for (const [key, definition] of Object.entries(definitions)) {
582
- if (Object.hasOwn(value, key)) {
583
- output[key] = validateFieldValue(definition, value[key], [...path, key]);
872
+ let present;
873
+ if (Object.hasOwn(value, key))
874
+ present = value[key];
875
+ else if (Object.hasOwn(definition, "defaultValue"))
876
+ present = definition.defaultValue;
877
+ else {
878
+ if (mode === "publish" && definition.required)
879
+ invalid([...path, key], "missing_required_field", "is required for publication.");
584
880
  continue;
585
881
  }
586
- if (Object.hasOwn(definition, "defaultValue")) {
587
- output[key] = validateFieldValue(definition, definition.defaultValue, [...path, key]);
588
- continue;
589
- }
590
- if (mode === "publish" && definition.required) {
591
- invalid([...path, key], "missing_required_field", "is required for publication.");
592
- }
882
+ Object.defineProperty(output, key, {
883
+ value: normalizeFieldValue(definition, present, mode, [...path, key], budget),
884
+ enumerable: true,
885
+ });
593
886
  }
594
887
  return output;
595
888
  }
889
+ /** Validates field data for either an incomplete draft or a publish candidate. */
890
+ export function validateModelFields(definitions, value, mode, path = []) {
891
+ return normalizeFieldMap(definitions, value, mode, path, { count: 0 });
892
+ }
893
+ /** Checks already normalized model/block values against one snapshot-wide budget. */
894
+ export function validateSnapshotListBudget(fields, values, blocks) {
895
+ const budget = { count: 0 };
896
+ function count(definition, value, path) {
897
+ if (definition.type === "group" && isRecord(value))
898
+ walk(definition.fields, value, path);
899
+ if (definition.type === "list" && Array.isArray(value)) {
900
+ addListItems(value.length, path, budget);
901
+ value.forEach((item, index) => count(definition.item, item, [...path, index]));
902
+ }
903
+ }
904
+ function walk(definitions, data, path) {
905
+ for (const [key, definition] of Object.entries(definitions))
906
+ count(definition, data[key], [...path, key]);
907
+ }
908
+ walk(fields, values, ["fields"]);
909
+ blocks.forEach((block) => walk(block.fields, block.data, block.path));
910
+ }
911
+ /** Finds declared media leaves only; ordinary strings never become references. */
912
+ export function collectFieldMedia(definitions, values) {
913
+ const references = [];
914
+ function visit(definition, value, path) {
915
+ if (definition.type === "media" && typeof value === "string")
916
+ references.push({ mediaId: value, path });
917
+ else if (definition.type === "group" && isRecord(value))
918
+ walk(definition.fields, value, path);
919
+ else if (definition.type === "list" && Array.isArray(value))
920
+ value.forEach((item, index) => visit(definition.item, item, [...path, index]));
921
+ }
922
+ function walk(fields, data, path) {
923
+ for (const [key, definition] of Object.entries(fields))
924
+ visit(definition, data[key], [...path, key]);
925
+ }
926
+ walk(definitions, values, []);
927
+ return references;
928
+ }
929
+ /** Keeps legacy scalar keys; nested locations are relative JSON Pointers. */
930
+ export function encodeFieldPath(path) {
931
+ if (path.length === 1)
932
+ return String(path[0]);
933
+ return ("/" + path.map((part) => String(part).replaceAll("~", "~0").replaceAll("/", "~1")).join("/"));
934
+ }
935
+ /** Reads a stored reference path; numeric tokens are list indices under the field-key grammar. */
936
+ export function decodeFieldPath(path) {
937
+ if (!path.startsWith("/"))
938
+ return [path];
939
+ return path
940
+ .slice(1)
941
+ .split("/")
942
+ .map((part) => {
943
+ const decoded = part.replaceAll("~1", "/").replaceAll("~0", "~");
944
+ return /^(?:0|[1-9][0-9]*)$/u.test(decoded) ? Number(decoded) : decoded;
945
+ });
946
+ }
596
947
  const BLOCK_TYPE_PATTERN = /^[A-Za-z][A-Za-z0-9-]*$/u;
597
948
  const BLOCK_KEY_PATTERN = /^(?:[A-Za-z][A-Za-z0-9-]*|[0-7][0-9A-HJKMNP-TV-Z]{25})$/u;
598
949
  const FIELD_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9]*$/u;
950
+ /** Maximum length of a block anchor. */
951
+ export const MAX_BLOCK_ANCHOR_LENGTH = 64;
952
+ /** Maximum length of a normalized block class name. */
953
+ export const MAX_BLOCK_CLASS_NAME_LENGTH = 256;
954
+ /** Maximum number of class tokens in a block class name. */
955
+ export const MAX_BLOCK_CLASS_TOKENS = 16;
956
+ /** Maximum length of one block class token. */
957
+ export const MAX_BLOCK_CLASS_TOKEN_LENGTH = 64;
958
+ const BLOCK_ANCHOR_PATTERN = /^[a-z][a-z0-9-]{0,63}$/u;
959
+ const BLOCK_CLASS_TOKEN_PATTERN = /^[A-Za-z_-][A-Za-z0-9_\-:/.%#[\]]*$/u;
960
+ /** Whether a value is a block anchor: a lowercase letter, then lowercase letters, digits and hyphens. */
961
+ export function isBlockAnchor(value) {
962
+ return typeof value === "string" && BLOCK_ANCHOR_PATTERN.test(value);
963
+ }
964
+ /**
965
+ * Normalizes a block class name: whitespace-separated class tokens, repeats
966
+ * dropped, joined with single spaces. Returns `undefined` for a non-string,
967
+ * blank or invalid value.
968
+ */
969
+ export function normalizeBlockClassName(value) {
970
+ if (typeof value !== "string")
971
+ return undefined;
972
+ const tokens = [...new Set(value.split(/[\t\n\f\r ]+/u).filter((token) => token !== ""))];
973
+ if (tokens.length === 0 ||
974
+ tokens.length > MAX_BLOCK_CLASS_TOKENS ||
975
+ tokens.some((token) => token.length > MAX_BLOCK_CLASS_TOKEN_LENGTH || !BLOCK_CLASS_TOKEN_PATTERN.test(token))) {
976
+ return undefined;
977
+ }
978
+ const normalized = tokens.join(" ");
979
+ return normalized.length > MAX_BLOCK_CLASS_NAME_LENGTH ? undefined : normalized;
980
+ }
599
981
  /** Thrown when a block definition or registry is not portable or internally consistent. */
600
982
  export class BlockConfigurationError extends Error {
601
983
  constructor(message) {
@@ -603,37 +985,117 @@ export class BlockConfigurationError extends Error {
603
985
  this.name = "BlockConfigurationError";
604
986
  }
605
987
  }
988
+ /** Field types a block setting may use; every setting declares a default. */
989
+ export const BLOCK_SETTING_FIELD_TYPES = Object.freeze([
990
+ "boolean",
991
+ "number",
992
+ "select",
993
+ "text",
994
+ ]);
606
995
  function blockFail(message) {
607
996
  throw new BlockConfigurationError(message);
608
997
  }
609
- function normalizeBlockFields(value) {
998
+ function normalizeBlockFields(value, name = "fields") {
610
999
  if (!isRecord(value)) {
611
- blockFail("fields must be a plain object.");
1000
+ blockFail(`${name} must be a plain object.`);
612
1001
  }
613
1002
  const fields = {};
614
1003
  for (const [key, definition] of Object.entries(value)) {
615
1004
  if (!FIELD_KEY_PATTERN.test(key)) {
616
- blockFail(`fields.${key} must be a valid field key.`);
1005
+ blockFail(`${name}.${key} must be a valid field key.`);
617
1006
  }
618
1007
  try {
619
- fields[key] = toFieldMetadata(definition);
1008
+ const metadata = toFieldMetadata(definition);
1009
+ const rejectHints = (field, path) => {
1010
+ if (Object.hasOwn(field, "renamedFrom"))
1011
+ blockFail(`${path} must not declare renamedFrom; block data changes use block versions.`);
1012
+ if (field.type === "group")
1013
+ for (const [childKey, child] of Object.entries(field.fields))
1014
+ rejectHints(child, `${path}.fields.${childKey}`);
1015
+ if (field.type === "list")
1016
+ rejectHints(field.item, `${path}.item`);
1017
+ };
1018
+ rejectHints(metadata, `${name}.${key}`);
1019
+ fields[key] = metadata;
620
1020
  }
621
1021
  catch (error) {
622
1022
  if (error instanceof FieldConfigurationError) {
623
- blockFail(`fields.${key} must be a field definition.`);
1023
+ blockFail(`${name}.${key} must be a field definition.`);
624
1024
  }
625
1025
  throw error;
626
1026
  }
627
1027
  }
628
1028
  return deepFreeze(fields);
629
1029
  }
1030
+ const SETTING_TYPES = new Set(BLOCK_SETTING_FIELD_TYPES);
1031
+ /** Normalizes declared settings; an empty map yields none. */
1032
+ function normalizeBlockSettings(value) {
1033
+ if (value === undefined)
1034
+ return undefined;
1035
+ const settings = normalizeBlockFields(value, "settings");
1036
+ for (const [key, definition] of Object.entries(settings)) {
1037
+ if (!SETTING_TYPES.has(definition.type)) {
1038
+ blockFail(`settings.${key} must be a select, boolean, number or text field.`);
1039
+ }
1040
+ if (!Object.hasOwn(definition, "defaultValue")) {
1041
+ blockFail(`settings.${key} must declare a defaultValue.`);
1042
+ }
1043
+ }
1044
+ return Object.keys(settings).length === 0 ? undefined : settings;
1045
+ }
1046
+ const MIGRATION_KEY_PATTERN = /^[1-9][0-9]*$/u;
1047
+ function normalizeBlockMigrations(value, version) {
1048
+ if (value === undefined)
1049
+ return undefined;
1050
+ if (!isRecord(value)) {
1051
+ blockFail("migrations must be a plain object keyed by target version.");
1052
+ }
1053
+ const keys = Object.keys(value);
1054
+ if (keys.length === 0)
1055
+ return undefined;
1056
+ const targets = [];
1057
+ for (const key of keys) {
1058
+ const target = Number(key);
1059
+ if (!MIGRATION_KEY_PATTERN.test(key) || !Number.isSafeInteger(target)) {
1060
+ blockFail(`migrations.${key} must be keyed by an integer target version.`);
1061
+ }
1062
+ if (target < 2 || target > version) {
1063
+ blockFail(`migrations.${key} must target a version from 2 to ${version}.`);
1064
+ }
1065
+ if (typeof value[key] !== "function") {
1066
+ blockFail(`migrations.${key} must be a function.`);
1067
+ }
1068
+ targets.push(target);
1069
+ }
1070
+ targets.sort((left, right) => left - right);
1071
+ if (targets.at(-1) !== version) {
1072
+ blockFail(`migrations must include the current version ${version}.`);
1073
+ }
1074
+ for (let index = 1; index < targets.length; index += 1) {
1075
+ if (targets[index] !== targets[index - 1] + 1) {
1076
+ blockFail(`migrations.${targets[index - 1] + 1} is missing; migrations must be contiguous.`);
1077
+ }
1078
+ }
1079
+ return Object.freeze(Object.fromEntries(targets.map((target) => [target, value[String(target)]])));
1080
+ }
630
1081
  /** Defines a versioned block using only portable field descriptors. */
631
1082
  export function defineBlock(input) {
632
1083
  if (!isRecord(input)) {
633
1084
  blockFail("block must be a plain object.");
634
1085
  }
635
1086
  for (const key of Object.keys(input)) {
636
- if (!new Set(["defaultValue", "description", "fields", "label", "type", "version"]).has(key)) {
1087
+ if (!new Set([
1088
+ "defaultValue",
1089
+ "description",
1090
+ "fields",
1091
+ "label",
1092
+ "migrations",
1093
+ "layout",
1094
+ "settingsLayout",
1095
+ "settings",
1096
+ "type",
1097
+ "version",
1098
+ ]).has(key)) {
637
1099
  blockFail(`block.${key} is not permitted.`);
638
1100
  }
639
1101
  }
@@ -652,6 +1114,10 @@ export function defineBlock(input) {
652
1114
  blockFail("description must be a string when provided.");
653
1115
  }
654
1116
  const fields = normalizeBlockFields(input.fields);
1117
+ const migrations = normalizeBlockMigrations(input.migrations, input.version);
1118
+ const settings = normalizeBlockSettings(input.settings);
1119
+ const layout = normalizeFormLayout(input.layout, fields, `block.${input.type}.layout`);
1120
+ const settingsLayout = normalizeFormLayout(input.settingsLayout, settings ?? {}, `block.${input.type}.settingsLayout`);
655
1121
  let defaultValue;
656
1122
  if (input.defaultValue !== undefined) {
657
1123
  try {
@@ -673,6 +1139,10 @@ export function defineBlock(input) {
673
1139
  ...(input.description === undefined ? {} : { description: input.description }),
674
1140
  fields,
675
1141
  ...(input.label === undefined ? {} : { label: input.label }),
1142
+ ...(migrations === undefined ? {} : { migrations }),
1143
+ ...(layout === undefined ? {} : { layout }),
1144
+ ...(settingsLayout === undefined ? {} : { settingsLayout }),
1145
+ ...(settings === undefined ? {} : { settings }),
676
1146
  type: input.type,
677
1147
  validate: (value, mode) => {
678
1148
  if (!isRecord(value)) {
@@ -695,6 +1165,22 @@ export function toBlockMetadata(definition) {
695
1165
  toFieldMetadata(fieldDefinition),
696
1166
  ])),
697
1167
  ...(definition.label === undefined ? {} : { label: definition.label }),
1168
+ ...(definition.layout === undefined
1169
+ ? {}
1170
+ : { layout: normalizeFormLayout(definition.layout, definition.fields) }),
1171
+ ...(definition.settingsLayout === undefined
1172
+ ? {}
1173
+ : {
1174
+ settingsLayout: normalizeFormLayout(definition.settingsLayout, definition.settings ?? {}),
1175
+ }),
1176
+ ...(definition.settings === undefined
1177
+ ? {}
1178
+ : {
1179
+ settings: Object.fromEntries(Object.entries(definition.settings).map(([key, fieldDefinition]) => [
1180
+ key,
1181
+ toFieldMetadata(fieldDefinition),
1182
+ ])),
1183
+ }),
698
1184
  type: definition.type,
699
1185
  version: definition.version,
700
1186
  };
@@ -727,6 +1213,115 @@ export function validateBlockData(definition, value, mode, path = []) {
727
1213
  const withDefault = definition.defaultValue === undefined ? value : { ...definition.defaultValue, ...value };
728
1214
  return validateModelFields(definition.fields, withDefault, mode, path);
729
1215
  }
1216
+ /**
1217
+ * Validates a block's settings record against its declared settings, filling
1218
+ * every default; a block that declares none accepts only `{}`.
1219
+ */
1220
+ export function validateBlockSettings(definition, value, path = []) {
1221
+ if (!isRecord(value)) {
1222
+ invalid(path, "invalid_block_settings", "must be an object.");
1223
+ }
1224
+ return validateModelFields(definition.settings ?? {}, value, "draft", path);
1225
+ }
1226
+ /** Thrown when stored block data cannot be migrated to its definition's version. */
1227
+ export class BlockMigrationError extends Error {
1228
+ code;
1229
+ blockType;
1230
+ fromVersion;
1231
+ toVersion;
1232
+ step;
1233
+ constructor(code, blockType, fromVersion, toVersion, message,
1234
+ /** Target version of the failing step, for failed or invalid steps. */
1235
+ step, options) {
1236
+ super(message, options);
1237
+ this.code = code;
1238
+ this.blockType = blockType;
1239
+ this.fromVersion = fromVersion;
1240
+ this.toVersion = toVersion;
1241
+ this.step = step;
1242
+ this.name = "BlockMigrationError";
1243
+ }
1244
+ }
1245
+ function jsonObject(value, name) {
1246
+ if (value instanceof Promise || !isRecord(value)) {
1247
+ throw new FieldConfigurationError(`${name} must be a plain JSON object.`);
1248
+ }
1249
+ return deepFreeze(normalizeJsonValue(value, name, new WeakSet()));
1250
+ }
1251
+ /** Checks a step result: `{data, settings?}`; absent settings keep `previous`. */
1252
+ function migrationResult(value, previous) {
1253
+ if (value instanceof Promise || !isRecord(value)) {
1254
+ throw new FieldConfigurationError("result must be a plain object.");
1255
+ }
1256
+ for (const key of Object.keys(value)) {
1257
+ if (key !== "data" && key !== "settings") {
1258
+ throw new FieldConfigurationError(`result.${key} is not permitted.`);
1259
+ }
1260
+ }
1261
+ if (!Object.hasOwn(value, "data")) {
1262
+ throw new FieldConfigurationError("result.data is required.");
1263
+ }
1264
+ return Object.freeze({
1265
+ data: jsonObject(value.data, "result.data"),
1266
+ settings: value.settings === undefined ? previous : jsonObject(value.settings, "result.settings"),
1267
+ });
1268
+ }
1269
+ /**
1270
+ * Migrates stored block data and settings from `fromVersion` to the
1271
+ * definition's version by composing its declared migrations in ascending
1272
+ * order. Each step receives a detached, frozen copy. The result is not
1273
+ * validated against the definition.
1274
+ */
1275
+ export function migrateBlockData(definition, block, fromVersion) {
1276
+ const toVersion = definition.version;
1277
+ function fail(code, message, step, cause) {
1278
+ throw new BlockMigrationError(code, definition.type, fromVersion, toVersion, message, step, cause === undefined ? undefined : { cause });
1279
+ }
1280
+ if (fromVersion > toVersion) {
1281
+ fail("version_ahead", `Block ${definition.type} version ${fromVersion} is newer than ${toVersion}.`);
1282
+ }
1283
+ let current;
1284
+ try {
1285
+ current = Object.freeze({
1286
+ data: jsonObject(block.data, "data"),
1287
+ settings: jsonObject(block.settings, "settings"),
1288
+ });
1289
+ }
1290
+ catch (error) {
1291
+ fail("invalid_result", `Block ${definition.type} data or settings are not JSON objects.`, fromVersion, error);
1292
+ }
1293
+ for (let step = fromVersion + 1; step <= toVersion; step += 1) {
1294
+ const migration = definition.migrations?.[step];
1295
+ if (migration === undefined) {
1296
+ fail("missing_step", `Block ${definition.type} has no migration from version ${fromVersion} to ${toVersion}.`);
1297
+ }
1298
+ let output;
1299
+ try {
1300
+ output = migration(current);
1301
+ }
1302
+ catch (error) {
1303
+ fail("migration_failed", `Block ${definition.type} migration to version ${step} threw.`, step, error);
1304
+ }
1305
+ try {
1306
+ current = migrationResult(output, current.settings);
1307
+ }
1308
+ catch (error) {
1309
+ fail("invalid_result", `Block ${definition.type} migration to version ${step} did not return {data, settings?} JSON objects.`, step, error);
1310
+ }
1311
+ }
1312
+ return current;
1313
+ }
1314
+ /**
1315
+ * Resolves the alt text of one media usage: a non-blank usage alt (such as the
1316
+ * `image` block's `alt`), then a non-blank media alt, then an empty string.
1317
+ */
1318
+ export function effectiveAltText(usageAlt, mediaAlt) {
1319
+ if (typeof usageAlt === "string" && usageAlt.trim().length > 0)
1320
+ return usageAlt;
1321
+ if (typeof mediaAlt === "string" && mediaAlt.trim().length > 0)
1322
+ return mediaAlt;
1323
+ return "";
1324
+ }
730
1325
  /** Starter blocks implemented exclusively through the public block and field DSL. */
731
1326
  export const builtInBlocks = deepFreeze({
732
1327
  cta: defineBlock({
@@ -741,6 +1336,35 @@ export const builtInBlocks = deepFreeze({
741
1336
  type: "cta",
742
1337
  version: 1,
743
1338
  }),
1339
+ gallery: defineBlock({
1340
+ description: "A grid of images with optional captions.",
1341
+ fields: {
1342
+ images: field.list({
1343
+ defaultValue: [],
1344
+ item: field.group({
1345
+ fields: {
1346
+ alt: field.text({
1347
+ description: "Leave empty to use the media item's alt text.",
1348
+ label: "Alt text",
1349
+ }),
1350
+ caption: field.text({
1351
+ description: "Leave empty to use the media item's caption.",
1352
+ label: "Caption",
1353
+ }),
1354
+ media: field.media({ label: "Image", required: true }),
1355
+ },
1356
+ }),
1357
+ itemLabel: "caption",
1358
+ label: "Images",
1359
+ maxItems: 50,
1360
+ minItems: 1,
1361
+ }),
1362
+ title: field.text({ label: "Title" }),
1363
+ },
1364
+ label: "Gallery",
1365
+ type: "gallery",
1366
+ version: 1,
1367
+ }),
744
1368
  hero: defineBlock({
745
1369
  description: "Large heading with optional text, image, and action.",
746
1370
  fields: {
@@ -756,14 +1380,55 @@ export const builtInBlocks = deepFreeze({
756
1380
  version: 1,
757
1381
  }),
758
1382
  image: defineBlock({
759
- description: "A single image with alt text and an optional caption.",
1383
+ description: "A single image with an optional caption and alt text that overrides the media alt.",
760
1384
  fields: {
761
- alt: field.text({ required: true }),
1385
+ alt: field.text(),
762
1386
  caption: field.text(),
763
1387
  media: field.media({ required: true }),
764
1388
  },
765
1389
  label: "Image",
1390
+ // Version 2 only made `alt` optional, so version 1 data is already valid.
1391
+ migrations: { 2: (block) => block },
766
1392
  type: "image",
1393
+ version: 2,
1394
+ }),
1395
+ navigation: defineBlock({
1396
+ description: "A list of links with optional one-level submenus.",
1397
+ fields: {
1398
+ links: field.list({
1399
+ defaultValue: [],
1400
+ item: field.group({
1401
+ fields: {
1402
+ children: field.list({
1403
+ item: field.group({
1404
+ fields: {
1405
+ label: field.text({ label: "Label", required: true }),
1406
+ url: field.url({ label: "URL", required: true }),
1407
+ },
1408
+ }),
1409
+ itemLabel: "label",
1410
+ label: "Submenu links",
1411
+ maxItems: 20,
1412
+ }),
1413
+ label: field.text({ label: "Label", required: true }),
1414
+ url: field.url({
1415
+ description: "Optional when the link has submenu links.",
1416
+ label: "URL",
1417
+ }),
1418
+ },
1419
+ }),
1420
+ itemLabel: "label",
1421
+ label: "Links",
1422
+ maxItems: 20,
1423
+ minItems: 1,
1424
+ }),
1425
+ name: field.text({
1426
+ description: "Read by screen readers, for example Main or On this page.",
1427
+ label: "Navigation name",
1428
+ }),
1429
+ },
1430
+ label: "Navigation",
1431
+ type: "navigation",
767
1432
  version: 1,
768
1433
  }),
769
1434
  quote: defineBlock({
@@ -840,8 +1505,8 @@ function assertJsonSize(value, path) {
840
1505
  }
841
1506
  /** Validates system entry data and shared payload limits for a draft or publish candidate. */
842
1507
  export function validateEntryPayload(input, mode) {
843
- if (input.kind !== "collection" && input.kind !== "page") {
844
- invalid(["kind"], "invalid_model_kind", "must be page or collection.");
1508
+ if (input.kind !== "collection" && input.kind !== "global" && input.kind !== "page") {
1509
+ invalid(["kind"], "invalid_model_kind", "must be page, collection, or global.");
845
1510
  }
846
1511
  if (typeof input.title !== "string" || input.title.length === 0) {
847
1512
  invalid(["title"], "missing_title", "is required.");
@@ -853,6 +1518,9 @@ export function validateEntryPayload(input, mode) {
853
1518
  (typeof input.slug !== "string" || input.slug.length > MAX_SLUG_LENGTH)) {
854
1519
  invalid(["slug"], "slug_too_long", `must not exceed ${MAX_SLUG_LENGTH} characters.`);
855
1520
  }
1521
+ if (input.kind === "global" && input.slug !== undefined) {
1522
+ invalid(["slug"], "slug_not_allowed", "is not allowed for a global.");
1523
+ }
856
1524
  if (mode === "publish" &&
857
1525
  input.kind === "collection" &&
858
1526
  (input.slug === undefined || input.slug.length === 0)) {
@@ -888,13 +1556,14 @@ export function validateEntryAggregate(input, model, registry, mode) {
888
1556
  const fields = validateModelFields(model.fields, input.fields, mode, ["fields"]);
889
1557
  assertJsonSize(fields, ["fields"]);
890
1558
  const keys = new Set();
1559
+ const anchors = new Set();
891
1560
  const blocks = [];
892
1561
  for (const [index, block] of input.blocks.entries()) {
893
1562
  const path = ["blocks", index];
894
1563
  if (!isRecord(block)) {
895
1564
  invalid(path, "invalid_block", "must be an object.");
896
1565
  }
897
- assertExactKeys(block, ["data", "key", "schemaVersion", "type"], [], path);
1566
+ assertExactKeys(block, ["data", "key", "schemaVersion", "type"], ["anchor", "className", "hidden", "settings"], path);
898
1567
  if (typeof block.key !== "string" || !BLOCK_KEY_PATTERN.test(block.key)) {
899
1568
  invalid([...path, "key"], "invalid_block_key", "must be a stable block key.");
900
1569
  }
@@ -915,15 +1584,50 @@ export function validateEntryAggregate(input, model, registry, mode) {
915
1584
  if (block.schemaVersion !== definition.version) {
916
1585
  invalid([...path, "schemaVersion"], "stale_block_version", "does not match the registered version.");
917
1586
  }
1587
+ if (block.anchor !== undefined) {
1588
+ if (!isBlockAnchor(block.anchor)) {
1589
+ invalid([...path, "anchor"], "invalid_block_anchor", `must start with a lowercase letter and use only lowercase letters, digits and hyphens, up to ${MAX_BLOCK_ANCHOR_LENGTH} characters.`);
1590
+ }
1591
+ if (anchors.has(block.anchor)) {
1592
+ invalid([...path, "anchor"], "duplicate_block_anchor", "must be unique within the entry.");
1593
+ }
1594
+ anchors.add(block.anchor);
1595
+ }
1596
+ let className;
1597
+ if (block.className !== undefined) {
1598
+ className = normalizeBlockClassName(block.className);
1599
+ if (className === undefined) {
1600
+ invalid([...path, "className"], "invalid_block_class_name", `must hold 1 to ${MAX_BLOCK_CLASS_TOKENS} valid class tokens, up to ${MAX_BLOCK_CLASS_NAME_LENGTH} characters.`);
1601
+ }
1602
+ }
1603
+ if (block.hidden !== undefined && typeof block.hidden !== "boolean") {
1604
+ invalid([...path, "hidden"], "invalid_block_hidden", "must be a boolean.");
1605
+ }
1606
+ const hidden = block.hidden === true;
1607
+ const settings = validateBlockSettings(definition, block.settings ?? {}, [...path, "settings"]);
918
1608
  assertJsonSize(block.data, [...path, "data"]);
919
- const data = validateBlockData(definition, block.data, mode, [...path, "data"]);
1609
+ // A hidden block is never delivered, so publication accepts it unfinished.
1610
+ const data = validateBlockData(definition, block.data, hidden ? "draft" : mode, [
1611
+ ...path,
1612
+ "data",
1613
+ ]);
1614
+ assertJsonSize(data, [...path, "data"]);
920
1615
  blocks.push(deepFreeze({
1616
+ ...(block.anchor === undefined ? {} : { anchor: block.anchor }),
1617
+ ...(className === undefined ? {} : { className }),
921
1618
  data: data,
1619
+ hidden,
922
1620
  key: block.key,
923
1621
  schemaVersion: block.schemaVersion,
1622
+ settings,
924
1623
  type: block.type,
925
1624
  }));
926
1625
  }
1626
+ validateSnapshotListBudget(model.fields, fields, blocks.map((block, index) => ({
1627
+ fields: registry.get(block.type).fields,
1628
+ data: block.data,
1629
+ path: ["blocks", index, "data"],
1630
+ })));
927
1631
  return deepFreeze({
928
1632
  blocks: deepFreeze(blocks),
929
1633
  fields,
@@ -932,4 +1636,13 @@ export function validateEntryAggregate(input, model, registry, mode) {
932
1636
  title: input.title,
933
1637
  });
934
1638
  }
1639
+ export { parseSchemaPath, encodeSchemaPath, schemaFieldAt } from "./schema-path.js";
1640
+ /** Raw UTF-16 units: the existing text/textarea length contract, without trimming. */
1641
+ export function textLength(value) {
1642
+ return value.length;
1643
+ }
1644
+ /** Trimmed Unicode code points: the existing SEO title/description contract. */
1645
+ export function seoTextLength(value) {
1646
+ return [...value.trim()].length;
1647
+ }
935
1648
  //# sourceMappingURL=index.js.map