@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/query.ts CHANGED
@@ -1,6 +1,6 @@
1
- // packages/core/src/query.ts
1
+ import type { BlockDef } from "./block";
2
2
  import type { BackmatterDoc, BackmatterDocSummary } from "./doc";
3
- import type { FieldKind } from "./fields";
3
+ import type { FieldDef, FieldKind } from "./fields";
4
4
  import { IMPLICIT_SINGLETON_SLUG, type InferFrontmatter, type ModelDef } from "./model";
5
5
  import { normalizeFrontmatter } from "./zod";
6
6
 
@@ -10,11 +10,6 @@ export type DocLoader = {
10
10
  getDoc(type: string, slug: string): Promise<BackmatterDoc | null>;
11
11
  };
12
12
 
13
- export type TypedDoc<M extends ModelDef> = Omit<BackmatterDoc, "type" | "frontmatter"> & {
14
- type: M["type"];
15
- frontmatter: InferFrontmatter<M>;
16
- };
17
-
18
13
  type KeysOfKind<M extends ModelDef, K extends FieldKind> = {
19
14
  [N in keyof M["fields"]]: M["fields"][N]["kind"] extends K ? N : never;
20
15
  }[keyof M["fields"]];
@@ -29,52 +24,421 @@ export type Where<M extends ModelDef> = Partial<
29
24
  >
30
25
  >;
31
26
 
32
- /** Relation fields that may be resolved (depth 1). */
33
- export type Include<M extends ModelDef> = Partial<Record<KeysOfKind<M, "relation">, true>>;
27
+ type Simplify<T> = { -readonly [K in keyof T]: T[K] } & {};
28
+
29
+ type IsRequired<F> = F extends { required?: infer R }
30
+ ? [Exclude<R, undefined>] extends [true]
31
+ ? true
32
+ : false
33
+ : false;
34
+
35
+ type RelationMode = "load" | "slug";
36
+
37
+ type ModelByType<Models extends readonly ModelDef[], Type extends string> = Extract<
38
+ Models[number],
39
+ { type: Type }
40
+ >;
41
+
42
+ /** `true` selects the stored field. An object on an object or array field is a cut. A relation object is one hop. A blocks field is only `true`. */
43
+ type FieldChoice<Models extends readonly ModelDef[], F, Mode extends RelationMode> = F extends {
44
+ kind: "blocks";
45
+ }
46
+ ? true
47
+ : F extends {
48
+ kind: "object" | "array";
49
+ fields: infer Fields;
50
+ }
51
+ ? true | NestedSelect<Models, Fields, Mode>
52
+ : F extends { kind: "relation" }
53
+ ? RelationChoice<Models, F, Mode>
54
+ : true;
55
+
56
+ type NestedSelect<Models extends readonly ModelDef[], Fields, Mode extends RelationMode> = {
57
+ [K in keyof Fields]?: FieldChoice<Models, Fields[K], Mode>;
58
+ };
59
+
60
+ /** `relationTo` is optional on `FieldDef`, so a direct `{ relationTo: infer To extends string }` does not match. */
61
+ type RelationToOf<F> = F extends { relationTo?: infer To } ? Extract<To, string> : never;
62
+
63
+ type RelationTargetChoice<Models extends readonly ModelDef[], To extends string> =
64
+ ModelByType<Models, To> extends infer Target
65
+ ? [Target] extends [never]
66
+ ? true
67
+ : Target extends { external: true }
68
+ ? true
69
+ : Target extends ModelDef
70
+ ? true | SelectShape<Models, Target, "slug">
71
+ : true
72
+ : true;
73
+
74
+ type RelationChoice<Models extends readonly ModelDef[], F, Mode extends RelationMode> = Mode extends "slug"
75
+ ? true
76
+ : RelationToOf<F> extends infer To
77
+ ? [To] extends [never]
78
+ ? true
79
+ : To extends string
80
+ ? RelationTargetChoice<Models, To>
81
+ : true
82
+ : true;
34
83
 
