@backmatter/core 0.0.33 → 0.0.35

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/src/validate.ts CHANGED
@@ -1,16 +1,105 @@
1
1
  // packages/core/src/validate.ts
2
+ import { z } from "zod";
2
3
  import { modelFormat, parseDoc } from "./doc-format";
3
- import type { Frontmatter } from "./mdx";
4
+ import { linkProblems } from "./link-problems";
5
+ import { relationProblems } from "./relation-problems";
6
+ import type { FieldSnapshot } from "./fields";
4
7
  import { parseMdx } from "./mdx";
8
+ import type { Frontmatter } from "./mdx";
5
9
  import type { ModelSnapshot } from "./model";
6
10
  import type { BlockInstance, BlockSnapshot } from "./block";
11
+ import type { ObjectSnapshot } from "./object";
7
12
  import { matchAnyModelPath } from "./path";
8
- import { expectedTypeFor, frontmatterZod, normalizeFrontmatter } from "./zod";
13
+ import { expectedTypeFor, fieldAtPath, frontmatterZod, normalizeFrontmatter } from "./zod";
9
14
 
10
15
  export type ValidationResult =
11
16
  | { ok: true }
12
17
  | { ok: false; errors: string[] };
13
18
 
19
+ function pathKey(path: PropertyKey[]): string {
20
+ return path.map(String).join(".");
21
+ }
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
+
41
+ function valueAtPath(data: Frontmatter, path: PropertyKey[]): unknown {
42
+ let current: unknown = data;
43
+ for (const seg of path) {
44
+ if (current === null || current === undefined || typeof current !== "object") {
45
+ return undefined;
46
+ }
47
+ current = (current as Record<string, unknown>)[String(seg)];
48
+ }
49
+ return current;
50
+ }
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
+
65
+ function issueMessage(
66
+ issue: z.core.$ZodIssue | z.ZodIssue,
67
+ model: Pick<ModelSnapshot, "fields">,
68
+ data: Frontmatter,
69
+ objects: ObjectSnapshot[],
70
+ ): string | null {
71
+ const top = String(issue.path[0] ?? "");
72
+ const field = fieldAtPath(model.fields, issue.path, objects) ?? model.fields[top];
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";
77
+
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
+ }
82
+ return `${key} is required`;
83
+ }
84
+ if (issue.code === "custom" && issue.message.startsWith("must")) {
85
+ return `${key} ${issue.message}`;
86
+ }
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
+ }
95
+ return `${key} must be a media URL`;
96
+ }
97
+ if (field) {
98
+ return `${key} must be a ${expectedTypeFor(field.kind)}`;
99
+ }
100
+ return null;
101
+ }
102
+
14
103
  /**
15
104
  * Frontmatter must satisfy the model: required fields present and non-blank,
16
105
  * every declared field of the right primitive type. Unknown keys are ignored.
@@ -18,26 +107,23 @@ export type ValidationResult =
18
107
  export function validateFrontmatter(
19
108
  model: Pick<ModelSnapshot, "fields">,
20
109
  frontmatter: Frontmatter,
110
+ objects: ObjectSnapshot[] = [],
21
111
  ): ValidationResult {
22
112
  const data = normalizeFrontmatter(frontmatter);
23
- const result = frontmatterZod(model).safeParse(data);
113
+ const result = frontmatterZod(model, objects).safeParse(data);
24
114
  if (result.success) return { ok: true };
25
115
 
26
116
  const errors: string[] = [];
27
117
  const seen = new Set<string>();
28
118
  for (const issue of result.error.issues) {
29
- const name = String(issue.path[0] ?? "");
30
- const field = model.fields[name];
31
- if (!field || seen.has(name)) continue;
32
- seen.add(name);
33
- const missing = data[name] === undefined;
34
- if (issue.code === "too_small" || (issue.code === "invalid_type" && missing)) {
35
- errors.push(`${name} is required`);
36
- } else if (field.kind === "media" && !missing) {
37
- errors.push(`${name} must be a media URL`);
38
- } else {
39
- errors.push(`${name} must be a ${expectedTypeFor(field.kind)}`);
40
- }
119
+ const key = pathKey(issue.path);
120
+ if (!key || seen.has(key)) continue;
121
+ const top = String(issue.path[0] ?? "");
122
+ if (!model.fields[top] && issue.path.length === 1) continue;
123
+ const msg = issueMessage(issue, model, data, objects);
124
+ if (!msg) continue;
125
+ seen.add(key);
126
+ errors.push(msg);
41
127
  }
42
128
  // Never fail open: if every issue was filtered above, still report invalid.
43
129
  // Unreachable through the public API today (normalizeFrontmatter always yields
@@ -61,6 +147,7 @@ export function validateBlocks(
61
147
  blocks: unknown,
62
148
  catalog: BlockSnapshot[],
63
149
  prefix = "blocks",
150
+ objects: ObjectSnapshot[] = [],
64
151
  ): ValidationResult {
65
152
  if (!Array.isArray(blocks)) return { ok: true };
66
153
  const byName = new Map(catalog.map((b) => [b.name, b]));
@@ -72,7 +159,7 @@ export function validateBlocks(
72
159
  return;
73
160
  }
74
161
  const props = block.props && typeof block.props === "object" ? block.props : {};
75
- const result = validateFrontmatter({ fields: def.fields }, props);
162
+ const result = validateFrontmatter({ fields: def.fields }, props, objects);
76
163
  if (!result.ok) {
77
164
  for (const err of result.errors) {
78
165
  errors.push(`${prefix}[${i}].${err}`);
@@ -90,6 +177,7 @@ export function validateBlocks(
90
177
  export function validateMdxFile(
91
178
  model: Pick<ModelSnapshot, "fields">,
92
179
  raw: string,
180
+ objects: ObjectSnapshot[] = [],
93
181
  ): ValidationResult {
94
182
  let frontmatter: Frontmatter;
95
183
  try {
@@ -98,13 +186,14 @@ export function validateMdxFile(
98
186
  const msg = err instanceof Error ? err.message : "invalid";
99
187
  return { ok: false, errors: [`frontmatter: ${msg}`] };
100
188
  }
101
- return validateFrontmatter(model, frontmatter);
189
+ return validateFrontmatter(model, frontmatter, objects);
102
190
  }
103
191
 
104
192
  export function validateDocFile(
105
193
  model: Pick<ModelSnapshot, "fields" | "format">,
106
194
  raw: string,
107
195
  catalog: BlockSnapshot[] = [],
196
+ objects: ObjectSnapshot[] = [],
108
197
  ): ValidationResult {
109
198
  const format = modelFormat(model);
110
199
  let frontmatter: Frontmatter;
@@ -115,11 +204,16 @@ export function validateDocFile(
115
204
  const label = format === "page" ? "JSON" : "frontmatter";
116
205
  return { ok: false, errors: [msg.startsWith("JSON:") ? msg : `${label}: ${msg}`] };
117
206
  }
118
- const base = validateFrontmatter(model, frontmatter);
207
+ const base = validateFrontmatter(model, frontmatter, objects);
119
208
  if (format !== "page") return base;
120
209
  const blockField = Object.entries(model.fields).find(([, f]) => f.kind === "blocks");
121
210
  if (!blockField) return base;
122
- const blockResult = validateBlocks(frontmatter[blockField[0]], catalog, blockField[0]);
211
+ const blockResult = validateBlocks(
212
+ frontmatter[blockField[0]],
213
+ catalog,
214
+ blockField[0],
215
+ objects,
216
+ );
123
217
  if (base.ok && blockResult.ok) return { ok: true };
124
218
  return {
125
219
  ok: false,
@@ -132,20 +226,65 @@ export type ContentFileResult =
132
226
  | { path: string; type: string; ok: false; errors: string[] }
133
227
  | { path: string; type: null; ok: true; skipped: true };
134
228
 
229
+ function collectParsedDocs(input: {
230
+ models: ModelSnapshot[];
231
+ files: Array<{ path: string; raw: string }>;
232
+ }): Array<{ type: string; slug: string; frontmatter: Frontmatter }> {
233
+ const docs: Array<{ type: string; slug: string; frontmatter: Frontmatter }> = [];
234
+ for (const file of input.files) {
235
+ const hit = matchAnyModelPath(input.models, file.path);
236
+ if (!hit) continue;
237
+ const model = input.models.find((m) => m.type === hit.type);
238
+ if (!model) continue;
239
+ try {
240
+ const { frontmatter } = parseDoc(file.raw, modelFormat(model));
241
+ docs.push({ type: hit.type, slug: hit.slug, frontmatter });
242
+ } catch {
243
+ // Unparseable files are skipped for the relation pass.
244
+ }
245
+ }
246
+ return docs;
247
+ }
248
+
135
249
  /** Validate many repo-relative files against a model set. Order is preserved. */
