@backmatter/core 0.0.34 → 0.0.36

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backmatter/core",
3
- "version": "0.0.34",
3
+ "version": "0.0.36",
4
4
  "description": "Experimental Backmatter SDK. APIs will break. Not ready for production.",
5
5
  "type": "module",
6
6
  "publishConfig": {
package/src/fields.ts CHANGED
@@ -5,6 +5,7 @@ export type FieldKind =
5
5
  | "image"
6
6
  | "media"
7
7
  | "relation"
8
+ | "link"
8
9
  | "number"
9
10
  | "boolean"
10
11
  | "blocks"
@@ -39,10 +40,15 @@ export type FieldDef<
39
40
  input?: string;
40
41
  /** Allowed values for a text field stored as a string. */
41
42
  options?: readonly string[];
43
+ /** For link fields: internal document targets vs external URLs. */
44
+ to?: "internal" | "external";
45
+ /** For link fields: allowed target model types. */
46
+ models?: string[];
42
47
  min?: number;
43
48
  max?: number;
44
49
  step?: number;
45
50
  where?: RelationWhere;
51
+ multiple?: true;
46
52
  };
47
53
 
48
54
  export type FieldSnapshot = {
@@ -53,10 +59,13 @@ export type FieldSnapshot = {
53
59
  fields?: Record<string, FieldSnapshot>;
54
60
  input?: string;
55
61
  options?: string[];
62
+ to?: "internal" | "external";
63
+ models?: string[];
56
64
  min?: number;
57
65
  max?: number;
58
66
  step?: number;
59
67
  where?: RelationWhere;
68
+ multiple?: true;
60
69
  };
61
70
 
62
71
  type ObjectLike = { name: string; fields: Record<string, FieldDef> };
@@ -77,6 +86,30 @@ type RelationModelInput = {
77
86
  external?: boolean;
78
87
  };
79
88
 
89
+ type LinkModelInput = RelationModelInput & { route?: string | false };
90
+
91
+ type LinkTo = "internal" | "external";
92
+
93
+ type LinkOptsBase<R extends boolean> = Opts<R> & { to?: LinkTo };
94
+
95
+ type LinkOptsNoModels<R extends boolean> = LinkOptsBase<R>;
96
+
97
+ type LinkOptsWithStringModels<R extends boolean> = LinkOptsBase<R> & {
98
+ to?: "internal";
99
+ models: readonly [string, ...string[]];
100
+ };
101
+
102
+ type LinkOptsWithModelModels<R extends boolean> = LinkOptsBase<R> & {
103
+ to?: "internal";
104
+ models: readonly [LinkModelInput, ...LinkModelInput[]];
105
+ };
106
+
107
+ type LinkOptsWithSingleModelWhere<M extends LinkModelInput, R extends boolean> = LinkOptsBase<R> & {
108
+ to?: "internal";
109
+ models: readonly [M];
110
+ where?: RelationWhereForModel<M>;
111
+ };
112
+
80
113
  type ScalarFieldKind = "text" | "number" | "boolean";
81
114
 
82
115
  type ScalarValueOfField<F extends FieldDef> = F extends { kind: "number" }
@@ -148,6 +181,64 @@ function assertNumberConstraints(
148
181
  return { min, max };
149
182
  }
150
183
 
184
+ function assertLinkModelTypes(models: readonly (string | LinkModelInput)[]): string[] {
185
+ if (models.length === 0) {
186
+ throw new Error("field.link models must include at least one model");
187
+ }
188
+ const seen = new Set<string>();
189
+ const types: string[] = [];
190
+ for (const entry of models) {
191
+ if (typeof entry === "string") {
192
+ if (isBlankString(entry)) {
193
+ throw new Error("field.link models must include at least one distinct model type");
194
+ }
195
+ if (seen.has(entry)) {
196
+ throw new Error("field.link models must be distinct model type names");
197
+ }
198
+ seen.add(entry);
199
+ types.push(entry);
200
+ continue;
201
+ }
202
+ if (entry.external) {
203
+ throw new Error("field.link cannot include an external model");
204
+ }
205
+ if (entry.route === false) {
206
+ throw new Error("field.link model must have a route");
207
+ }
208
+ if (seen.has(entry.type)) {
209
+ throw new Error("field.link models must be distinct model type names");
210
+ }
211
+ seen.add(entry.type);
212
+ types.push(entry.type);
213
+ }
214
+ return types;
215
+ }
216
+
217
+ function parseLinkModels(value: unknown): string[] | undefined {
218
+ if (value === undefined) {
219
+ return undefined;
220
+ }
221
+ if (!Array.isArray(value)) {
222
+ throw new Error("invalid field.models");
223
+ }
224
+ if (value.length === 0) {
225
+ throw new Error("invalid field.models");
226
+ }
227
+ const seen = new Set<string>();
228
+ const models: string[] = [];
229
+ for (const item of value) {
230
+ if (typeof item !== "string" || isBlankString(item)) {
231
+ throw new Error("invalid field.models");
232
+ }
233
+ if (seen.has(item)) {
234
+ throw new Error("invalid field.models");
235
+ }
236
+ seen.add(item);
237
+ models.push(item);
238
+ }
239
+ return models;
240
+ }
241
+
151
242
  function parseRelationWhere(value: unknown): RelationWhere | undefined {
152
243
  if (!value || typeof value !== "object" || Array.isArray(value)) {
153
244
  return undefined;
@@ -174,6 +265,9 @@ function base<K extends FieldKind, R extends boolean, To extends string>(
174
265
  max?: number;
175
266
  step?: number;
176
267
  where?: RelationWhere;
268
+ multiple?: boolean;
269
+ to?: LinkTo;
270
+ models?: string[];
177
271
  },
178
272
  ): FieldDef<K, R, To> {
179
273
  return {
@@ -182,10 +276,13 @@ function base<K extends FieldKind, R extends boolean, To extends string>(
182
276
  ...(opts?.relationTo ? { relationTo: opts.relationTo } : {}),
183
277
  ...(opts?.input ? { input: opts.input } : {}),
184
278
  ...(opts?.options ? { options: opts.options } : {}),
279
+ ...(opts?.to ? { to: opts.to } : {}),
280
+ ...(opts?.models ? { models: opts.models } : {}),
185
281
  ...(opts?.min !== undefined ? { min: opts.min } : {}),
186
282
  ...(opts?.max !== undefined ? { max: opts.max } : {}),
187
283
  ...(opts?.step !== undefined ? { step: opts.step } : {}),
188
284
  ...(opts?.where ? { where: opts.where } : {}),
285
+ ...(opts?.multiple === true ? { multiple: true as const } : {}),
189
286
  } as FieldDef<K, R, To>;
190
287
  }
191
288
 
@@ -271,9 +368,73 @@ function relation(
271
368
  });
272
369
  }
273
370
 
371
+ function link<const R extends boolean = false>(opts?: LinkOptsNoModels<R>): FieldDef<"link", R>;
372
+ function link<const M extends LinkModelInput, const R extends boolean = false>(
373
+ opts: LinkOptsWithSingleModelWhere<M, R>,
374
+ ): FieldDef<"link", R>;
375
+ function link<const R extends boolean = false>(
376
+ opts: LinkOptsWithStringModels<R>,
377
+ ): FieldDef<"link", R>;
378
+ function link<const R extends boolean = false>(
379
+ opts: LinkOptsWithModelModels<R>,
380
+ ): FieldDef<"link", R>;
381
+ function link(opts?: LinkOptsBase<boolean> & {
382
+ models?: readonly (string | LinkModelInput)[];
383
+ where?: unknown;
384
+ }): FieldDef<"link", boolean> {
385
+ if (opts?.to === "external") {
386
+ if (opts.models !== undefined || opts.where !== undefined) {
387
+ throw new Error("field.link external cannot include models or where");
388
+ }
389
+ return base("link", {
390
+ to: "external",
391
+ required: opts.required,
392
+ input: opts.input,
393
+ });
394
+ }
395
+
396
+ if (opts?.where !== undefined) {
397
+ const models = opts.models;
398
+ if (!models || models.length !== 1 || typeof models[0] === "string") {
399
+ throw new Error("field.link where requires a model");
400
+ }
401
+ const where = parseRelationWhere(opts.where);
402
+ if (!where) {
403
+ throw new Error("field.link where must be a plain object");
404
+ }
405
+ const modelTypes = assertLinkModelTypes(models);
406
+ return base("link", {
407
+ to: opts.to,
408
+ models: modelTypes,
409
+ where,
410
+ required: opts.required,
411
+ input: opts.input,
412
+ });
413
+ }
414
+
415
+ if (opts?.models !== undefined) {
416
+ const modelTypes = assertLinkModelTypes(opts.models);
417
+ return base("link", {
418
+ to: opts.to,
419
+ models: modelTypes,
420
+ required: opts.required,
421
+ input: opts.input,
422
+ });
423
+ }
424
+
425
+ return base("link", {
426
+ to: opts?.to,
427
+ required: opts?.required,
428
+ input: opts?.input,
429
+ });
430
+ }
431
+
274
432
  type TextFieldDef<R extends boolean, O extends readonly string[] | undefined = undefined> =
275
433
  FieldDef<"text", R> & (O extends readonly string[] ? { readonly options: O } : {});
276
434
 
435
+ type MediaFieldDef<R extends boolean, M extends boolean = false> = FieldDef<"media", R> &
436
+ (M extends true ? { readonly multiple: true } : {});
437
+
277
438
  export const field = {
278
439
  text: <
279
440
  const R extends boolean = false,
@@ -294,7 +455,9 @@ export const field = {
294
455
  }) as TextFieldDef<R, O>;
295
456
  },