35
- type RelationTarget<
84
+ type SelectShape<
85
+ Models extends readonly ModelDef[],
36
86
  M extends ModelDef,
37
- N extends keyof M["fields"],
87
+ Mode extends RelationMode = "load",
88
+ > = Simplify<
89
+ {
90
+ [K in keyof M["fields"]]?: FieldChoice<Models, M["fields"][K], Mode>;
91
+ } & (M extends { format: "page" } ? object : { body?: true })
92
+ >;
93
+
94
+ type SelectValue<
38
95
  Models extends readonly ModelDef[],
39
- > = M["fields"][N] extends { relationTo?: infer To }
40
- ? Extract<Models[number], { type: Exclude<To, undefined> }>
41
- : never;
96
+ M extends ModelDef,
97
+ P extends PropertyKey,
98
+ Mode extends RelationMode = "load",
99
+ > = P extends "body"
100
+ ? true
101
+ : P extends keyof M["fields"]
102
+ ? FieldChoice<Models, M["fields"][P], Mode>
103
+ : never;
42
104
 
43
- export type Resolved<
105
+ /** One or more known keys. An empty object is `never`. */
106
+ type SelectArg<
107
+ Models extends readonly ModelDef[],
44
108
  M extends ModelDef,
109
+ K extends PropertyKey,
110
+ Mode extends RelationMode = "load",
111
+ > = [K] extends [never] ? never : { [P in K]: SelectValue<Models, M, P, Mode> };
112
+
113
+ type StoredOf<F, Blocks extends readonly BlockDef[]> = F extends { kind: "number" }
114
+ ? number
115
+ : F extends { kind: "boolean" }
116
+ ? boolean
117
+ : F extends { kind: "blocks" }
118
+ ? BlockValue<Blocks>
119
+ : F extends { kind: "object"; fields: infer Fields }
120
+ ? ObjectShape<Fields, Blocks>
121
+ : F extends { kind: "array"; fields: infer Fields }
122
+ ? ObjectShape<Fields, Blocks>[]
123
+ : F extends { kind: "media"; multiple: true }
124
+ ? string[]
125
+ : F extends { options: infer O extends readonly [string, ...string[]] }
126
+ ? O[number]
127
+ : string;
128
+
129
+ type ObjectShape<Fields, Blocks extends readonly BlockDef[]> = Simplify<
130
+ {
131
+ [K in keyof Fields as IsRequired<Fields[K]> extends true ? K : never]: StoredOf<Fields[K], Blocks>;
132
+ } & {
133
+ [K in keyof Fields as IsRequired<Fields[K]> extends true ? never : K]?: StoredOf<Fields[K], Blocks>;
134
+ }
135
+ >;
136
+
137
+ /** One stored block. An empty `Blocks` has no members, so the value is `never[]`. */
138
+ type BlockValue<Blocks extends readonly BlockDef[]> = [Blocks[number]] extends [never]
139
+ ? never[]
140
+ : Array<
141
+ Blocks[number] extends infer B
142
+ ? B extends { name: infer Name extends string; fields: infer Fields }
143
+ ? { id: string; type: Name; props: ObjectShape<Fields, Blocks> }
144
+ : never
145
+ : never
146
+ >;
147
+
148
+ /** A relation object is always present: the loaded cut, or `null` when the slug cannot be loaded. */
149
+ type RelationObject<F, Sel> = F extends { kind: "relation" }
150
+ ? Sel extends true
151
+ ? false
152
+ : Sel extends readonly unknown[]
153
+ ? false
154
+ : Sel extends object
155
+ ? true
156
+ : false
157
+ : false;
158
+
159
+ type KeyRequired<F, Sel> = RelationObject<F, Sel> extends true ? true : IsRequired<F>;
160
+
161
+ type RelationLoaded<Models extends readonly ModelDef[], F, Sel, Blocks extends readonly BlockDef[]> =
162
+ RelationToOf<F> extends infer To
163
+ ? [To] extends [never]
164
+ ? null
165
+ : To extends string
166
+ ? ModelByType<Models, To> extends infer Target
167
+ ? [Target] extends [never]
168
+ ? null
169
+ : Target extends { external: true }
170
+ ? null
171
+ : Target extends ModelDef
172
+ ? SelectionOf<Models, Target, Sel, "slug", Blocks> | null
173
+ : null
174
+ : null
175
+ : null
176
+ : null;
177
+
178
+ type ValueAt<
179
+ Models extends readonly ModelDef[],
180
+ F,
181
+ Sel,
182
+ Mode extends RelationMode,
183
+ Blocks extends readonly BlockDef[],
184
+ > = Sel extends true
185
+ ? StoredOf<F, Blocks>
186
+ : Sel extends readonly unknown[]
187
+ ? never
188
+ : Sel extends object
189
+ ? F extends { kind: "object"; fields: infer Fields }
190
+ ? CutShape<Models, Fields, Sel, Mode, Blocks>
191
+ : F extends { kind: "array"; fields: infer Fields }
192
+ ? CutShape<Models, Fields, Sel, Mode, Blocks>[]
193
+ : F extends { kind: "relation" }
194
+ ? Mode extends "slug"
195
+ ? never
196
+ : RelationLoaded<Models, F, Sel, Blocks>
197
+ : never
198
+ : never;
199
+
200
+ type CutShape<
45
201
  Models extends readonly ModelDef[],
