@caelo-cms/shared 0.11.8 → 0.11.9

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.
Files changed (58) hide show
  1. package/dist/ai-tools.d.ts +2 -2
  2. package/dist/build-page.d.ts +4 -4
  3. package/dist/change-journal.d.ts.map +1 -1
  4. package/dist/change-journal.js +1 -0
  5. package/dist/change-journal.js.map +1 -1
  6. package/dist/content.d.ts +6 -6
  7. package/dist/content.d.ts.map +1 -1
  8. package/dist/content.js +8 -1
  9. package/dist/content.js.map +1 -1
  10. package/dist/lists/fields.d.ts +6 -0
  11. package/dist/lists/fields.d.ts.map +1 -1
  12. package/dist/lists/fields.js +70 -7
  13. package/dist/lists/fields.js.map +1 -1
  14. package/dist/lists/index.d.ts +1 -0
  15. package/dist/lists/index.d.ts.map +1 -1
  16. package/dist/lists/index.js +1 -0
  17. package/dist/lists/index.js.map +1 -1
  18. package/dist/lists/list-type.d.ts +28 -6
  19. package/dist/lists/list-type.d.ts.map +1 -1
  20. package/dist/lists/list-type.js +43 -15
  21. package/dist/lists/list-type.js.map +1 -1
  22. package/dist/lists/overlay-scope.d.ts +68 -0
  23. package/dist/lists/overlay-scope.d.ts.map +1 -0
  24. package/dist/lists/overlay-scope.js +56 -0
  25. package/dist/lists/overlay-scope.js.map +1 -0
  26. package/dist/lists/query-merge.d.ts +27 -0
  27. package/dist/lists/query-merge.d.ts.map +1 -0
  28. package/dist/lists/query-merge.js +53 -0
  29. package/dist/lists/query-merge.js.map +1 -0
  30. package/dist/lists/resolve.d.ts +1 -0
  31. package/dist/lists/resolve.d.ts.map +1 -1
  32. package/dist/lists/resolve.js +11 -25
  33. package/dist/lists/resolve.js.map +1 -1
  34. package/dist/lists/scope.d.ts +4 -1
  35. package/dist/lists/scope.d.ts.map +1 -1
  36. package/dist/template-engine.d.ts.map +1 -1
  37. package/dist/template-engine.js +4 -1
  38. package/dist/template-engine.js.map +1 -1
  39. package/dist/version.d.ts +2 -2
  40. package/dist/version.js +1 -1
  41. package/package.json +1 -1
  42. package/src/change-journal.ts +1 -0
  43. package/src/content.test.ts +54 -0
  44. package/src/content.ts +10 -1
  45. package/src/lists/fields.ts +88 -7
  46. package/src/lists/index.ts +1 -0
  47. package/src/lists/list-type.ts +53 -18
  48. package/src/lists/lists.test.ts +70 -0
  49. package/src/lists/overlay-scope.test.ts +140 -0
  50. package/src/lists/overlay-scope.ts +120 -0
  51. package/src/lists/pagination.test.ts +15 -0
  52. package/src/lists/query-merge.ts +84 -0
  53. package/src/lists/resolve.test.ts +24 -4
  54. package/src/lists/resolve.ts +12 -33
  55. package/src/lists/scope.ts +4 -2
  56. package/src/template-engine-lists.test.ts +27 -1
  57. package/src/template-engine.ts +4 -1
  58. package/src/version.ts +1 -1
@@ -82,12 +82,60 @@ export type PageQuery = z.infer<typeof pageQuerySchema>;
82
82
  /** Partial query: defaults on a node, or the knobs an entry overrides. */
83
83
  export const pageQueryPartialSchema = pageQuerySchema.partial();
84
84
 