296
457
  image: <const R extends boolean = false>(opts?: Opts<R>) => base("image", opts),
297
- media: <const R extends boolean = false>(opts?: Opts<R>) => base("media", opts),
458
+ media: <const R extends boolean = false, const M extends boolean = false>(
459
+ opts?: Opts<R> & { multiple?: M },
460
+ ) => base("media", opts) as MediaFieldDef<R, M>,
298
461
  number: <const R extends boolean = false>(opts?: NumberOpts<R>) => {
299
462
  const bounds = opts ? assertNumberConstraints(opts) : undefined;
300
463
  if (bounds) {
@@ -304,6 +467,7 @@ export const field = {
304
467
  },
305
468
  boolean: <const R extends boolean = false>(opts?: Opts<R>) => base("boolean", opts),
306
469
  relation,
470
+ link,
307
471
  blocks: <const R extends boolean = false>(opts?: Opts<R>) => base("blocks", opts),
308
472
  object: objectField,
309
473
  array: arrayField,
@@ -320,7 +484,10 @@ export function serializeField(def: FieldDef): FieldSnapshot {
320
484
  ...(def.min !== undefined ? { min: def.min } : {}),
321
485
  ...(def.max !== undefined ? { max: def.max } : {}),
322
486
  ...(def.step !== undefined ? { step: def.step } : {}),
487
+ ...(def.to ? { to: def.to } : {}),
488
+ ...(def.models ? { models: [...def.models] } : {}),
323
489
  ...(def.where ? { where: def.where } : {}),
490
+ ...(def.multiple ? { multiple: true as const } : {}),
324
491
  };
325
492
  if (def.fields) {
326
493
  const fields: Record<string, FieldSnapshot> = {};
@@ -343,6 +510,7 @@ export function parseFieldSnapshot(input: unknown): FieldSnapshot {
343
510
  "image",
344
511
  "media",
345
512
  "relation",
513
+ "link",
346
514
  "number",
347
515
  "boolean",
348
516
  "blocks",
@@ -354,6 +522,12 @@ export function parseFieldSnapshot(input: unknown): FieldSnapshot {
354
522
  }
355
523
  const snap: FieldSnapshot = { kind: kind as FieldKind };
356
524
  if (value.required === true) snap.required = true;
525
+ if (value.multiple !== undefined) {
526
+ if (value.multiple !== true && value.multiple !== false) {
527
+ throw new Error("invalid field.multiple");
528
+ }
529
+ if (value.multiple === true) snap.multiple = true;
530
+ }
357
531
  if (typeof value.relationTo === "string" && value.relationTo.length > 0) {
358
532
  snap.relationTo = value.relationTo;
359
533
  }
@@ -363,6 +537,15 @@ export function parseFieldSnapshot(input: unknown): FieldSnapshot {
363
537
  if (typeof value.input === "string" && value.input.length > 0) {
364
538
  snap.input = value.input;
365
539
  }
540
+ if (value.to !== undefined) {
541
+ if (value.to !== "internal" && value.to !== "external") {
542
+ throw new Error("invalid field.to");
543
+ }
544
+ snap.to = value.to;
545
+ }
546
+ if (value.models !== undefined) {
547
+ snap.models = parseLinkModels(value.models);
548
+ }
366
549
  if (Array.isArray(value.options)) {
367
550
  const options: string[] = [];
368
551
  for (const item of value.options) {
package/src/index.ts CHANGED
@@ -67,6 +67,7 @@ export { defineSource } from "./source";
67
67
 
68
68
  export type { DocFormat } from "./doc-format";
69
69
  export { modelFormat, parseDoc, serializeDoc } from "./doc-format";
70
+ export { reserializeDoc } from "./reserialize";
70
71
 
71
72
  export type { BackmatterConfig, BackmatterDirs, DevBarHostConfig, ResolvedConfig } from "./config";
72
73
  export {
@@ -132,10 +133,14 @@ export {
132
133
  validateBlocks,
133
134
  validateContentTree,
134
135
  } from "./validate";
136
+ export type { Problem } from "./problem";
137
+ export type { ValidationIssue } from "./validation-issue";
138
+ export { describeValidationError } from "./validation-issue";
135
139
  export { coerceFieldValue, coerceDocValues, imageUrlFromUnknown } from "./coerce";
136
140
  export { documentLabel } from "./document-label";
137
141
  export { matchesWhere } from "./relation-match";
138
142
  export { relationProblems } from "./relation-problems";
143
+ export { linkProblems } from "./link-problems";
139
144
  export { isColorString } from "./color";
140
145
 
141
146
  export type { FrontmatterJsonSchema } from "./zod";
@@ -205,3 +210,12 @@ export {
205
210
  type EnterRequest,
206
211
  type EnterTarget,
207
212
  } from "./enter";
213
+
214
+ export type { LinkSide } from "./link-address";
215
+ export {
216
+ externalLinkOk,
217
+ internalSuffixError,
218
+ joinInternalLink,
219
+ linkSide,
220
+ splitInternalLink,
221
+ } from "./link-address";
@@ -0,0 +1,141 @@
1
+ // packages/core/src/link-address.ts
2
+ export type LinkSide = "internal" | "external" | "neither";
3
+
4
+ const SCHEME_RE = /^([a-z][a-z0-9+.-]*):/i;
5
+ const EXTERNAL_SCHEMES = new Set(["http", "https", "mailto", "tel"]);
6
+
7
+ export function linkSide(value: string): LinkSide {
8
+ const trimmed = value.trim();
9
+ const schemeMatch = trimmed.match(SCHEME_RE);
10
+ if (schemeMatch) {
11
+ const scheme = schemeMatch[1].toLowerCase();
12
+ if (EXTERNAL_SCHEMES.has(scheme)) {
13
+ return "external";
14
+ }
15
+ }
16
+ if (trimmed.startsWith("/")) {
17
+ return "internal";
18
+ }
19
+ return "neither";
20
+ }
21
+
22
+ export function splitInternalLink(value: string): {
23
+ path: string;
24
+ query: string;
25
+ anchor: string;
26
+ } {
27
+ const trimmed = value.trim();
28
+ const hashIndex = trimmed.indexOf("#");
29
+ let pathAndQuery: string;
30
+ let anchor: string;
31
+ if (hashIndex === -1) {
32
+ pathAndQuery = trimmed;
33
+ anchor = "";
34
+ } else {
35
+ pathAndQuery = trimmed.slice(0, hashIndex);
36
+ anchor = trimmed.slice(hashIndex + 1);
37
+ }
38
+ const queryIndex = pathAndQuery.indexOf("?");
39
+ if (queryIndex === -1) {
40
+ return { path: pathAndQuery, query: "", anchor };
41
+ }
42
+ return {
43
+ path: pathAndQuery.slice(0, queryIndex),
44
+ query: pathAndQuery.slice(queryIndex + 1),
45
+ anchor,
46
+ };
47
+ }
48
+
49
+ export function joinInternalLink(path: string, query: string, anchor: string): string {
50
+ let result = path;
51
+ if (query !== "") {
52
+ result += `?${query}`;
53
+ }
54
+ if (anchor !== "") {
55
+ result += `#${anchor}`;
56
+ }
57
+ return result;
58
+ }
59
+
60
+ const QUERY_SUFFIX_RE = /^[^\s#]+$/;
61
+ const ANCHOR_SUFFIX_RE = /^[^\s#?]+$/;
62
+
63
+ export function internalSuffixError(
64
+ parts: { query: string; anchor: string },
65
+ present: { query: boolean; anchor: boolean },
66
+ ): "query" | "anchor" | null {
67
+ if (present.query && !QUERY_SUFFIX_RE.test(parts.query)) {
68
+ return "query";
69
+ }
70
+ if (present.anchor && !ANCHOR_SUFFIX_RE.test(parts.anchor)) {
71
+ return "anchor";
72
+ }
73
+ return null;
74
+ }
75
+
76
+ const MAILTO_RE = /^mailto:([^?#\s]*)(\?([^#\s]*))?$/i;
77
+ const TEL_BODY_RE = /^\+?[0-9 .()-]*$/;
78
+
79
+ function mailtoOk(trimmed: string): boolean {
80
+ const match = trimmed.match(MAILTO_RE);
81
+ if (!match) {
82
+ return false;
83
+ }
84
+ const address = match[1];
85
+ const query = match[3];
86
+ if (match[2] !== undefined && (query === undefined || query === "")) {
87
+ return false;
88
+ }
89
+ const atParts = address.split("@");
90
+ if (atParts.length !== 2 || atParts[0] === "" || atParts[1] === "") {
91
+ return false;
92
+ }
93
+ const domain = atParts[1];
94
+ const dotIndex = domain.indexOf(".");
95
+ if (dotIndex <= 0 || dotIndex >= domain.length - 1) {
96
+ return false;
97
+ }
98
+ return true;
99
+ }
100
+
101
+ function telOk(trimmed: string): boolean {
102
+ if (!trimmed.toLowerCase().startsWith("tel:")) {
103
+ return false;
104
+ }
105
+ const body = trimmed.slice(trimmed.indexOf(":") + 1);
106
+ if (!TEL_BODY_RE.test(body) || !/\d/.test(body)) {
107
+ return false;
108
+ }
109
+ return true;
110
+ }
111
+
112
+ function httpOk(trimmed: string): boolean {
113
+ try {
114
+ const url = new URL(trimmed);
115
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
116
+ return false;
117
+ }
118
+ return url.hostname !== "";
119
+ } catch {
120
+ return false;
121
+ }
122
+ }
123
+
124
+ export function externalLinkOk(value: string): boolean {
125
+ const trimmed = value.trim();
126
+ const schemeMatch = trimmed.match(SCHEME_RE);
127
+ if (!schemeMatch) {
128
+ return false;
129
+ }
130
+ const scheme = schemeMatch[1].toLowerCase();
131
+ if (scheme === "http" || scheme === "https") {
132
+ return httpOk(trimmed);
133
+ }
134
+ if (scheme === "mailto") {
135
+ return mailtoOk(trimmed);
136
+ }
137
+ if (scheme === "tel") {
138
+ return telOk(trimmed);
139
+ }
140
+ return false;
141
+ }
@@ -0,0 +1,274 @@
1
+ // packages/core/src/link-problems.ts
2
+ import type { BlockInstance } from "./block";
3
+ import type { FieldSnapshot } from "./fields";
4
+ import {
5
+ externalLinkOk,
6
+ internalSuffixError,
7
+ linkSide,
8
+ splitInternalLink,
9
+ } from "./link-address";
10
+ import { matchesWhere } from "./relation-match";
11
+ import type { ModelSnapshot, SchemaSnapshot } from "./model";
12
+ import { routeFor } from "./routes";
13
+
14
+ type DocEntry = {
15
+ type: string;
16
+ slug: string;
17
+ frontmatter: Record<string, unknown>;
18
+ };
19
+
20
+ function isBlankLinkValue(value: unknown): boolean {
21
+ return typeof value !== "string" || value.trim() === "";
22
+ }
23
+
24
+ function inlineFields(field: FieldSnapshot): Record<string, FieldSnapshot> | undefined {
25
+ if (!field.fields || Object.keys(field.fields).length === 0) return undefined;
26
+ return field.fields;
27
+ }
28
+
29
+ function objectFieldsFor(
30
+ schema: SchemaSnapshot,
31
+ field: FieldSnapshot,
32
+ ): Record<string, FieldSnapshot> | undefined {
33
+ const inline = inlineFields(field);
34
+ if (inline) return inline;
35
+ if ((field.kind === "object" || field.kind === "array") && field.object) {
36
+ const def = schema.objects?.find((o) => o.name === field.object);
37
+ return def?.fields;
38
+ }
39
+ return undefined;
40
+ }
41
+
42
+ function joinPath(prefix: string, segment: string): string {
43
+ return prefix ? `${prefix}.${segment}` : segment;
44
+ }
45
+
46
+ function modelsLabel(models: string[]): string {
47
+ return models.join(" or ");
48
+ }
49
+
50
+ function documentRouteMessage(path: string, models: string[] | undefined): string {
51
+ if (models && models.length > 0) {
52
+ return `${path} must be a route of ${modelsLabel(models)}`;
53
+ }
54
+ return `${path} must be a document route`;
55
+ }
56
+
57
+ function buildRouteIndex(
58
+ schema: SchemaSnapshot,
59
+ docs: Array<{ type: string; slug: string; frontmatter: Record<string, unknown> }>,
60
+ modelsByType: Map<string, ModelSnapshot>,
61
+ ): Map<string, DocEntry[]> {
62
+ const index = new Map<string, DocEntry[]>();
63
+ for (const doc of docs) {
64
+ const model = modelsByType.get(doc.type);
65
+ if (!model || model.external || model.route === false) continue;
66
+ const route = routeFor(model, doc.slug);
67
+ const row: DocEntry = {
68
+ type: doc.type,
69
+ slug: doc.slug,
70
+ frontmatter: doc.frontmatter,
71
+ };
72
+ const list = index.get(route);
73
+ if (list) {
74
+ list.push(row);
75
+ } else {
76
+ index.set(route, [row]);
77
+ }
78
+ }
79
+ return index;
80
+ }
81
+
82
+ function validateInternalLink(
83
+ path: string,
84
+ field: FieldSnapshot,
85
+ value: string,
86
+ routeIndex: Map<string, DocEntry[]>,
87
+ errors: string[],
88
+ ): void {
89
+ const parts = splitInternalLink(value);
90
+ const atPath = routeIndex.get(parts.path) ?? [];
91
+ const models = field.models;
92
+ let candidates = atPath;
93
+ if (models && models.length > 0) {
94
+ candidates = atPath.filter((d) => models.includes(d.type));
95
+ }
96
+
97
+ if (candidates.length === 0) {
98
+ errors.push(documentRouteMessage(path, models));
99
+ return;
100
+ }
101
+
102
+ const passing = candidates.filter((d) =>
103
+ matchesWhere({ slug: d.slug, frontmatter: d.frontmatter }, field.where),
104
+ );
105
+ if (passing.length === 0) {
106
+ errors.push(`${path} must match the field's filter`);
107
+ return;
108
+ }
109
+
110
+ const hashIndex = value.indexOf("#");
111
+ const preHash = hashIndex === -1 ? value : value.slice(0, hashIndex);
112
+ const suffixErr = internalSuffixError(
113
+ { query: parts.query, anchor: parts.anchor },
114
+ { query: preHash.includes("?"), anchor: hashIndex !== -1 },
115
+ );
116
+ if (suffixErr === "query") {
117
+ errors.push(`${path} has an invalid query`);
118
+ } else if (suffixErr === "anchor") {
119
+ errors.push(`${path} has an invalid anchor`);
120
+ }
121
+ }
122
+
123
+ function checkLinkValue(
124
+ path: string,
125
+ field: FieldSnapshot,
126
+ value: unknown,
127
+ routeIndex: Map<string, DocEntry[]>,
128
+ errors: string[],
129
+ ): void {
130
+ if (field.kind !== "link") return;
131
+ if (isBlankLinkValue(value)) return;
132
+
133
+ const side = linkSide(value as string);
134
+ const models = field.models;
135
+
136
+ if (field.to === "external" || (field.to === undefined && side === "external")) {
137
+ if (!externalLinkOk(value as string)) {
138
+ errors.push(`${path} must be an http(s) URL, email, or phone`);
139
+ }
140
+ return;
141
+ }
142
+
143
+ if (field.to === "internal" || (field.to === undefined && side === "internal")) {
144
+ validateInternalLink(path, field, value as string, routeIndex, errors);
145
+ return;
146
+ }
147
+
148
+ if (field.to === undefined && side === "neither") {
149
+ errors.push(
150
+ `${path} must be a document route or an http(s) URL, email, or phone`,
151
+ );
152
+ return;
153
+ }
154
+
155
+ if (field.to === "internal" && side !== "internal") {
156
+ errors.push(documentRouteMessage(path, models));
157
+ }
158
+ }
159
+
160
+ function asBlockList(value: unknown): BlockInstance[] {
161
+ if (!Array.isArray(value)) return [];
162
+ return value.filter((item): item is BlockInstance => {
163
+ if (!item || typeof item !== "object") return false;
164
+ const row = item as Record<string, unknown>;
165
+ return typeof row.id === "string" && typeof row.type === "string";
166
+ });
167
+ }
168
+
169
+ function walkFields(
170
+ schema: SchemaSnapshot,
171
+ pathPrefix: string,
172
+ fields: Record<string, FieldSnapshot>,
173
+ data: Record<string, unknown>,
174
+ routeIndex: Map<string, DocEntry[]>,
175
+ errors: string[],
176
+ ): void {
177
+ for (const [name, field] of Object.entries(fields)) {
178
+ const path = joinPath(pathPrefix, name);
179
+ const value = data[name];
180
+
181
+ if (field.kind === "link") {
182
+ checkLinkValue(path, field, value, routeIndex, errors);
183
+ continue;
184
+ }
185
+
186
+ if (field.kind === "blocks") {
187
+ walkBlockInstances(schema, name, value, routeIndex, errors);
188
+ continue;
189
+ }
190
+
191
+ const nested = objectFieldsFor(schema, field);
192
+ if (!nested) continue;
193
+
194
+ if (field.kind === "array" && Array.isArray(value)) {
195
+ value.forEach((item, index) => {
196
+ if (!item || typeof item !== "object") return;
197
+ walkFields(
198
+ schema,
199
+ `${path}.${index}`,
200
+ nested,
201
+ item as Record<string, unknown>,
202
+ routeIndex,
203
+ errors,
204
+ );
205
+ });
206
+ } else if (field.kind === "object" && value && typeof value === "object") {
207
+ walkFields(
208
+ schema,
209
+ path,
210
+ nested,
211
+ value as Record<string, unknown>,
212
+ routeIndex,
213
+ errors,
214
+ );
215
+ }
216
+ }
217
+ }
218
+
219
+ function walkBlockInstances(
220
+ schema: SchemaSnapshot,
221
+ prefix: string,
222
+ blocks: unknown,
223
+ routeIndex: Map<string, DocEntry[]>,
224
+ errors: string[],
225
+ ): void {
226
+ const catalog = schema.blocks ?? [];
227
+ const byName = new Map(catalog.map((b) => [b.name, b]));
228
+ asBlockList(blocks).forEach((block, index) => {
229
+ const def = byName.get(block.type);
230
+ if (!def) return;
231
+ const props =
232
+ block.props && typeof block.props === "object"
233
+ ? (block.props as Record<string, unknown>)
234
+ : {};
235
+ walkFields(
236
+ schema,
237
+ `${prefix}[${index}]`,
238
+ def.fields,
239
+ props,
240
+ routeIndex,
241
+ errors,
242
+ );
243
+ });
244
+ }
245
+
246
+ function walkDocument(
247
+ schema: SchemaSnapshot,
248
+ model: ModelSnapshot,
249
+ frontmatter: Record<string, unknown>,
250
+ routeIndex: Map<string, DocEntry[]>,
251
+ errors: string[],
252
+ ): void {
253
+ walkFields(schema, "", model.fields, frontmatter, routeIndex, errors);
254
+ }
255
+
256
+ export function linkProblems(input: {
257
+ schema: SchemaSnapshot;
258
+ docs: Array<{ type: string; slug: string; frontmatter: Record<string, unknown> }>;
259
+ }): Array<{ type: string; slug: string; errors: string[] }> {
260
+ const modelsByType = new Map(input.schema.models.map((m) => [m.type, m]));
261
+ const routeIndex = buildRouteIndex(input.schema, input.docs, modelsByType);
262
+
263
+ const rows: Array<{ type: string; slug: string; errors: string[] }> = [];
264
+ for (const doc of input.docs) {
265
+ const model = modelsByType.get(doc.type);
266
+ if (!model) continue;
267
+ const errors: string[] = [];
268
+ walkDocument(input.schema, model, doc.frontmatter, routeIndex, errors);
269
+ if (errors.length > 0) {
270
+ rows.push({ type: doc.type, slug: doc.slug, errors });
271
+ }
272
+ }
273
+ return rows;
274
+ }
@@ -28,6 +28,12 @@ function collect(
28
28
  if (typeof value === "string") {
29
29
  const id = mediaIdFromUrl(value);
30
30
  if (id) ids.push(id);
31
+ } else if (Array.isArray(value)) {
32
+ for (const entry of value) {
33
+ if (typeof entry !== "string") continue;
34
+ const id = mediaIdFromUrl(entry);
35
+ if (id) ids.push(id);
36
+ }
31
37
  }
32
38
  continue;
33
39
  }
package/src/model.ts CHANGED
@@ -196,7 +196,9 @@ type ValueOfField<F> = F extends { kind: "number" }
196
196
  ? boolean
197
197
  : F extends { kind: "blocks" }
198
198
  ? BlockInstance[]
199
- : F extends { options: infer O extends readonly [string, ...string[]] }
199
+ : F extends { kind: "media"; multiple: true }
200
+ ? string[]
201
+ : F extends { options: infer O extends readonly [string, ...string[]] }
200
202
  ? O[number]
201
203
  : string;
202
204
 
package/src/problem.ts ADDED
@@ -0,0 +1,15 @@
1
+ // packages/core/src/problem.ts
2
+
3
+ /** One failure from a workspace action, written for the person or agent who repairs it. */
4
+ export type Problem = {
5
+ code: string;
6
+ message: string;
7
+ fix?: string;
8
+ doc?: { type: string; slug: string };
9
+ /** Dotted path, such as "cover" or "blocks[2].image". */
10
+ field?: string;
11
+ path?: string;
12
+ /** A step only a person can take, such as approving a GitHub install. */
13
+ needsPerson?: { url: string; reason: string };
14
+ retryable: boolean;
15
+ };
package/src/query.ts CHANGED
@@ -120,7 +120,9 @@ type StoredOf<F, Blocks extends readonly BlockDef[]> = F extends { kind: "number
120
120
  ? ObjectShape<Fields, Blocks>
121
121
  : F extends { kind: "array"; fields: infer Fields }
122
122
  ? ObjectShape<Fields, Blocks>[]
123
- : F extends { options: infer O extends readonly [string, ...string[]] }
123
+ : F extends { kind: "media"; multiple: true }
124
+ ? string[]
125
+ : F extends { options: infer O extends readonly [string, ...string[]] }
124
126
  ? O[number]
125
127
  : string;
126
128
 
@@ -0,0 +1,54 @@
1
+ // packages/core/src/reserialize.ts
2
+ //
3
+ // Write a document's new values over its previous text. Fields whose values
4
+ // didn't change keep their exact lines, so an edit to one field doesn't
5
+ // reformat the rest of the file in git.
6
+ import { isMap, parseDocument } from "yaml";
7
+ import { serializeDoc, type DocFormat } from "./doc-format";
8
+ import { parseMdx, type Frontmatter } from "./mdx";
9
+
10
+ const FM_RE = /^(---\r?\n)([\s\S]*?)(\r?\n---\r?\n?)([\s\S]*)$/;
11
+
12
+ function sameValue(a: unknown, b: unknown): boolean {
13
+ return JSON.stringify(a) === JSON.stringify(b);
14
+ }
15
+
16
+ export function reserializeDoc(
17
+ previous: string | null,
18
+ format: DocFormat,
19
+ frontmatter: Frontmatter,
20
+ body: string,
21
+ ): string {
22
+ if (format === "page" || previous === null) return serializeDoc(format, frontmatter, body);
23
+ const match = FM_RE.exec(previous);
24
+ if (!match) return serializeDoc(format, frontmatter, body);
25
+
26
+ let before: Frontmatter;
27
+ try {
28
+ before = parseMdx(previous).frontmatter;
29
+ } catch {
30
+ return serializeDoc(format, frontmatter, body);
31
+ }
32
+ const doc = parseDocument(match[2] ?? "");
33
+ if (doc.errors.length > 0 || !isMap(doc.contents)) {
34
+ return serializeDoc(format, frontmatter, body);
35
+ }
36
+ if (Object.keys(frontmatter).length === 0) return serializeDoc(format, frontmatter, body);
37
+
38
+ let changed = false;
39
+ for (const key of Object.keys(before)) {
40
+ if (!(key in frontmatter) || frontmatter[key] === undefined) {
41
+ doc.delete(key);
42
+ changed = true;
43
+ }
44
+ }
45
+ for (const [key, value] of Object.entries(frontmatter)) {
46
+ if (value === undefined) continue;
47
+ if (key in before && sameValue(before[key], value)) continue;
48
+ doc.set(key, value);
49
+ changed = true;
50
+ }
51
+
52
+ const yaml = changed ? doc.toString({ lineWidth: 0 }).replace(/\r?\n$/, "") : match[2];
53
+ return `${match[1]}${yaml}${match[3]}${body}`;
54
+ }
@@ -64,6 +64,82 @@ function nestedFieldsToWalk(
64
64
  return undefined;
65
65
  }
66
66
 
67
+ function checkWhereOnModel(
68
+ path: string,
69
+ where: NonNullable<FieldSnapshot["where"]>,
70
+ target: ModelSnapshot,
71
+ problems: string[],
72
+ ): void {
73
+ for (const [key, value] of Object.entries(where)) {
74
+ if (key === "slug") {
75
+ if (typeof value !== "string") {
76
+ problems.push(`${path} where.slug must be a string`);
77
+ }
78
+ continue;
79
+ }
80
+ const targetField = target.fields[key];
81
+ if (!targetField || !isScalarKind(targetField.kind)) {
82
+ problems.push(`${path} where.${key} is not a scalar field of ${target.type}`);
83
+ continue;
84
+ }
85
+ const expected = scalarJsonType(targetField.kind);
86
+ if (typeof value !== expected) {
87
+ problems.push(`${path} where.${key} must be a ${expected}`);
88
+ }
89
+ }
90
+ }
91
+
92
+ function checkLinkField(
93
+ path: string,
94
+ field: FieldSnapshot,
95
+ modelsByType: Map<string, ModelSnapshot>,
96
+ problems: string[],
97
+ ): void {
98
+ if (field.kind !== "link") {
99
+ return;
100
+ }
101
+ if (field.to === "external") {
102
+ if ((field.models && field.models.length > 0) || field.where) {
103
+ problems.push(`${path} to external cannot set models or where`);
104
+ }
105
+ return;
106
+ }
107
+ if (field.models) {
108
+ const seen = new Set<string>();
109
+ for (const name of field.models) {
110
+ if (seen.has(name)) {
111
+ problems.push(`${path} models repeats ${name}`);
112
+ continue;
113
+ }
114
+ seen.add(name);
115
+ const target = modelsByType.get(name);
116
+ if (!target) {
117
+ problems.push(`${path} models "${name}" names no model`);
118
+ continue;
119
+ }
120
+ if (target.external) {
121
+ problems.push(`${path} models names external model "${name}"`);
122
+ continue;
123
+ }
124
+ if (target.route === false) {
125
+ problems.push(`${path} models "${name}" route is false`);
126
+ }
127
+ }
128
+ }
129
+ if (!field.where) {
130
+ return;
131
+ }
132
+ if (field.models?.length !== 1) {
133
+ problems.push(`${path} where requires one model`);
134
+ return;
135
+ }
136
+ const target = modelsByType.get(field.models[0]!);
137
+ if (!target) {
138
+ return;
139
+ }
140
+ checkWhereOnModel(path, field.where, target, problems);
141
+ }
142
+
67
143
  function checkRelationField(
68
144
  path: string,
69
145
  field: FieldSnapshot,
@@ -85,23 +161,7 @@ function checkRelationField(
85
161
  problems.push(`${path} where is set on external model "${target.type}"`);
86
162
  return;
87
163
  }
88
- for (const [key, value] of Object.entries(field.where)) {
89
- if (key === "slug") {
90
- if (typeof value !== "string") {
91
- problems.push(`${path} where.slug must be a string`);
92
- }
93
- continue;
94
- }
95
- const targetField = target.fields[key];
96
- if (!targetField || !isScalarKind(targetField.kind)) {
97
- problems.push(`${path} where.${key} is not a scalar field of ${target.type}`);
98
- continue;
99
- }
100
- const expected = scalarJsonType(targetField.kind);
101
- if (typeof value !== expected) {
102
- problems.push(`${path} where.${key} must be a ${expected}`);
103
- }
104
- }
164
+ checkWhereOnModel(path, field.where, target, problems);
105
165
  }
106
166
 
107
167
  function checkObjectReference(
@@ -134,6 +194,7 @@ function walkFields(
134
194
  const path = fieldPath(owner, [...segments, name]);
135
195
  checkObjectReference(schema, path, field, problems);
136
196
  checkRelationField(path, field, modelsByType, problems);
197
+ checkLinkField(path, field, modelsByType, problems);
137
198
  const nested = nestedFieldsToWalk(schema, field, visitingObjects);
138
199
  if (nested) {
139
200
  walkFields(schema, owner, [...segments, name], nested, modelsByType, visitingObjects, problems);
package/src/validate.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  // packages/core/src/validate.ts
2
2
  import { z } from "zod";
3
3
  import { modelFormat, parseDoc } from "./doc-format";
4
+ import { linkProblems } from "./link-problems";
4
5
  import { relationProblems } from "./relation-problems";
5
- import type { Frontmatter } from "./mdx";
6
+ import type { FieldSnapshot } from "./fields";
6
7
  import { parseMdx } from "./mdx";
8
+ import type { Frontmatter } from "./mdx";
7
9
  import type { ModelSnapshot } from "./model";
8
10
  import type { BlockInstance, BlockSnapshot } from "./block";
9
11
  import type { ObjectSnapshot } from "./object";
@@ -18,6 +20,24 @@ function pathKey(path: PropertyKey[]): string {
18
20
  return path.map(String).join(".");
19
21
  }
20
22
 
23
+ function mediaListEntryKey(path: PropertyKey[]): string | null {
24
+ const last = path[path.length - 1];
25
+ if (typeof last !== "number") return null;
26
+ const parents = path.slice(0, -1).map(String).join(".");
27
+ return `${parents}[${last}]`;
28
+ }
29
+
30
+ function issuePathKey(
31
+ path: PropertyKey[],
32
+ field: FieldSnapshot | undefined,
33
+ ): string {
34
+ if (field?.kind === "media" && field.multiple) {
35
+ const listEntry = mediaListEntryKey(path);
36
+ if (listEntry) return listEntry;
37
+ }
38
+ return pathKey(path);
39
+ }
40
+
21
41
  function valueAtPath(data: Frontmatter, path: PropertyKey[]): unknown {
22
42
  let current: unknown = data;
23
43
  for (const seg of path) {
@@ -29,24 +49,49 @@ function valueAtPath(data: Frontmatter, path: PropertyKey[]): unknown {
29
49
  return current;
30
50
  }
31
51
 
52
+ function isMediaAbsentValue(value: unknown): boolean {
53
+ if (typeof value === "string" && value.trim() === "") return true;
54
+ if (Array.isArray(value) && value.length === 0) return true;
55
+ return false;
56
+ }
57
+
58
+ function isMissingValue(value: unknown, field: FieldSnapshot | undefined): boolean {
59
+ if (field?.kind === "media") {
60
+ return value === undefined || isMediaAbsentValue(value);
61
+ }
62
+ return value === undefined;
63
+ }
64
+
32
65
  function issueMessage(
33
66
  issue: z.core.$ZodIssue | z.ZodIssue,
34
67
  model: Pick<ModelSnapshot, "fields">,
35
68
  data: Frontmatter,
36
69
  objects: ObjectSnapshot[],
37
70
  ): string | null {
38
- const key = pathKey(issue.path);
39
71
  const top = String(issue.path[0] ?? "");
40
72
  const field = fieldAtPath(model.fields, issue.path, objects) ?? model.fields[top];
41
- const missing = valueAtPath(data, issue.path) === undefined;
73
+ const key = issuePathKey(issue.path, field);
74
+ const missing = isMissingValue(valueAtPath(data, issue.path), field);
75
+ const listEntry =
76
+ field?.kind === "media" && field.multiple && typeof issue.path[issue.path.length - 1] === "number";
42
77
 
43
- if (issue.code === "too_small" || (issue.code === "invalid_type" && missing)) {
78
+ if (issue.code === "too_small" || (issue.code === "invalid_type" && missing && !listEntry)) {
79
+ if (listEntry && issue.code === "too_small") {
80
+ return `${key} must be a media URL`;
81
+ }
44
82
  return `${key} is required`;
45
83
  }
46
- if (issue.code === "custom" && issue.message.startsWith("must be")) {
84
+ if (issue.code === "custom" && issue.message.startsWith("must")) {
47
85
  return `${key} ${issue.message}`;
48
86
  }
49
87
  if (field?.kind === "media" && !missing) {
88
+ if (
89
+ field.multiple &&
90
+ !listEntry &&
91
+ !Array.isArray(valueAtPath(data, issue.path))
92
+ ) {
93
+ return `${key} must be a list of media URLs`;
94
+ }
50
95
  return `${key} must be a media URL`;
51
96
  }
52
97
  if (field) {
@@ -211,13 +256,20 @@ export function validateContentTree(input: {
211
256
  const catalog = input.catalog ?? [];
212
257
  const objects = input.objects ?? [];
213
258
  const docs = collectParsedDocs({ models: input.models, files: input.files });
214
- const relationRows = relationProblems({
215
- schema: { version: 1, models: input.models, blocks: catalog, objects },
216
- docs,
217
- });
218
- const relationByDoc = new Map(
219
- relationRows.map((row) => [`${row.type}/${row.slug}`, row.errors] as const),
220
- );
259
+ const schema = { version: 1, models: input.models, blocks: catalog, objects };
260
+ const linkRows = linkProblems({ schema, docs });
261
+ const relationRows = relationProblems({ schema, docs });
262
+ const crossDocByKey = new Map<string, string[]>();
263
+ for (const row of linkRows) {
264
+ const key = `${row.type}/${row.slug}`;
265
+ const prev = crossDocByKey.get(key) ?? [];
266
+ crossDocByKey.set(key, [...prev, ...row.errors]);
267
+ }
268
+ for (const row of relationRows) {
269
+ const key = `${row.type}/${row.slug}`;
270
+ const prev = crossDocByKey.get(key) ?? [];
271
+ crossDocByKey.set(key, [...prev, ...row.errors]);
272
+ }
221
273
 
222
274
  return input.files.map((file) => {
223
275
  const hit = matchAnyModelPath(input.models, file.path);
@@ -225,13 +277,13 @@ export function validateContentTree(input: {
225
277
  const model = input.models.find((m) => m.type === hit.type);
226
278
  if (!model) return { path: file.path, type: null, ok: true, skipped: true };
227
279
  const result = validateDocFile(model, file.raw, catalog, objects);
228
- const relationErrors = relationByDoc.get(`${hit.type}/${hit.slug}`) ?? [];
229
- if (result.ok && relationErrors.length === 0) {
280
+ const crossDocErrors = crossDocByKey.get(`${hit.type}/${hit.slug}`) ?? [];
281
+ if (result.ok && crossDocErrors.length === 0) {
230
282
  return { path: file.path, type: model.type, ok: true };
231
283
  }
232
284
  const errors = [
233
285
  ...(result.ok ? [] : result.errors),
234
- ...relationErrors,
286
+ ...crossDocErrors,
235
287
  ];
236
288
  return { path: file.path, type: model.type, ok: false, errors };
237
289
  });
@@ -0,0 +1,61 @@
1
+ // packages/core/src/validation-issue.ts
2
+
3
+ export type ValidationIssue = {
4
+ field: string | null;
5
+ message: string;
6
+ fix: string | undefined;
7
+ };
8
+
9
+ const FIELD_LINE = /^([^\s:]+) (is required|must .+|has .+)$/;
10
+
11
+ function sentence(text: string): string {
12
+ return /[.!?]$/.test(text) ? text : `${text}.`;
13
+ }
14
+
15
+ function fixFor(field: string, rest: string): string | undefined {
16
+ if (rest === "is required") return `Add a value for ${field}.`;
17
+ if (rest.includes("media URL")) return "Use a URL from the media library.";
18
+ const relation = rest.match(/^must name a (\S+) document$/);
19
+ if (relation) return `Pick an existing ${relation[1]} document.`;
20
+ return undefined;
21
+ }
22
+
23
+ /**
24
+ * Turn one line from document validation into its field, a sentence, and a
25
+ * repair. Validation keeps emitting lines, because the CLI prints them.
26
+ */
27
+ export function describeValidationError(line: string): ValidationIssue {
28
+ const parse = line.match(/^(frontmatter|JSON): (.+)/);
29
+ if (parse) {
30
+ // A YAML error continues with a code snippet. The first line says what's wrong.
31
+ const detail = parse[2]!.replace(/:$/, "");
32
+ return parse[1] === "JSON"
33
+ ? {
34
+ field: null,
35
+ message: sentence(`The file isn't valid JSON: ${detail}`),
36
+ fix: "Fix the JSON syntax.",
37
+ }
38
+ : {
39
+ field: null,
40
+ message: sentence(`The frontmatter can't be read: ${detail}`),
41
+ fix: "Fix the YAML at the top of the file.",
42
+ };
43
+ }
44
+ const unknownBlock = line.match(/^(\S+): unknown type "(.+)"$/);
45
+ if (unknownBlock) {
46
+ return {
47
+ field: unknownBlock[1]!,
48
+ message: `${unknownBlock[1]} uses an unknown block type "${unknownBlock[2]}".`,
49
+ fix: "Use a block type from the schema.",
50
+ };
51
+ }
52
+ const fieldLine = line.match(FIELD_LINE);
53
+ if (fieldLine) {
54
+ return {
55
+ field: fieldLine[1]!,
56
+ message: sentence(line),
57
+ fix: fixFor(fieldLine[1]!, fieldLine[2]!),
58
+ };
59
+ }
60
+ return { field: null, message: sentence(line), fix: undefined };
61
+ }
package/src/zod.ts CHANGED
@@ -27,6 +27,7 @@ export function expectedTypeFor(
27
27
  case "image":
28
28
  case "media":
29
29
  case "relation":
30
+ case "link":
30
31
  return "string";
31
32
  default: {
32
33
  const _exhaustive: never = kind;
@@ -53,6 +54,8 @@ export function exampleValueFor(kind: FieldKind): unknown {
53
54
  return "https://cdn.backmatter.app/img/med_018f6b3e-7c2a-7b1d-8e4f-9a0b1c2d3e4f";
54
55
  case "relation":
55
56
  return "related-slug";
57
+ case "link":
58
+ return "/page";
56
59
  case "text":
57
60
  return "";
58
61
  default: {
@@ -164,13 +167,40 @@ function fieldZod(field: FieldSnapshot, ctx: ZodBuildContext): z.ZodType {
164
167
  return field.required ? arr : arr.optional();
165
168
  }
166
169
  if (field.kind === "media") {
170
+ const absentMedia = (value: unknown) => {
171
+ if (typeof value === "string" && value.trim() === "") return undefined;
172
+ if (Array.isArray(value) && value.length === 0) return undefined;
173
+ return value;
174
+ };
175
+ const asAbsent = <T extends z.ZodType>(schema: T) => z.preprocess(absentMedia, schema);
176
+ if (field.multiple) {
177
+ const entry = z
178
+ .string()
179
+ .trim()
180
+ .min(1)
181
+ .refine((value) => mediaIdFromUrl(value) !== null);
182
+ const arr = z.array(entry).superRefine((values, ctx) => {
183
+ const seen = new Set<string>();
184
+ for (const value of values) {
185
+ const trimmed = value.trim();
186
+ if (seen.has(trimmed)) {
187
+ ctx.addIssue({ code: "custom", message: "must not repeat a media URL" });
188
+ return;
189
+ }
190
+ seen.add(trimmed);
191
+ }
192
+ });
193
+ return asAbsent(field.required ? arr.min(1) : arr.optional());
194
+ }
167
195
  const url = z.string().refine((value) => value.trim() === "" || mediaIdFromUrl(value) !== null);
168
- if (!field.required) return url.optional();
169
- return z
170
- .string()
171
- .trim()
172
- .min(1)
173
- .refine((value) => mediaIdFromUrl(value) !== null);
196
+ if (!field.required) return asAbsent(url.optional());
197
+ return asAbsent(
198
+ z
199
+ .string()
200
+ .trim()
201
+ .min(1)
202
+ .refine((value) => mediaIdFromUrl(value) !== null),
203
+ );
174
204
  }
175
205
  let base: z.ZodType;
176
206
  switch (expectedTypeFor(field.kind)) {
@@ -241,6 +271,7 @@ export function fieldAtPath(
241
271
  if (i === path.length - 1) return current;
242
272
  const next = path[i + 1];
243
273
  if (typeof next === "number") {
274
+ if (current.kind === "media" && current.multiple) return current;
244
275
  if (current.kind !== "array") return undefined;
245
276
  const itemFields = objectFieldsFor(current, { objects, objectSchemas: new Map() });
246
277
  if (!itemFields) return undefined;