136
250
  export function validateContentTree(input: {
137
251
  models: ModelSnapshot[];
138
252
  files: Array<{ path: string; raw: string }>;
139
253
  catalog?: BlockSnapshot[];
254
+ objects?: ObjectSnapshot[];
140
255
  }): ContentFileResult[] {
141
256
  const catalog = input.catalog ?? [];
257
+ const objects = input.objects ?? [];
258
+ const docs = collectParsedDocs({ models: input.models, files: input.files });
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
+ }
273
+
142
274
  return input.files.map((file) => {
143
275
  const hit = matchAnyModelPath(input.models, file.path);
144
276
  if (!hit) return { path: file.path, type: null, ok: true, skipped: true };
145
277
  const model = input.models.find((m) => m.type === hit.type);
146
278
  if (!model) return { path: file.path, type: null, ok: true, skipped: true };
147
- const result = validateDocFile(model, file.raw, catalog);
148
- if (result.ok) return { path: file.path, type: model.type, ok: true };
149
- return { path: file.path, type: model.type, ok: false, errors: result.errors };
279
+ const result = validateDocFile(model, file.raw, catalog, objects);
280
+ const crossDocErrors = crossDocByKey.get(`${hit.type}/${hit.slug}`) ?? [];
281
+ if (result.ok && crossDocErrors.length === 0) {
282
+ return { path: file.path, type: model.type, ok: true };
283
+ }
284
+ const errors = [
285
+ ...(result.ok ? [] : result.errors),
286
+ ...crossDocErrors,
287
+ ];
288
+ return { path: file.path, type: model.type, ok: false, errors };
150
289
  });