46
- I extends Include<M>,
202
+ Fields,
203
+ Sel,
204
+ Mode extends RelationMode,
205
+ Blocks extends readonly BlockDef[],
206
+ > = Simplify<
207
+ {
208
+ [K in keyof Sel & keyof Fields as KeyRequired<Fields[K], Sel[K]> extends true ? K : never]: ValueAt<
209
+ Models,
210
+ Fields[K],
211
+ Sel[K],
212
+ Mode,
213
+ Blocks
214
+ >;
215
+ } & {
216
+ [K in keyof Sel & keyof Fields as KeyRequired<Fields[K], Sel[K]> extends true ? never : K]?: ValueAt<
217
+ Models,
218
+ Fields[K],
219
+ Sel[K],
220
+ Mode,
221
+ Blocks
222
+ >;
223
+ }
224
+ >;
225
+
226
+ type SelectionOf<
227
+ Models extends readonly ModelDef[],
228
+ M extends ModelDef,
229
+ Sel,
230
+ Mode extends RelationMode = "load",
231
+ Blocks extends readonly BlockDef[] = [],
232
+ > = Simplify<
233
+ { slug: string } &
234
+ ("body" extends keyof Sel ? (M extends { format: "page" } ? object : { body: string }) : object) &
235
+ CutShape<Models, M["fields"], Sel, Mode, Blocks>
236
+ >;
237
+
238
+ type SelectFor<
239
+ Models extends readonly ModelDef[],
240
+ M extends ModelDef,
241
+ K extends PropertyKey,
242
+ Mode extends RelationMode = "load",
47
243
  > = {
48
- [N in keyof I as I[N] extends true ? N : never]: N extends keyof M["fields"]
49
- ? TypedDoc<RelationTarget<M, N, Models>> | null
50
- : never;
244
+ [P in K]: SelectValue<Models, M, P, Mode>;
51
245
  };
52
246
 
53
- type ModelGet<M extends ModelDef> = M["singleton"] extends true
54
- ? () => Promise<TypedDoc<M> | null>
55
- : (slug: string) => Promise<TypedDoc<M> | null>;
247
+ type ModelGet<Models extends readonly ModelDef[], M extends ModelDef, Blocks extends readonly BlockDef[]> =
248
+ M["singleton"] extends true
249
+ ? <const K extends keyof SelectShape<Models, M>, const S extends SelectArg<Models, M, K>>(
250
+ select: SelectFor<Models, M, K> & S,
251
+ ) => Promise<SelectionOf<Models, M, S, "load", Blocks> | null>
252
+ : <const K extends keyof SelectShape<Models, M>, const S extends SelectArg<Models, M, K>>(
253
+ slug: string,
254
+ select: SelectFor<Models, M, K> & S,
255
+ ) => Promise<SelectionOf<Models, M, S, "load", Blocks> | null>;
56
256
 