85
+ /** A complete query source, as the AI-facing examples and refusals show it. */
86
+ export const QUERY_SOURCE_EXAMPLE =
87
+ '{kind:"query", defaults:{page_type:"<slug>", order:"published_desc", limit:10}}';
88
+
89
+ /**
90
+ * The same for a paginated field: no `limit` — `paginate.per_page` is the
91
+ * page size, and a limit next to paginate is refused.
92
+ */
93
+ export const PAGINATED_QUERY_SOURCE_EXAMPLE =
94
+ '{kind:"query", defaults:{page_type:"<slug>", order:"published_desc"}} with paginate:{} on the field (no limit; paginate.per_page is the page size)';
95
+
96
+ /**
97
+ * #1281 — the knobs a query source's `defaults` must carry so it renders
98
+ * without any placement value: `order` always, `limit` unless the field
99
+ * is paginated (its page size is the limit). An editable knob is only an
100
+ * override, never a substitute: a placement that does not set it would
101
+ * leave the query incomplete. Returns the AI-actionable refusal, or null.
102
+ *
103
+ * @param where `"paginated"` — a module list field with `paginate`;
104
+ * `"field"` — any other module list field (may opt into paginate);
105
+ * `"node"` — a list-type node (never paginated).
106
+ */
107
+ export function missingQueryDefaults(
108
+ defaults: { readonly order?: unknown; readonly limit?: unknown },
109
+ where: "paginated" | "field" | "node",
110
+ ): string | null {
111
+ const missing: string[] = [];
112
+ if (defaults.order === undefined) {
113
+ missing.push(
114
+ 'order ("published_desc", "published_asc", "title_asc", or "prop_desc:<property>" / "prop_asc:<property>")',
115
+ );
116
+ }
117
+ if (where !== "paginated" && defaults.limit === undefined) {
118
+ missing.push(
119
+ where === "field"
120
+ ? "limit (1–50; for an overview of every matching page instead: no limit and `paginate:{}` on the list field)"
121
+ : "limit (1–50)",
122
+ );
123
+ }
124
+ if (missing.length === 0) return null;
125
+ const example = where === "paginated" ? PAGINATED_QUERY_SOURCE_EXAMPLE : QUERY_SOURCE_EXAMPLE;
126
+ return `a query source needs ${missing.join(" and ")} in source.defaults — e.g. ${example}.`;
127
+ }
128
+
85
129
  export const sourceDefSchema = z.discriminatedUnion("kind", [
86
130
  z
87
131
  .object({
88
132
  kind: z.literal("query"),
89
- /** Which query parts an editor (or the AI) may set per entry/placement. */
90
- editable: z.array(z.enum(QUERY_KNOBS)).max(QUERY_KNOBS.length),
133
+ /**
134
+ * Which query parts an editor (or the AI) may set per entry/placement.
135
+ * Optional, default none (#1304): most sources fix every knob, and a
136
+ * required empty array only produced refused tool calls.
137
+ */
138
+ editable: z.array(z.enum(QUERY_KNOBS)).max(QUERY_KNOBS.length).default([]),
91
139
  defaults: pageQueryPartialSchema,
92
140
  })
93
141
  .strict(),
@@ -227,22 +275,9 @@ export function checkListTypeDef(def: ListTypeDef): ListIssue[] {
227
275
  const q = pageQueryPartialSchema.safeParse(node.source.defaults);
228
276
  if (!q.success) {
229
277
  issues.push({ path: `${at}.source.defaults`, message: "query defaults are invalid." });
230
- } else if (
231
- node.source.defaults.order === undefined &&
232
- !node.source.editable.includes("order")
233
- ) {
234
- issues.push({
235
- path: `${at}.source`,
236
- message: 'a query source needs a default "order" or "order" in editable.',
237
- });
238
- } else if (
239
- node.source.defaults.limit === undefined &&
240
- !node.source.editable.includes("limit")
241
- ) {
242
- issues.push({
243
- path: `${at}.source`,
244
- message: 'a query source needs a default "limit" or "limit" in editable.',
245
- });
278
+ } else {
279
+ const missing = missingQueryDefaults(node.source.defaults, "node");
280
+ if (missing !== null) issues.push({ path: `${at}.source.defaults`, message: missing });
246
281
  }
247
282
  }
248
283
  }
@@ -112,6 +112,44 @@ describe("field values", () => {
112
112
  expect(validateFieldValue(f, v, "p").length === 0).toBe(ok);
113
113
  }
114
114
  });