151
290
  }
package/src/zod.ts CHANGED
@@ -1,9 +1,13 @@
1
1
  // packages/core/src/zod.ts
2
2
  import { z } from "zod";
3
+ import { isColorString } from "./color";
3
4
  import type { FieldKind, FieldSnapshot } from "./fields";
4
5
  import { mediaIdFromUrl } from "./media-url";
5
6
  import type { Frontmatter } from "./mdx";
6
7
  import type { ModelSnapshot } from "./model";
8
+ import type { ObjectSnapshot } from "./object";
9
+
10
+ const STEP_EPS = 1e-9;
7
11
 
8
12
  /** Primitive a field kind is stored as in frontmatter; used in error messages. */
9
13
  export function expectedTypeFor(
@@ -23,6 +27,7 @@ export function expectedTypeFor(
23
27
  case "image":
24
28
  case "media":
25
29
  case "relation":
30
+ case "link":
26
31
  return "string";
27
32
  default: {
28
33
  const _exhaustive: never = kind;
@@ -49,6 +54,8 @@ export function exampleValueFor(kind: FieldKind): unknown {
49
54
  return "https://cdn.backmatter.app/img/med_018f6b3e-7c2a-7b1d-8e4f-9a0b1c2d3e4f";
50
55
  case "relation":
51
56
  return "related-slug";
57
+ case "link":
58
+ return "/page";
52
59
  case "text":
53
60
  return "";
54
61
  default: {
@@ -58,16 +65,90 @@ export function exampleValueFor(kind: FieldKind): unknown {
58
65
  }
59
66
  }
60
67
 
61
- function objectZod(field: FieldSnapshot): z.ZodType {
62
- if (!field.fields) return z.record(z.string(), z.unknown());
68
+ type ZodBuildContext = {
69
+ objects: ObjectSnapshot[];
70
+ objectSchemas: Map<string, z.ZodType>;
71
+ };
72
+
73
+ function objectFieldsFor(field: FieldSnapshot, ctx: ZodBuildContext): Record<string, FieldSnapshot> | undefined {
74
+ if (field.fields) return field.fields;
75
+ if (!field.object) return undefined;
76
+ const def = ctx.objects.find((o) => o.name === field.object);
77
+ return def?.fields;
78
+ }
79
+
80
+ function objectZod(field: FieldSnapshot, ctx: ZodBuildContext): z.ZodType {
81
+ const nested = objectFieldsFor(field, ctx);
82
+ if (!nested) return z.record(z.string(), z.unknown());
83
+ if (field.object && !field.fields) {
84
+ return namedObjectZod(field.object, nested, ctx);
85
+ }
63
86
  const shape: Record<string, z.ZodType> = {};
64
- for (const [name, nested] of Object.entries(field.fields)) {
65
- shape[name] = fieldZod(nested);
87
+ for (const [name, child] of Object.entries(nested)) {
88
+ shape[name] = fieldZod(child, ctx);
66
89
  }
67
90
  return z.looseObject(shape);
68
91
  }
69
92
 
70
- function fieldZod(field: FieldSnapshot): z.ZodType {
93
+ function namedObjectZod(
94
+ name: string,
95
+ fields: Record<string, FieldSnapshot>,
96
+ ctx: ZodBuildContext,
97
+ ): z.ZodType {
98
+ const cached = ctx.objectSchemas.get(name);
99
+ if (cached) return cached;
100
+ const schema = z.lazy(() => {
101
+ const shape: Record<string, z.ZodType> = {};
102
+ for (const [key, nested] of Object.entries(fields)) {
103
+ shape[key] = fieldZod(nested, ctx);
104
+ }
105
+ return z.looseObject(shape);
106
+ });
107
+ ctx.objectSchemas.set(name, schema);
108
+ return schema;
109
+ }
110
+
111
+ function applyNumberConstraints(field: FieldSnapshot, base: z.ZodNumber): z.ZodType {
112
+ const { min, max, step } = field;
113
+ if (typeof min !== "number" || typeof max !== "number") return base;
114
+ return base.superRefine((value, ctx) => {
115
+ if (!Number.isFinite(value) || value < min || value > max) {
116
+ ctx.addIssue({ code: "custom", message: `must be between ${min} and ${max}` });
117
+ return;
118
+ }
119
+ if (step !== undefined) {
120
+ const offset = (value - min) / step;
121
+ const n = Math.round(offset);
122
+ if (Math.abs(offset - n) > STEP_EPS || n < 0) {
123
+ ctx.addIssue({ code: "custom", message: `must be a step of ${step} from ${min}` });
124
+ }
125
+ }
126
+ });
127
+ }
128
+
129
+ function applyStringConstraints(field: FieldSnapshot, base: z.ZodString): z.ZodType {
130
+ let out: z.ZodType = base;
131
+ if (field.options && field.options.length > 0) {
132
+ const options = field.options;
133
+ out = out.superRefine((value, ctx) => {
134
+ if (typeof value !== "string" || value.trim() === "") return;
135
+ if (!options.includes(value)) {
136
+ ctx.addIssue({ code: "custom", message: `must be one of ${options.join(", ")}` });
137
+ }
138
+ });
139
+ }
140
+ if (field.input === "color") {
141
+ out = out.superRefine((value, ctx) => {
142
+ if (typeof value !== "string" || value.trim() === "") return;
143
+ if (!isColorString(value.trim())) {
144
+ ctx.addIssue({ code: "custom", message: "must be a color" });
145
+ }
146
+ });
147
+ }
148
+ return out;
149
+ }
150
+
151
+ function fieldZod(field: FieldSnapshot, ctx: ZodBuildContext): z.ZodType {
71
152
  if (field.kind === "blocks") {
72
153
  const item = z.object({
73
154
  id: z.string().min(1),
@@ -78,26 +159,53 @@ function fieldZod(field: FieldSnapshot): z.ZodType {
78
159
  return arr;
79
160
  }
80
161
  if (field.kind === "object") {
81
- const obj = objectZod(field);
162
+ const obj = objectZod(field, ctx);
82
163
  return field.required ? obj : obj.optional();
83
164
  }
84
165
  if (field.kind === "array") {
85
- const arr = z.array(objectZod(field));
166
+ const arr = z.array(objectZod(field, ctx));
86
167
  return field.required ? arr : arr.optional();
87
168
  }
88
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
+ }
89
195
  const url = z.string().refine((value) => value.trim() === "" || mediaIdFromUrl(value) !== null);
90
- if (!field.required) return url.optional();
91
- return z
92
- .string()
93
- .trim()
94
- .min(1)
95
- .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
+ );
96
204
  }
97
205
  let base: z.ZodType;
98
206
  switch (expectedTypeFor(field.kind)) {
99
207
  case "number":
100
- base = z.number();
208
+ base = applyNumberConstraints(field, z.number());
101
209
  break;
102
210
  case "boolean":
103
211
  base = z.boolean();
@@ -105,6 +213,7 @@ function fieldZod(field: FieldSnapshot): z.ZodType {
105
213
  default:
106
214
  // Required strings must be non-blank; trim happens before min(1).
107
215
  base = field.required ? z.string().trim().min(1) : z.string();
216
+ base = applyStringConstraints(field, base as z.ZodString);
108
217
  }
109
218
  return field.required ? base : base.optional();
110
219
  }
@@ -113,10 +222,14 @@ function fieldZod(field: FieldSnapshot): z.ZodType {
113
222
  * Zod object for a model's frontmatter.
114
223
  * Loose: keys not in the model pass through untouched (drift is not an error).
115
224
  */
116
- export function frontmatterZod(model: Pick<ModelSnapshot, "fields">) {
225
+ export function frontmatterZod(
226
+ model: Pick<ModelSnapshot, "fields">,
227
+ objects: ObjectSnapshot[] = [],
228
+ ) {
229
+ const ctx: ZodBuildContext = { objects, objectSchemas: new Map() };
117
230
  const shape: Record<string, z.ZodType> = {};
118
231
  for (const [name, field] of Object.entries(model.fields)) {
119
- shape[name] = fieldZod(field);
232
+ shape[name] = fieldZod(field, ctx);
120
233
  }
121
234
  return z.looseObject(shape);
122
235
  }
@@ -141,3 +254,38 @@ export function frontmatterJsonSchema(model: ModelSnapshot): FrontmatterJsonSche
141
254
  });
142
255
  return { ...schema, title: model.type };
143
256
  }
257
+
258
+ /** Resolve the field definition for a Zod issue path (for error messages). */
259
+ export function fieldAtPath(
260
+ rootFields: Record<string, FieldSnapshot>,
261
+ path: PropertyKey[],
262
+ objects: ObjectSnapshot[],
263
+ ): FieldSnapshot | undefined {
264
+ let fields = rootFields;
265
+ let current: FieldSnapshot | undefined;
266
+ for (let i = 0; i < path.length; i++) {
267
+ const seg = path[i];
268
+ if (typeof seg === "number") continue;
269
+ current = fields[String(seg)];
270
+ if (!current) return undefined;
271
+ if (i === path.length - 1) return current;
272
+ const next = path[i + 1];
273
+ if (typeof next === "number") {
274
+ if (current.kind === "media" && current.multiple) return current;
275
+ if (current.kind !== "array") return undefined;
276
+ const itemFields = objectFieldsFor(current, { objects, objectSchemas: new Map() });
277
+ if (!itemFields) return undefined;
278
+ fields = itemFields;
279
+ i += 1;
280
+ continue;
281
+ }
282
+ if (current.kind === "object" || current.kind === "array") {
283
+ const nested = objectFieldsFor(current, { objects, objectSchemas: new Map() });
284
+ if (!nested) return undefined;
285
+ fields = nested;
286
+ } else {
287
+ return undefined;
288
+ }
289
+ }
290
+ return current;
291
+ }