57
- export type ModelQuery<M extends ModelDef, Models extends readonly ModelDef[]> = {
58
- get: ModelGet<M>;
59
- findMany<I extends Include<M> = {}>(opts?: {
257
+ export type ModelQuery<
258
+ M extends ModelDef,
259
+ Models extends readonly ModelDef[] = readonly [M],
260
+ Blocks extends readonly BlockDef[] = [],
261
+ > = {
262
+ get: ModelGet<Models, M, Blocks>;
263
+ findMany<const K extends keyof SelectShape<Models, M>, const S extends SelectArg<Models, M, K>>(opts: {
60
264
  where?: Where<M>;
61
- include?: I;
62
- }): Promise<Array<TypedDoc<M> & Resolved<M, Models, I>>>;
265
+ select: SelectFor<Models, M, K> & S;
266
+ }): Promise<Array<SelectionOf<Models, M, S, "load", Blocks>>>;
63
267
  };
64
268
 
65
- export type Query<Models extends readonly ModelDef[]> = {
66
- [M in Models[number] as M["type"]]: ModelQuery<M, Models>;
269
+ export type Query<Models extends readonly ModelDef[], Blocks extends readonly BlockDef[] = []> = {
270
+ [M in Models[number] as M["type"]]: ModelQuery<M, Models, Blocks>;
67
271
  };
68
272
 
69
273
  type RawOpts = {
70
274
  where?: Record<string, unknown>;
71
- include?: Record<string, boolean | undefined>;
275
+ select: Record<string, unknown>;
72
276
  };
73
277
 
74
- export function createQuery<const Models extends readonly ModelDef[]>(
75
- models: Models,
76
- loader: DocLoader,
77
- ): Query<Models> {
278
+ function isRecord(value: unknown): value is Record<string, unknown> {
279
+ return typeof value === "object" && value !== null && !Array.isArray(value);
280
+ }
281
+
282
+ function withoutBody(select: Record<string, unknown>): Record<string, unknown> {
283
+ if (!("body" in select)) return select;
284
+ const rest = { ...select };
285
+ delete rest.body;
286
+ return rest;
287
+ }
288
+
289
+ /** A blocks `true` keeps the stored array and does not walk `props`. Anything else is omitted. */
290
+ function storedBlockArray(value: unknown): unknown[] | undefined {
291
+ return Array.isArray(value) ? value : undefined;
292
+ }
293
+
294
+ type LoadDoc = (type: string, slug: string) => Promise<BackmatterDoc | null>;
295
+
296
+ /** One file-backed hop. A missing slug or file is `null`. A hopped relation is not loaded. */
297
+ function queueRelation(
298
+ out: Record<string, unknown>,
299
+ loads: Promise<void>[],
300
+ key: string,
301
+ field: FieldDef,
302
+ storedValue: unknown,
303
+ wanted: Record<string, unknown>,
304
+ load: LoadDoc,
305
+ models: Map<string, ModelDef>,
306
+ ) {
307
+ const slug = relationSlug(storedValue);
308
+ const relationTo = field.relationTo;
309
+ const target = relationTo ? models.get(relationTo) : undefined;
310
+ if (!slug || !relationTo || !target || target.external === true) {
311
+ out[key] = null;
312
+ return;
313
+ }
314
+ loads.push(
315
+ load(relationTo, slug).then(async (related) => {
316
+ out[key] = related ? await selected(target, related, wanted, load, models, true) : null;
317
+ }),
318
+ );
319
+ }
320
+
321
+ /** Cut `stored` to `select`. A missing value or an empty cut is omitted. `true` copies the stored leaf. */
322
+ async function cutFields(
323
+ fields: Record<string, FieldDef> | undefined,
324
+ stored: Record<string, unknown>,
325
+ select: Record<string, unknown>,
326
+ load: LoadDoc,
327
+ models: Map<string, ModelDef>,
328
+ hopped: boolean,
329
+ ): Promise<Record<string, unknown> | undefined> {
330
+ const out: Record<string, unknown> = {};
331
+ const loads: Promise<void>[] = [];
332
+ for (const [key, wanted] of Object.entries(select)) {
333
+ const field = fields?.[key];
334
+ if (!field) continue;
335
+ if (wanted === true) {
336
+ if (!(key in stored)) continue;
337
+ if (field.kind === "blocks") {
338
+ const value = storedBlockArray(stored[key]);
339
+ if (value) out[key] = value;
340
+ } else {
341
+ out[key] = stored[key];
342
+ }
343
+ continue;
344
+ }
345
+ if (!isRecord(wanted)) continue;
346
+ if (field.kind === "relation") {
347
+ if (hopped) continue;
348
+ queueRelation(out, loads, key, field, stored[key], wanted, load, models);
349
+ continue;
350
+ }
351
+ if (field.kind !== "object" && field.kind !== "array") continue;
352
+ if (!(key in stored)) continue;
353
+ loads.push(
354
+ cutComposite(field, stored[key], wanted, load, models, hopped).then((cut) => {
355
+ if (cut !== undefined) out[key] = cut;
356
+ }),
357
+ );
358
+ }
359
+ if (loads.length > 0) await Promise.all(loads);
360
+ return Object.keys(out).length === 0 ? undefined : out;
361
+ }
362
+
363
+ async function cutComposite(
364
+ field: FieldDef,
365
+ stored: unknown,
366
+ select: Record<string, unknown>,
367
+ load: LoadDoc,
368
+ models: Map<string, ModelDef>,
369
+ hopped: boolean,
370
+ ): Promise<unknown> {
371
+ if (stored == null) return undefined;
372
+ if (field.kind === "array") {
373
+ if (!Array.isArray(stored)) return undefined;
374
+ const items = await Promise.all(
375
+ stored.map(async (item) => {
376
+ if (!isRecord(item)) return undefined;
377
+ return cutFields(field.fields, item, select, load, models, hopped);
378
+ }),
379
+ );
380
+ return items.filter((item): item is Record<string, unknown> => item !== undefined);
381
+ }
382
+ if (field.kind === "object") {
383
+ if (!isRecord(stored)) return undefined;
384
+ return cutFields(field.fields, stored, select, load, models, hopped);
385
+ }
386
+ return undefined;
387
+ }
388
+
389
+ function relationSlug(value: unknown): string | null {
390
+ if (typeof value !== "string" || value.trim() === "") return null;
391
+ return value;
392
+ }
393
+
394
+ async function selected(
395
+ model: ModelDef,
396
+ doc: { slug: string; frontmatter: Record<string, unknown>; body: string },
397
+ select: Record<string, unknown>,
398
+ load: LoadDoc,
399
+ models: Map<string, ModelDef>,
400
+ hopped: boolean,
401
+ ) {
402
+ const out: Record<string, unknown> = { slug: doc.slug };
403
+ const loads: Promise<void>[] = [];
404
+ for (const [key, wanted] of Object.entries(select)) {
405
+ if (key === "body") {
406
+ if (model.format !== "page" && wanted === true) out.body = doc.body;
407
+ continue;
408
+ }
409
+ const field = model.fields[key];
410
+ if (field?.kind === "blocks") {
411
+ if (wanted === true) {
412
+ const value = storedBlockArray(doc.frontmatter[key]);
413
+ if (value) out[key] = value;
414
+ }
415
+ continue;
416
+ }
417
+ if (field?.kind === "relation" && isRecord(wanted)) {
418
+ if (hopped) continue;
419
+ queueRelation(out, loads, key, field, doc.frontmatter[key], wanted, load, models);
420
+ continue;
421
+ }
422
+ if (wanted === true) {
423
+ if (key in doc.frontmatter) out[key] = doc.frontmatter[key];
424
+ continue;
425
+ }
426
+ if (!field || !isRecord(wanted) || (field.kind !== "object" && field.kind !== "array")) continue;
427
+ if (!(key in doc.frontmatter)) continue;
428
+ loads.push(
429
+ cutComposite(field, doc.frontmatter[key], wanted, load, models, hopped).then((cut) => {
430
+ if (cut !== undefined) out[key] = cut;
431
+ }),
432
+ );
433
+ }
434
+ if (loads.length > 0) await Promise.all(loads);
435
+ return out;
436
+ }
437
+
438
+ export function createQuery<
439
+ const Models extends readonly ModelDef[],
440
+ const Blocks extends readonly BlockDef[] = [],
441
+ >(models: Models, loader: DocLoader, blocks?: Blocks): Query<Models, Blocks> {
78
442
  const byType = new Map<string, ModelDef>(models.map((m) => [m.type, m]));
79
443
 
80
444
  function slugForGet(type: string, arg?: string): string {
@@ -92,6 +456,27 @@ export function createQuery<const Models extends readonly ModelDef[]>(
92
456
  return { ...doc, frontmatter: normalizeFrontmatter(doc.frontmatter) };
93
457
  }
94
458
 
459
+ function loadCached(
460
+ cache: Map<string, Promise<BackmatterDoc | null>>,
461
+ type: string,
462
+ slug: string,
463
+ ): Promise<BackmatterDoc | null> {
464
+ const key = `${type}:${slug}`;
465
+ const hit = cache.get(key);
466
+ if (hit) return hit;
467
+ const pending = get(type, slug);
468
+ cache.set(key, pending);
469
+ return pending;
470
+ }
471
+
472
+ async function read(type: string, slug: string, select: Record<string, unknown>) {
473
+ const model = byType.get(type);
474
+ const doc = await get(type, slug);
475
+ if (!doc || !model) return null;
476
+ const cache = new Map<string, Promise<BackmatterDoc | null>>();
477
+ return selected(model, doc, select, (rel, id) => loadCached(cache, rel, id), byType, false);
478
+ }
479
+
95
480
  function matchesWhere(doc: BackmatterDoc, where: Record<string, unknown>): boolean {
96
481
  for (const [key, expected] of Object.entries(where)) {
97
482
  if (expected === undefined) continue;
@@ -101,71 +486,67 @@ export function createQuery<const Models extends readonly ModelDef[]>(
101
486
  return true;
102
487
  }
103
488
 
104
- async function findMany(type: string, opts?: RawOpts): Promise<BackmatterDoc[]> {
489
+ async function findMany(type: string, opts: RawOpts) {
105
490
  const model = byType.get(type);
106
- const whereSlug = opts?.where?.slug;
491
+ if (!model) return [];
492
+ const whereSlug = opts.where?.slug;
107
493
 
108
- let docs: BackmatterDoc[];
494
+ let docs: Array<BackmatterDoc & { bodyLoaded: boolean }>;
109
495
  if (typeof whereSlug === "string") {
110
496
  const doc = await get(type, whereSlug);
111
- docs = doc ? [doc] : [];
497
+ docs = doc ? [{ ...doc, bodyLoaded: true }] : [];
112
498
  } else {
113
499
  const summaries = await loader.listDocs({ type });
114
500
  const fromList = summaries.filter((s) => s.frontmatter != null);
115
501
  const missing = summaries.filter((s) => s.frontmatter == null);
116
502
  const loaded = await Promise.all(missing.map((s) => get(type, s.slug)));
117
503
  docs = [
118
- ...fromList.map((s) => ({
119
- type: s.type,
120
- slug: s.slug,
121
- source: "head" as const,
122
- frontmatter: normalizeFrontmatter(s.frontmatter ?? {}),
123
- body: "",
124
- raw: "",
125
- })),
126
- ...loaded.filter((d): d is BackmatterDoc => d !== null),
504
+ ...fromList.map((s) => {
505
+ const body = s.body;
506
+ const bodyLoaded = typeof body === "string";
507
+ return {
508
+ type: s.type,
509
+ slug: s.slug,
510
+ source: "head" as const,
511
+ frontmatter: normalizeFrontmatter(s.frontmatter ?? {}),
512
+ body: bodyLoaded ? body : "",
513
+ raw: "",
514
+ bodyLoaded,
515
+ };
516
+ }),
517
+ ...loaded.flatMap((doc) => (doc ? [{ ...doc, bodyLoaded: true }] : [])),
127
518
  ];
128
519
  }
129
520
 
130
- const filtered = opts?.where ? docs.filter((d) => matchesWhere(d, opts.where!)) : docs;
131
- const include = opts?.include;
132
- if (!include || !model) return filtered;
133
-
134
- const relationCache = new Map<string, Promise<BackmatterDoc | null>>();
135
- const getCached = (target: string, slug: string) => {
136
- const key = `${target}:${slug}`;
137
- let promise = relationCache.get(key);
138
- if (!promise) {
139
- promise = get(target, slug);
140
- relationCache.set(key, promise);
141
- }
142
- return promise;
143
- };
144
-
521
+ const filtered = opts.where ? docs.filter((d) => matchesWhere(d, opts.where!)) : docs;
522
+ const wantsBody = opts.select.body === true && model.format !== "page";
523
+ const cache = new Map<string, Promise<BackmatterDoc | null>>();
524
+ const load = (rel: string, id: string) => loadCached(cache, rel, id);
145
525
  return Promise.all(
146
526
  filtered.map(async (doc) => {
147
- const extra: Record<string, BackmatterDoc | null> = {};
148
- for (const [name, on] of Object.entries(include)) {
149
- if (!on) continue;
150
- const field = model.fields[name];
151
- const target = field?.kind === "relation" ? field.relationTo : undefined;
152
- const relatedSlug = doc.frontmatter[name];
153
- extra[name] =
154
- target && typeof relatedSlug === "string" && relatedSlug.length > 0
155
- ? await getCached(target, relatedSlug)
156
- : null;
527
+ if (!wantsBody || doc.bodyLoaded) {
528
+ return selected(model, doc, opts.select, load, byType, false);
157
529
  }
158
- return { ...doc, ...extra };
530
+ const loaded = await get(type, doc.slug);
531
+ const select = loaded ? opts.select : withoutBody(opts.select);
532
+ return selected(model, loaded ?? doc, select, load, byType, false);
159
533
  }),
160
534
  );
161
535
  }
162
536
 
163
537
  const query: Record<string, unknown> = {};
164
538
  for (const m of models) {
165
- query[m.type] = {
166
- get: (arg?: string) => get(m.type, slugForGet(m.type, arg)),
167
- findMany: (opts?: RawOpts) => findMany(m.type, opts),
168
- };
539
+ query[m.type] =
540
+ m.singleton === true
541
+ ? {
542
+ get: (select: Record<string, unknown>) => read(m.type, slugForGet(m.type), select),
543
+ findMany: (opts: RawOpts) => findMany(m.type, opts),
544
+ }
545
+ : {
546
+ get: (slug: string, select: Record<string, unknown>) =>
547
+ read(m.type, slugForGet(m.type, slug), select),
548
+ findMany: (opts: RawOpts) => findMany(m.type, opts),
549
+ };
169
550
  }
170
- return query as Query<Models>;
551
+ return query as Query<Models, Blocks>;
171
552
  }
@@ -0,0 +1,12 @@
1
+ // packages/core/src/relation-match.ts
2
+ export function matchesWhere(
3
+ doc: { slug: string; frontmatter: Record<string, unknown> },
4
+ where: Record<string, string | number | boolean> | undefined,
5
+ ): boolean {
6
+ if (where === undefined) return true;
7
+ for (const [key, expected] of Object.entries(where)) {
8
+ const actual = key === "slug" ? doc.slug : doc.frontmatter[key];
9
+ if (actual !== expected) return false;
10
+ }
11
+ return true;
12
+ }