115
+ // #1265 — an object value that does not fit says what is wrong in it,
116
+ // not just "got object".
117
+ describe("object-shaped values name the problem", () => {
118
+ const link: FieldDef = { name: "link", label: "Link", type: "link" };
119
+ const mod: FieldDef = { name: "cta", label: "CTA", type: "module" };
120
+ const msg = (f: FieldDef, v: unknown) => validateFieldValue(f, v, "p")[0]?.message ?? "";
121
+
122
+ it("unknown key", () => {
123
+ const m = msg(link, { url: "/about" });
124
+ expect(m).toContain('unknown key "url" (put the address in href)');
125
+ expect(m).toContain("href missing");
126
+ expect(m).not.toContain("got object");
127
+ });
128
+ it("href missing", () => {
129
+ expect(msg(link, { target: "_blank" })).toContain("href missing");
130
+ });
131
+ it("target outside the enum", () => {
132
+ expect(msg(link, { href: "/a", target: "new" })).toContain(
133
+ 'target must be "_self" | "_blank" (got "new")',
134
+ );
135
+ });
136
+ it("href of the wrong type or empty", () => {
137
+ expect(msg(link, { href: 5 })).toContain("href must be a string, got number");
138
+ expect(msg(link, { href: "" })).toContain("href is empty");
139
+ });
140
+ it("a non-object still says what it got", () => {
141
+ expect(msg(link, "/about")).toContain('got "/about"');
142
+ });
143
+ it("module value", () => {
144
+ const m = msg(mod, { moduleId: "x" });
145
+ expect(m).toContain("moduleId must be a uuid");
146
+ expect(m).toContain("contentInstanceId missing");
147
+ expect(msg(mod, { moduleId: PAGE, contentInstanceId: ITEM, extra: 1 })).toContain(
148
+ 'unknown key "extra"',
149
+ );
150
+ });
151
+ });
152
+
115
153
  it("rejects reserved names and invalid defaults", () => {
116
154
  expect(checkFieldDef({ name: "is_open", label: "x", type: "boolean" }, "f")).toHaveLength(1);
117
155
  expect(checkFieldDef({ name: "depth", label: "x", type: "number" }, "f")).toHaveLength(1);
@@ -150,6 +188,34 @@ describe("list type definitions", () => {
150
188
  expect(paths).toContain("nodes.column.current_from");
151
189
  expect(paths).toContain("nodes.column");
152
190
  });
191
+ // #1281 — an editable knob is an override, not a default: an entry that
192
+ // does not set it would leave the query incomplete.
193
+ it("requires order and limit in a query node's defaults, naming the fix", () => {
194
+ const withSource = (source: unknown): ListTypeDef =>
195
+ listTypeDefSchema.parse({
196
+ slug: "teasers",
197
+ name: "Teasers",
198
+ purpose: "p",
199
+ role: "content",
200
+ root: { allow: ["news"] },
201
+ nodes: { news: { label: "News", fields: [], source } },
202
+ });
203
+ const issues = checkListTypeDef(
204
+ withSource({ kind: "query", editable: ["order", "limit"], defaults: { page_type: "news" } }),
205
+ );
206
+ expect(issues).toHaveLength(1);
207
+ expect(issues[0]?.path).toBe("nodes.news.source.defaults");
208
+ expect(issues[0]?.message).toContain("needs order");
209
+ expect(issues[0]?.message).toContain("and limit (1–50) in source.defaults");
210
+ expect(
211
+ checkListTypeDef(
212
+ withSource({
213
+ kind: "query",
214
+ defaults: { page_type: "news", order: "published_desc", limit: 3 },
215
+ }),
216
+ ),
217
+ ).toEqual([]);
218
+ });
153
219
  it("requires name+slug on vocabulary entries", () => {
154
220
  const t: ListTypeDef = {
155
221
  slug: "v",
@@ -318,6 +384,10 @@ describe("page types and addresses", () => {
318
384
  });
319
385
 
320
386
  describe("source definitions", () => {
387
+ it("a query source's editable is optional and means none (#1304)", () => {
388
+ const r = sourceDefSchema.parse({ kind: "query", defaults: { order: "title_asc", limit: 5 } });
389
+ expect(r).toEqual({ kind: "query", editable: [], defaults: { order: "title_asc", limit: 5 } });
390
+ });
321
391
  it("a plugin source written as a system source is refused with the plugin form (PR #1121 e2e)", () => {
322
392
  const r = sourceDefSchema.safeParse({ kind: "system", name: "consent_categories" });
323
393
  expect(r.success).toBe(false);
@@ -0,0 +1,140 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * #1223 — what one previewed page can show from lists: the scope of its
5
+ * `list-resolve` call, or null when it shows nothing an overlay changes.
6
+ */
7
+
8
+ import { describe, expect, it } from "bun:test";
9
+ import type { TemplateField } from "../template-engine.js";
10
+ import type { ListTypeDef } from "./list-type.js";
11
+ import { pageListOverlayScope, type ScopedModule } from "./overlay-scope.js";
12
+ import type { ListPageRecord, ListRenderData } from "./render-data.js";
13
+
14
+ const P = (n: number): string => `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`;
15
+ const CI = "00000000-0000-4000-9000-000000000001";
16
+
17
+ function page(id: string, pageTypeSlug: string): ListPageRecord {
18
+ return {
19
+ id,
20
+ title: id,
21
+ shortTitle: id,
22
+ parentId: null,
23
+ pageTypeSlug,
24
+ properties: {},
25
+ terms: [],
26
+ firstPublishedAt: null,
27
+ updatedAt: "2026-10-01T00:00:00.000Z",
28
+ summary: null,
29
+ image: null,
30
+ inBuild: true,
31
+ } as ListPageRecord;
32
+ }
33
+
34
+ function listType(slug: string, source?: { kind: string; name?: string }): ListTypeDef {
35
+ return {
36
+ slug,
37
+ name: slug,
38
+ purpose: slug,
39
+ role: "content",
40
+ root: { allow: ["entry"] },
41
+ nodes: {
42
+ entry: { label: "Entry", fields: [{ name: "label", label: "Label", type: "text" }] },
43
+ ...(source ? { feed: { label: "Feed", fields: [], source } } : {}),
44
+ },
45
+ } as ListTypeDef;
46
+ }
47
+
48
+ /** P(1) en (product), P(2) de (product), P(3) de (plain), P(4) de (product). */
49
+ const data = {
50
+ listTypes: new Map([
51
+ ["nav", { id: "t1", def: listType("nav") }],
52
+ ["feed", { id: "t2", def: listType("feed", { kind: "query" }) }],
53
+ ["langs", { id: "t3", def: listType("langs", { kind: "plugin", name: "language_links" }) }],
54
+ ]),
55
+ lists: new Map([
56
+ ["l2", { id: "l2", slug: "footer", name: "Footer", typeSlug: "nav", items: [] }],
57
+ ["l1", { id: "l1", slug: "menu", name: "Menu", typeSlug: "nav", items: [] }],
58
+ ]),
59
+ pageTypes: new Map([
60
+ [
61
+ "product",
62
+ {
63
+ id: "pt1",
64
+ def: { slug: "product", properties: [{ name: "tagline", label: "T", type: "text" }] },
65
+ },
66
+ ],
67
+ ["plain", { id: "pt2", def: { slug: "plain", properties: [] } }],
68
+ ]),
69
+ pages: new Map([
70
+ [P(1), page(P(1), "product")],
71
+ [P(2), page(P(2), "product")],
72
+ [P(3), page(P(3), "plain")],
73
+ [P(4), page(P(4), "product")],
74
+ ]),
75
+ media: new Map(),
76
+ pageVariants: new Map([
77
+ [P(1), { variant: "en", group: "g1" }],
78
+ [P(2), { variant: "de", group: "g1" }],
79
+ [P(3), { variant: "de", group: null }],
80
+ [P(4), { variant: "de", group: "g2" }],
81
+ ]),
82
+ siteLanguage: "en",
83
+ homePageId: null,
84
+ } as unknown as ListRenderData;
85
+
86
+ const field = (f: Partial<TemplateField> & { name: string }): TemplateField =>
87
+ ({ kind: "text", ...f }) as TemplateField;
88
+ const mod = (fields: TemplateField[], html = ""): ScopedModule => ({ fields, html });
89
+
90
+ function scopeOf(modules: ScopedModule[], markup: string[] = []) {
91
+ return pageListOverlayScope({
92
+ pageId: P(2),
93
+ data,
94
+ modules,
95
+ markup,
96
+ contentInstanceIds: [CI, CI],
97
+ });
98
+ }
99
+
100
+ describe("pageListOverlayScope (#1223)", () => {
101
+ it("is null for a page that shows no list, no page value and no site text", () => {
102
+ expect(scopeOf([mod([field({ name: "title" })], "<h1>{{title}}</h1>")])).toBeNull();
103
+ });
104
+
105
+ it("covers every shared list, the page's instances and the page itself", () => {
106
+ expect(scopeOf([mod([field({ name: "items", kind: "list", listType: "nav" })])])).toEqual({
107
+ listIds: ["l1", "l2"],
108
+ contentInstanceIds: [CI],
109
+ pageIds: [P(2)],
110
+ });
111
+ });
112
+
113
+ it("counts `page.*` and `site_text.*` in any markup as a list read", () => {
114
+ const plain = [mod([field({ name: "title" })], "<h1>{{title}}</h1>")];
115
+ expect(scopeOf([mod([], "<p>{{ PAGE.props.tagline }}</p>")])?.pageIds).toEqual([P(2)]);
116
+ expect(scopeOf(plain, ["<footer>{{site_text.copyright}}</footer>"])).not.toBeNull();
117
+ });
118
+
119
+ it("adds the variant's pages with properties when a list generates page entries", () => {
120
+ const query = scopeOf([mod([field({ name: "news", kind: "list", listType: "feed" })])]);
121
+ // P(3) has no properties, P(1) is in another variant.
122
+ expect(query?.pageIds).toEqual([P(2), P(4)]);
123
+ const bound = scopeOf([
124
+ mod([
125
+ field({
126
+ name: "kids",
127
+ kind: "list",
128
+ bind: "source",
129
+ source: { kind: "system", name: "children" },
130
+ } as never),
131
+ ]),
132
+ ]);
133
+ expect(bound?.pageIds).toEqual([P(2), P(4)]);
134
+ });
135
+
136
+ it("a plugin source generates no pages", () => {
137
+ const langs = scopeOf([mod([field({ name: "langs", kind: "list", listType: "langs" })])]);
138
+ expect(langs?.pageIds).toEqual([P(2)]);
139
+ });
140
+ });
@@ -0,0 +1,120 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * #1223 — what one page's render can show from lists, so the editor
5
+ * preview asks `list-resolve` for that page's overlay instead of the whole
6
+ * site's (the plugin's answer then costs what the page costs).
7
+ *
8
+ * An overlay is keyed by value address (`list/<listId>/…`,
9
+ * `instance/<ciId>/…`, `page/<pageId>/props/…`, docs/lists.md §9.3). The
10
+ * resolver reads it lazily while the page renders, so the scope has to be
11
+ * known before the render and has to be a SUPERSET of what the render
12
+ * reads; anything more only costs a few rows:
13
+ *
14
+ * - lists: every shared list. A list renders as a whole wherever it is
15
+ * bound (a menu, the site texts, a vocabulary's terms), and their
16
+ * number does not grow with the pages.
17
+ * - content instances: the instances the page renders (its placements
18
+ * and the instances nested in them), whose local lists the overlay
19
+ * translates.
20
+ * - pages: the rendered page (`{{page.props.*}}`) and, when a list on
21
+ * the page generates page entries (a query or a system source:
22
+ * latest news, children, breadcrumbs), every page of the page's
23
+ * variant that has properties. A props overlay only exists for pages
24
+ * of the variant the page renders, and only for page types that
25
+ * declare properties, so no other page can show one.
26
+ *
27
+ * Null when the page shows nothing a list overlay can change: no module
28
+ * on it (placed, chrome, nested or a content variant) has a list field,
29
+ * and no markup reads `page.*` or `site_text.*`. The preview then skips
30
+ * `list-resolve` entirely.
31
+ *
32
+ * The static build asks per page batch with the union of its pages'
33
+ * scopes (#1307, the generator's `list-overlay-batches.ts`), so a build's
34
+ * `list-resolve` reads cost what the batch costs, not the site.
35
+ */
36
+
37
+ import type { TemplateField } from "../template-engine.js";
38
+ import type { ListRenderData } from "./render-data.js";
39
+
40
+ /** The `scope` of a scoped `list-resolve` call (plugin-sdk `listResolveScope`). */
41
+ export interface ListOverlayScope {
42
+ readonly listIds: string[];
43
+ readonly contentInstanceIds: string[];
44
+ readonly pageIds: string[];
45
+ }
46
+
47
+ /** A module field as far as the scope cares (a build's fields may leave `kind` out: text). */
48
+ export type ScopedField = Omit<TemplateField, "kind"> & { readonly kind?: string };
49
+
50
+ /** A module as far as the scope cares: its fields and its markup. */
51
+ export interface ScopedModule {
52
+ readonly fields: readonly ScopedField[];
53
+ readonly html: string;
54
+ }
55
+
56
+ /** What {@link pageListOverlayScope} reads the page from. */
57
+ export interface PageListOverlayInput {
58
+ readonly pageId: string;
59
+ /** The page's list render data before overlays (pages, lists, types, partition). */
60
+ readonly data: ListRenderData;
61
+ /** Every module the page renders: placed, chrome, nested, content variants. */
62
+ readonly modules: Iterable<ScopedModule>;
63
+ /** Markup outside the modules: the template's and the layout's HTML. */
64
+ readonly markup: Iterable<string>;
65
+ /** The stored content instances the page renders (render-local aliases excluded). */
66
+ readonly contentInstanceIds: Iterable<string>;
67
+ }
68
+
69
+ /**
70
+ * `{{page.…}}` / `{{site_text.…}}` (any case, any section operator). A
71
+ * loose match on purpose: a false hit costs one scoped plugin call, a
72
+ * miss would show the page untranslated.
73
+ */
74
+ const LIST_SCOPE_READ_RE = /\b(?:page|site_text)\./i;
75
+
76
+ /** True when the module's markup or fields can read list data. */
77
+ function readsLists(m: ScopedModule): boolean {
78
+ return m.fields.some((f) => f.kind === "list") || LIST_SCOPE_READ_RE.test(m.html);
79
+ }
80
+
81
+ /** True when one of `fields` can generate page entries (a query or system source). */
82
+ function generatesPages(fields: readonly ScopedField[], data: ListRenderData): boolean {
83
+ for (const f of fields) {
84
+ if (f.kind !== "list") continue;
85
+ if (f.bind === "source" && f.source?.kind !== "plugin") return true;
86
+ const type = f.listType === undefined ? undefined : data.listTypes.get(f.listType);
87
+ if (!type) continue;
88
+ for (const node of Object.values(type.def.nodes)) {
89
+ if (node.source && node.source.kind !== "plugin") return true;
90
+ }
91
+ }
92
+ return false;
93
+ }
94
+
95
+ /**
96
+ * The scope of one page's `list-resolve` call, or null when the page
97
+ * shows nothing an overlay can change (see the file header).
98
+ */
99
+ export function pageListOverlayScope(input: PageListOverlayInput): ListOverlayScope | null {
100
+ const { data, pageId } = input;
101
+ const modules = [...input.modules];
102
+ const usesLists =
103
+ modules.some(readsLists) || [...input.markup].some((html) => LIST_SCOPE_READ_RE.test(html));
104
+ if (!usesLists) return null;
105
+
106
+ const pageIds = new Set<string>([pageId]);
107
+ const variant = data.pageVariants?.get(pageId)?.variant;
108
+ if (variant !== undefined && modules.some((m) => generatesPages(m.fields, data))) {
109
+ for (const p of data.pages.values()) {
110
+ if (data.pageVariants?.get(p.id)?.variant !== variant) continue;
111
+ if ((data.pageTypes.get(p.pageTypeSlug)?.def.properties.length ?? 0) === 0) continue;
112
+ pageIds.add(p.id);
113
+ }
114
+ }
115
+ return {
116
+ listIds: [...data.lists.keys()].sort(),
117
+ contentInstanceIds: [...new Set(input.contentInstanceIds)].sort(),
118
+ pageIds: [...pageIds].sort(),
119
+ };
120
+ }
@@ -226,6 +226,21 @@ describe("module field schema", () => {
226
226
  });
227
227
 
228
228
  describe("resolver", () => {
229
+ // #1281 review — a paginated query without order must not be told to add
230
+ // a limit: paginateIssues refuses a limit next to paginate.
231
+ it("a paginated query without order names order, never a limit", () => {
232
+ const noOrder: ListFieldSpec = {
233
+ ...GUIDES,
234
+ source: { kind: "query", editable: [], defaults: { page_type: "guide" } },
235
+ };
236
+ const r = ctxFor(3).resolveField(noOrder, undefined, { contentInstanceId: null });
237
+ expect(r).toMatchObject({ ok: false, marker: "list-malformed:guides[query.order]" });
238
+ const detail = r.ok ? "" : (r.detail ?? "");
239
+ expect(detail).toContain('the query has no "order"');
240
+ expect(detail).toContain("paginate:{}");
241
+ expect(detail).not.toContain("limit:");
242
+ });
243
+
229
244
  it("shows 50 per page by default and records the sequence", () => {
230
245
  const ctx = ctxFor(63);
231
246
  const page1 = resolve(ctx, GUIDES);
@@ -0,0 +1,84 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * Merging a query source's defaults with the knobs an entry or placement
5
+ * sets (`docs/lists.md` §6). A query that does not come out complete is
6
+ * never guessed (CLAUDE.md §2): the render reports
7
+ * `list-malformed:<field>[<path>.<knob>]`, the marker names the failing
8
+ * knob, and `detail` says how to fix it — `preview_list_source` hands it to
9
+ * the AI verbatim (#1281).
10
+ */
11
+
12
+ import {
13
+ PAGINATED_QUERY_SOURCE_EXAMPLE,
14
+ type PageQuery,
15
+ pageQuerySchema,
16
+ QUERY_SOURCE_EXAMPLE,
17
+ type QueryKnob,
18
+ type SourceDef,
19
+ } from "./list-type.js";
20
+
21
+ /** Why a merged query failed: the marker the render reports + the fix. */
22
+ export interface QueryMergeFailure {
23
+ readonly marker: string;
24
+ readonly detail: string;
25
+ }
26
+
27
+ const ORDER_VALUES =
28
+ '"published_desc", "published_asc", "title_asc", "prop_desc:<property>" or "prop_asc:<property>"';
29
+
30
+ /**
31
+ * Merge `source.defaults` with `overrides` (an entry's / placement's knobs)
32
+ * and parse the result as a complete page query.
33
+ *
34
+ * @param field The list field the source belongs to (marker prefix).
35
+ * @param path Where the overrides live (`query`, `<itemId>.query`).
36
+ * @param paginated The field is paginated: its page size is the limit, so
37
+ * the fix never suggests one (a limit next to paginate is refused).
38
+ */
39
+ export function mergeQuerySource(
40
+ source: Extract<SourceDef, { kind: "query" }>,
41
+ overrides: unknown,
42
+ field: string,
43
+ path: string,
44
+ paginated = false,
45
+ ): PageQuery | QueryMergeFailure {
46
+ const fail = (at: string, detail: string): QueryMergeFailure => ({
47
+ marker: `list-malformed:${field}[${at}]`,
48
+ detail,
49
+ });
50
+ const merged: Record<string, unknown> = { ...source.defaults };
51
+ const editable: readonly string[] = source.editable;
52
+ if (overrides !== undefined && overrides !== null) {
53
+ if (typeof overrides !== "object" || Array.isArray(overrides)) {
54
+ return fail(path, "the value of a query field is an object of query knobs, e.g. {limit:3}.");
55
+ }
56
+ for (const [k, v] of Object.entries(overrides)) {
57
+ if (!editable.includes(k as QueryKnob)) {
58
+ return fail(
59
+ `${path}.${k}`,
60
+ `"${k}" cannot be set per entry or placement — the source's editable list is ${editable.length > 0 ? editable.join(", ") : "empty"}. Remove "${k}" from the value, or add it to source.editable.`,
61
+ );
62
+ }
63
+ merged[k] = v;
64
+ }
65
+ }
66
+ const parsed = pageQuerySchema.safeParse(merged);
67
+ if (parsed.success) return parsed.data;
68
+ const issue = parsed.error.issues[0];
69
+ const knob = issue?.path.map(String).join(".") ?? "";
70
+ const at = knob === "" ? path : `${path}.${knob}`;
71
+ if (knob === "order" && merged.order === undefined) {
72
+ return fail(
73
+ at,
74
+ `the query has no "order" — add order (${ORDER_VALUES}) to source.defaults, e.g. ${paginated ? PAGINATED_QUERY_SOURCE_EXAMPLE : QUERY_SOURCE_EXAMPLE}.`,
75
+ );
76
+ }
77
+ if (knob === "limit" && merged.limit === undefined) {
78
+ return fail(
79
+ at,
80
+ `the query has no "limit" — add limit (1–50) to source.defaults, e.g. ${QUERY_SOURCE_EXAMPLE}; for an overview of every matching page, give the list field paginate:{} instead.`,
81
+ );
82
+ }
83
+ return fail(at, `query knob "${knob}" is invalid: ${issue?.message ?? "invalid value"}.`);
84
+ }
@@ -104,14 +104,34 @@ describe("query sources", () => {
104
104
  const q = query({ page_type: "news", order: "published_desc", limit: 3 }, ["limit"]);
105
105
  expect(entries(page(PAGE.home), q, { limit: 1 })).toHaveLength(1);
106
106
  const r = page(PAGE.home).resolveField(q, { page_type: "page" }, { contentInstanceId: null });
107
- expect(r).toEqual({ ok: false, marker: "list-malformed:q[query.page_type]" });
107
+ expect(r).toMatchObject({ ok: false, marker: "list-malformed:q[query.page_type]" });
108
+ expect(r.ok ? "" : r.detail).toContain(
109
+ '"page_type" cannot be set per entry or placement — the source\'s editable list is limit.',
110
+ );
108
111
  });
109
112
 
110
- it("an incomplete query (no order / limit) is malformed, never guessed", () => {
111
- const r = page(PAGE.home).resolveField(query({ page_type: "news" }), undefined, {
113
+ // #1281 — the marker names the missing knob and `detail` says the fix
114
+ // (preview_list_source used to blame the `editable` list instead).
115
+ it("an incomplete query (no order / limit) is malformed, never guessed — naming the knob", () => {
116
+ const noOrder = page(PAGE.home).resolveField(query({ page_type: "news" }), undefined, {
112
117
  contentInstanceId: null,
113
118
  });
114
- expect(r).toEqual({ ok: false, marker: "list-malformed:q[query]" });
119
+ expect(noOrder).toMatchObject({ ok: false, marker: "list-malformed:q[query.order]" });
120
+ expect(noOrder.ok ? "" : noOrder.detail).toContain('the query has no "order" — add order (');
121
+ const noLimit = page(PAGE.home).resolveField(
122
+ query({ page_type: "news", order: "title_asc" }),
123
+ undefined,
124
+ { contentInstanceId: null },
125
+ );
126
+ expect(noLimit).toMatchObject({ ok: false, marker: "list-malformed:q[query.limit]" });
127
+ expect(noLimit.ok ? "" : noLimit.detail).toContain('the query has no "limit"');
128
+ const badLimit = page(PAGE.home).resolveField(
129
+ query({ page_type: "news", order: "title_asc", limit: 3 }, ["limit"]),
130
+ { limit: 500 },
131
+ { contentInstanceId: null },
132
+ );
133
+ expect(badLimit).toMatchObject({ ok: false, marker: "list-malformed:q[query.limit]" });
134
+ expect(badLimit.ok ? "" : badLimit.detail).toContain('query knob "limit" is invalid');
115
135
  });
116
136
 
117
137
  it("returns only pages of the rendering page's variant", () => {