suppa-mcp-2 1.45.1 → 1.47.0

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.
@@ -0,0 +1,307 @@
1
+ /**
2
+ * The platform's MANUAL order of records ("custom order") — for ANY entity.
3
+ *
4
+ * It is not a column. The platform keeps it in its own table, CustomOrders, one
5
+ * row per (entity, context field, context value, record), and exposes it two ways
6
+ * (entity-builder develop 1e8ea716d):
7
+ * - read: an orderBy entry {field, order, function: "custom_order", args: [value]}
8
+ * (core2 lower-custom-order.pass.ts; "#custom_order" is the same name —
9
+ * sql-safety.util.ts toSafeDslFunctionName strips the "#");
10
+ * - write: POST /api/core/data/custom-order/<Entity> with InstancesOrderDto
11
+ * (modules/entity/controllers/custom-order.controller.ts).
12
+ *
13
+ * The CONTEXT names the list: one parent's children are (parent, 40), a
14
+ * hierarchy's top level is (parent, null), a flat entity's own list is the global
15
+ * order (no field, no value). Reads express exactly these three; nothing reads a
16
+ * value without a field (assertReadableContext). A hierarchy that ALSO has an
17
+ * owner keeps its top level per owner: the top-level PageBlocks of page 12 are
18
+ * (page, 12) read with parent = null, the top-level Pages of doc 55 are (doc, 55)
19
+ * — the front reads and writes exactly these (pagesStore.ts loadDocPages, the
20
+ * page and block reorders), and nothing reads (parent, null) for them.
21
+ *
22
+ * Anchors are positions IN THE LIST THE READER SEES, read in `direction`, and the
23
+ * ids land as one block in the order given — InstancesOrderDto.direction ("relative
24
+ * to what the user sees … Absent ⇒ 'desc'") and
25
+ * test/integration/common/custom-order/custom-order-visible-order.e2e.spec.ts pin
26
+ * both. Nothing here inverts an anchor or reverses the ids.
27
+ */
28
+ import { makeRequest, searchEntity } from "../httpClient.js";
29
+ /**
30
+ * contextFieldName for the global order. The DTO requires a name, and the
31
+ * controller's (no field, no value) branch IS the global order — the front sends
32
+ * 'parent' for a flat table and relies on exactly that (custom-order.controller.ts
33
+ * assertReadableContext). orderContextRefusal guarantees the entity has no `parent`.
34
+ */
35
+ export const GLOBAL_CONTEXT_FIELD = "parent";
36
+ /** What the planner scopes a custom_order by (lower-custom-order.pass.ts: "must be an "enum" or "many-to-one" relation"). */
37
+ const CONTEXT_FIELD_TYPES = new Set(["many-to-one", "enum"]);
38
+ const ACCEPTED = "custom_order, custom_order(page, 12) or custom_order(parent), each optionally followed by :asc or :desc";
39
+ const CUSTOM_ORDER = /^custom_order\s*(?:\(\s*(?:"?([A-Za-z_][A-Za-z0-9_]*)"?\s*(?:,\s*(null|\d+)\s*)?)?\))?\s*(?::\s*([A-Za-z]+)\s*)?$/i;
40
+ /**
41
+ * An order_by that asks for the manual order, or null when it is a plain 'field:dir'.
42
+ * custom_order the entity's global order, desc
43
+ * custom_order(page, 2962) the list of page 2962
44
+ * custom_order(parent):asc a hierarchy's top level, read ascending
45
+ * Throws, naming the accepted forms, when it starts like one and is malformed.
46
+ */
47
+ export function parseCustomOrderBy(orderBy) {
48
+ const text = String(orderBy ?? "").trim();
49
+ if (!/^custom_order(?![A-Za-z0-9_])/i.test(text))
50
+ return null;
51
+ const m = CUSTOM_ORDER.exec(text);
52
+ if (!m)
53
+ throw new Error(`order_by '${text}' is not a manual-order read. Accepted: ${ACCEPTED}.`);
54
+ const [, field, rawValue, rawDir] = m;
55
+ const direction = (rawDir ?? "desc").toLowerCase();
56
+ if (direction !== "asc" && direction !== "desc") {
57
+ throw new Error(`order_by direction must be 'asc' or 'desc', got '${rawDir}'. Accepted: ${ACCEPTED}.`);
58
+ }
59
+ const value = rawValue === undefined || rawValue.toLowerCase() === "null" ? null : Number(rawValue);
60
+ if (value !== null && !isRecordId(value)) {
61
+ throw new Error(`order_by's context value must be a positive record id, got '${rawValue}'. Accepted: ${ACCEPTED}.`);
62
+ }
63
+ return { context: { field: field ?? null, value }, direction };
64
+ }
65
+ /** A record id: a positive, safe integer (the platform once stored contextValue = 0 for a missing value). */
66
+ export function isRecordId(n) {
67
+ return Number.isSafeInteger(n) && n > 0;
68
+ }
69
+ export function flip(direction) {
70
+ return direction === "desc" ? "asc" : "desc";
71
+ }
72
+ /**
73
+ * The orderBy of a read in that order. The custom-order entry goes FIRST:
74
+ * #expand_tree orders a row's children by their own parent's order only then
75
+ * (expand-tree.service.ts selectInParentOrder). The id entry breaks ties so offset
76
+ * paging is stable, and runs against the order so asc is exactly desc reversed.
77
+ */
78
+ export function customOrderBy(context, direction) {
79
+ const entry = {};
80
+ if (context.field !== null)
81
+ entry.field = context.field;
82
+ entry.order = direction;
83
+ entry.function = "custom_order";
84
+ if (context.field !== null && context.value !== null)
85
+ entry.args = [context.value];
86
+ return [entry, { field: "id", order: flip(direction) }];
87
+ }
88
+ /**
89
+ * The filters that keep a read to the rows of its list (a row outside it has no
90
+ * place in it) — with `topLevelField`, an owner list's top level only.
91
+ */
92
+ export function contextFilters(context, topLevelField = null) {
93
+ if (context.field === null)
94
+ return [];
95
+ const own = context.value === null
96
+ ? { field: context.field, comparator: "=", value: null }
97
+ : { field: `${context.field}.id`, comparator: "=", value: context.value };
98
+ return topLevelField === null ? [own] : [own, { field: topLevelField, comparator: "=", value: null }];
99
+ }
100
+ /** The order_by that reads this list back with suppa_search_records. */
101
+ export function orderByText(context, direction) {
102
+ const head = context.field === null
103
+ ? "custom_order"
104
+ : context.value === null
105
+ ? `custom_order(${context.field})`
106
+ : `custom_order(${context.field}, ${context.value})`;
107
+ return direction === "asc" ? `${head}:asc` : head;
108
+ }
109
+ /** Why this placement cannot be sent, or null. `anchorArg` names the anchor's argument in the answer. */
110
+ export function placementProblem(where, anchorId, movedIds, anchorArg = "anchor_id") {
111
+ const noAnchor = anchorId === null || anchorId === undefined;
112
+ if (where === "before" || where === "after") {
113
+ if (noAnchor)
114
+ return `where='${where}' needs ${anchorArg} — the id of a record of the same list.`;
115
+ if (!isRecordId(anchorId)) {
116
+ return `${anchorArg} must be a positive record id, got ${String(anchorId)}.`;
117
+ }
118
+ if (movedIds.includes(anchorId)) {
119
+ return `${anchorArg} ${anchorId} is one of the records being placed — anchor on a record that stays put.`;
120
+ }
121
+ return null;
122
+ }
123
+ if (where === "first" || where === "last") {
124
+ return noAnchor ? null : `where='${where}' takes no ${anchorArg} — leave it null, or use where='before'/'after'.`;
125
+ }
126
+ return `where must be 'before', 'after', 'first' or 'last', got '${String(where)}'.`;
127
+ }
128
+ /** The body of POST /api/core/data/custom-order/<Entity>. `updates` stays empty: the platform applies it as sudo. */
129
+ export function reorderBody(ids, context, direction, anchor) {
130
+ return {
131
+ instanceIds: [...ids],
132
+ contextFieldName: context.field ?? GLOBAL_CONTEXT_FIELD,
133
+ contextValue: context.value,
134
+ direction,
135
+ updates: {},
136
+ ...("beforeId" in anchor ? { beforeInstanceId: anchor.beforeId } : { afterInstanceId: anchor.afterId }),
137
+ };
138
+ }
139
+ function fieldsOf(schema) {
140
+ const fields = schema?.fields;
141
+ return Array.isArray(fields) ? fields.filter((f) => typeof f === "object" && f !== null) : [];
142
+ }
143
+ const carriesOrder = (f) => f.options?.customOrder === true;
144
+ /** The hierarchy field of an entity whose order is kept per parent. */
145
+ const HIERARCHY_FIELD = "parent";
146
+ /**
147
+ * The owners of a hierarchy kept per owner: the order-carrying many-to-one fields
148
+ * other than `parent` (Pages: doc, PageBlocks: page). Read from the schema, never
149
+ * from the entity's name; empty when the entity has no `parent` many-to-one.
150
+ */
151
+ function ownersOf(fields) {
152
+ const isManyToOne = (f) => String(f.type) === "many-to-one";
153
+ if (!fields.some((f) => f.name === HIERARCHY_FIELD && isManyToOne(f)))
154
+ return [];
155
+ return fields
156
+ .filter((f) => carriesOrder(f) && isManyToOne(f) && f.name !== HIERARCHY_FIELD && f.name !== "id")
157
+ .map((f) => String(f.name));
158
+ }
159
+ function perOwnerRefusal(entityName, owners) {
160
+ const top = owners.map((o) => `context_field='${o}', context_value=<${o} id> (custom_order(${o}, <id>))`).join(" or ");
161
+ return (`'${entityName}' is a hierarchy kept per ${owners.join(" / ")}: no list reads its global order or parent = null. ` +
162
+ `The top level is kept per owner — ${top}; one parent's children: ` +
163
+ "context_field='parent', context_value=<parent id> (custom_order(parent, <id>)).");
164
+ }
165
+ /**
166
+ * Why `context` cannot name a manual order of `entityName` — or, when it can, the
167
+ * list it names: an owner list of a hierarchy kept per owner carries its
168
+ * topLevelField, which contextFilters and listProblem apply. One GET
169
+ * /api/core/schema/<E>. Without it the platform answers a wrong context
170
+ * with "custom_order() expects a field name as its first argument, got a 'func'
171
+ * expression" (read live on Pages.title) — or, on a write, stores an order that
172
+ * no list ever reads.
173
+ */
174
+ export async function orderContextRefusal(entityName, context) {
175
+ const refuse = (refusal) => ({ refusal });
176
+ if (context.field === null && context.value !== null) {
177
+ return refuse("context_value needs a context_field: the platform keeps no list under a value without a field, " +
178
+ "and nothing could read it back. Name the field that scopes the list (e.g. 'page').");
179
+ }
180
+ if (context.value !== null && !isRecordId(context.value)) {
181
+ return refuse(`context_value must be a positive record id (or null for the field's empty group), got ${String(context.value)}.`);
182
+ }
183
+ let schema;
184
+ try {
185
+ // One path segment: a name with a '/' must not reach another endpoint.
186
+ schema = await makeRequest("GET", `/api/core/schema/${encodeURIComponent(entityName)}`);
187
+ }
188
+ catch (e) {
189
+ const msg = e instanceof Error ? e.message : String(e);
190
+ return refuse(`Refused: the schema of '${entityName}' could not be read (${msg}) — check the name with suppa_list_entities. Nothing was sent.`);
191
+ }
192
+ const fields = fieldsOf(schema);
193
+ if (!fields.some(carriesOrder)) {
194
+ return refuse(`'${entityName}' keeps no manual order: none of its fields carries options.customOrder.`);
195
+ }
196
+ const scoping = fields.filter((f) => carriesOrder(f) && f.name !== "id").map((f) => String(f.name));
197
+ const scopes = scoping.length ? scoping.join(", ") : "none — only its own list (no context)";
198
+ const owners = ownersOf(fields);
199
+ const list = (topLevelField = null) => ({ refusal: null, list: { context, topLevelField } });
200
+ if (context.field === null) {
201
+ const hierarchy = fields.find((f) => f.name === HIERARCHY_FIELD || f.name === "parents");
202
+ if (!hierarchy)
203
+ return list();
204
+ if (hierarchy.name === "parents") {
205
+ return refuse(`'${entityName}' is a multi-parent hierarchy: its manual order is kept per parent (parents), which this server does not read or write yet.`);
206
+ }
207
+ if (owners.length)
208
+ return refuse(perOwnerRefusal(entityName, owners));
209
+ return refuse(`'${entityName}' is a hierarchy: its manual order is kept per parent and no list reads a global one. ` +
210
+ "Name the field — context_field='parent' / custom_order(parent) for the top level, " +
211
+ "custom_order(parent, <id>) for one parent's children.");
212
+ }
213
+ const def = fields.find((f) => f.name === context.field);
214
+ if (!def)
215
+ return refuse(`'${entityName}' has no field '${context.field}'. Fields that scope its manual order: ${scopes}.`);
216
+ if (!CONTEXT_FIELD_TYPES.has(String(def.type))) {
217
+ return refuse(`'${context.field}' is a ${String(def.type)} field — a manual order is scoped only by a many-to-one ` +
218
+ `relation or an enum. Fields that scope it on '${entityName}': ${scopes}.`);
219
+ }
220
+ if (owners.length && context.field === HIERARCHY_FIELD && context.value === null) {
221
+ return refuse(perOwnerRefusal(entityName, owners));
222
+ }
223
+ return list(owners.includes(context.field) ? HIERARCHY_FIELD : null);
224
+ }
225
+ // ---------------------------------------------------------------------------
226
+ // Membership. The platform's custom-order write runs as sudo and checks no rights
227
+ // on the rows (custom-order.controller.ts updateRows), so every row a write moves,
228
+ // and every anchor, is read first WITH THE CALLER'S RIGHTS (active rows only).
229
+ // ---------------------------------------------------------------------------
230
+ /** One call moves or inserts at most this many records — one membership read covers them. */
231
+ export const MAX_ORDER_IDS = 200;
232
+ /** A record id from a bare id or a {id} reference; null for anything else. */
233
+ export function idOf(v) {
234
+ if (typeof v === "number" && Number.isInteger(v))
235
+ return v;
236
+ if (v !== null && typeof v === "object" && Number.isInteger(v.id))
237
+ return v.id;
238
+ return null;
239
+ }
240
+ /** Why `ids` cannot be the records of one move, or null. `arg` names the argument in the answer. */
241
+ export function idsProblem(ids, arg = "record_ids") {
242
+ if (!Array.isArray(ids) || ids.length === 0) {
243
+ return `${arg} is empty — pass the ids to move, in the order they should stand.`;
244
+ }
245
+ if (ids.length > MAX_ORDER_IDS)
246
+ return `${arg} has ${ids.length} ids; one call moves at most ${MAX_ORDER_IDS}.`;
247
+ const bad = ids.filter((n) => !isRecordId(n));
248
+ if (bad.length)
249
+ return `${arg} must be positive record ids; got ${JSON.stringify(bad)}.`;
250
+ if (new Set(ids).size !== ids.length)
251
+ return `${arg} names a record twice — each id once, in the order they should stand.`;
252
+ return null;
253
+ }
254
+ /** The fields a membership read of `list` projects: its context field, and the field its top level keeps empty. */
255
+ export function listFields(list) {
256
+ return [list.context.field, list.topLevelField].filter((f) => f !== null);
257
+ }
258
+ /** `ids` of `entity`, read with the caller's rights (active rows only), each of `fields` projected as {id}. */
259
+ export async function readOrderRows(entity, ids, fields) {
260
+ const projection = { id: true };
261
+ for (const f of fields)
262
+ projection[f] = { id: true };
263
+ const rows = (await searchEntity(entity, [{ field: "id", comparator: "in", value: ids }], projection, ids.length + 1, 0, [{ field: "id", order: "asc" }], "", "and", "active"));
264
+ return new Map(rows.map((r) => [r.id, r]));
265
+ }
266
+ /** Why the rows read (`byId`) do not all stand in `list`, or null. Pure; the reason only. */
267
+ export function listProblem(entity, list, ids, byId) {
268
+ const missing = ids.filter((id) => !byId.has(id));
269
+ if (missing.length) {
270
+ return `Records ${missing.join(", ")} of '${entity}' were not found — no such id, soft-deleted, or not visible to you.`;
271
+ }
272
+ const { field, value } = list.context;
273
+ if (field === null)
274
+ return null;
275
+ // An empty relation reads back as null. A field hidden by field permissions
276
+ // reads back ABSENT, and a related row the caller may not see comes back masked
277
+ // "*" (entity-builder lower-root-relations.pass.ts) — neither is "empty": never
278
+ // take them for standing in a list.
279
+ const readable = (row, f) => row !== undefined && Object.prototype.hasOwnProperty.call(row, f) && (row[f] === null || idOf(row[f]) !== null);
280
+ for (const f of listFields(list)) {
281
+ const unread = ids.filter((id) => !readable(byId.get(id), f));
282
+ if (unread.length) {
283
+ return `You cannot read '${f}' of records ${unread.join(", ")} of '${entity}' (hidden from you), so their list cannot be checked.`;
284
+ }
285
+ }
286
+ const foreign = ids.filter((id) => idOf(byId.get(id)?.[field] ?? null) !== value);
287
+ if (foreign.length) {
288
+ const where = value === null ? `${field} is empty` : `${field} = ${value}`;
289
+ return `Records ${foreign.join(", ")} do not stand in the list ${where} — a record is placed only among the records of its own list.`;
290
+ }
291
+ const top = list.topLevelField;
292
+ if (top === null)
293
+ return null;
294
+ const nested = ids
295
+ .map((id) => [id, idOf(byId.get(id)?.[top] ?? null)])
296
+ .filter((p) => p[1] !== null);
297
+ if (!nested.length)
298
+ return null;
299
+ return (`Records ${nested.map(([id, parent]) => `${id} (its list: custom_order(${top}, ${parent}))`).join(", ")} are nested: ` +
300
+ `the list ${field} = ${String(value)} holds the top level only; a nested record stands in its own parent's list — ` +
301
+ `context_field='${top}', context_value=<that parent's id>.`);
302
+ }
303
+ /** Why `ids` cannot be placed in `list`, or null. One read, with the caller's rights. */
304
+ export async function membershipRefusal(entity, list, ids) {
305
+ const why = listProblem(entity, list, ids, await readOrderRows(entity, ids, listFields(list)));
306
+ return why === null ? null : `${why} Nothing was sent.`;
307
+ }
@@ -10,6 +10,7 @@
10
10
  */
11
11
  import { makeRequest, dataUrl, customOrderUrl, searchEntity, selectEntity, insertEntity, updateEntity, removeEntity, } from "../httpClient.js";
12
12
  import { ownProjection, registerOwnProjections } from "../projection.js";
13
+ import { idOf, idsProblem, listProblem, membershipRefusal, placementProblem, readOrderRows, reorderBody, } from "./customOrder.js";
13
14
  import { makeFilter, writeOutcome, stripHtml, jsonResponse, wrapHtml, unescapeUnicode, parseJsonParam, parseProjectionParam, notFoundAnswer, } from "../utils.js";
14
15
  // ---------------------------------------------------------------------------
15
16
  // Constants
@@ -245,6 +246,15 @@ export function _flattenBlockTree(rows, _seen = null) {
245
246
  }
246
247
  return out;
247
248
  }
249
+ /**
250
+ * The list a page's top-level blocks stand in, as the front keeps it: (page, P)
251
+ * with parent empty. A block's children stand in (parent, X) — pagesStore.ts,
252
+ * the block reorders. The custom-order write is sudo and checks no rights, so the
253
+ * block tools read the rows they place, and the anchor, against this list first.
254
+ */
255
+ function topLevelBlocks(pageId) {
256
+ return { context: { field: "page", value: pageId }, topLevelField: "parent" };
257
+ }
248
258
  /** Fetch a page's blocks in custom (display) order (used by getBlocks/readPage). */
249
259
  async function _fetchBlocks(pageId) {
250
260
  const body = {
@@ -484,6 +494,18 @@ export async function insertBlock(pageId, blocksJson, afterId = null, beforeId =
484
494
  catch (e) {
485
495
  return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
486
496
  }
497
+ // The new blocks stand at the page's top level (_blocksFromJson sets page, never
498
+ // parent), so the anchor must be a top-level block of this page — read with the
499
+ // caller's rights BEFORE the create, so a refusal leaves nothing behind.
500
+ const anchorId = (afterId || beforeId);
501
+ const anchorArg = afterId ? "after_id" : "before_id";
502
+ const notHere = placementProblem(afterId ? "after" : "before", anchorId, [], anchorArg) ??
503
+ (await membershipRefusal(ENTITY_PAGE_BLOCKS, topLevelBlocks(pageId), [anchorId]));
504
+ if (notHere) {
505
+ return jsonResponse({
506
+ error: `${notHere} suppa_insert_block creates top-level blocks of page ${pageId}: ${anchorArg} must be one of those.`,
507
+ });
508
+ }
487
509
  const res = await makeRequest("POST", dataUrl(ENTITY_PAGE_BLOCKS, "insert"), {
488
510
  fields: payload,
489
511
  returning: { id: true, type: true },
@@ -498,24 +520,15 @@ export async function insertBlock(pageId, blocksJson, afterId = null, beforeId =
498
520
  if (newIds.length === 0) {
499
521
  return jsonResponse({ error: "Insert returned no block ids; nothing to position.", raw: res });
500
522
  }
501
- // Reorder — API reverses multi-block order, so we always reverse
502
- const reorderBody = {
503
- instanceIds: [...newIds].reverse(),
504
- contextFieldName: "page",
505
- contextValue: pageId,
506
- updates: {},
507
- };
508
- if (afterId) {
509
- reorderBody.beforeInstanceId = afterId;
510
- }
511
- else if (beforeId) {
512
- reorderBody.afterInstanceId = beforeId;
513
- }
523
+ // Anchors as the editor sends them (front pageBlocksAdapter.ts): the side the
524
+ // reader sees, ids in the order given, read desc — customOrder.ts F3.
525
+ const anchor = afterId ? { afterId } : { beforeId: beforeId };
526
+ const orderBody = reorderBody(newIds, { field: "page", value: pageId }, "desc", anchor);
514
527
  // The blocks already exist at this point. If only the positioning fails,
515
528
  // report partial success with the ids — raising would hide the insert and
516
529
  // bait the agent into retrying, which duplicates the blocks.
517
530
  try {
518
- await makeRequest("POST", customOrderUrl(ENTITY_PAGE_BLOCKS), reorderBody);
531
+ await makeRequest("POST", customOrderUrl(ENTITY_PAGE_BLOCKS), orderBody);
519
532
  }
520
533
  catch (e) {
521
534
  const msg = e instanceof Error ? e.message : String(e);
@@ -635,19 +648,27 @@ export async function reorderBlocks(pageId, blockIds, afterId = null, beforeId =
635
648
  if (ids.length === 0) {
636
649
  return jsonResponse({ error: "block_ids is empty — pass at least one block id." });
637
650
  }
638
- // API reverses multi-block order, so we always reverse
639
- const body = {
640
- instanceIds: [...ids].reverse(),
641
- contextFieldName: "page",
642
- contextValue: pageId,
643
- updates: {},
644
- };
645
- if (afterId) {
646
- body.beforeInstanceId = afterId;
647
- }
648
- else if (beforeId) {
649
- body.afterInstanceId = beforeId;
650
- }
651
+ const anchorId = (afterId || beforeId);
652
+ const problem = idsProblem(ids, "block_ids") ??
653
+ placementProblem(afterId ? "after" : "before", anchorId, ids, afterId ? "after_id" : "before_id");
654
+ if (problem)
655
+ return jsonResponse({ error: problem });
656
+ // One read of the blocks and the anchor, with the caller's rights. The first
657
+ // block names the list — the page's top level, or one block's children — and
658
+ // every block and the anchor must stand in it, on this page.
659
+ const all = [...ids, anchorId];
660
+ const rows = await readOrderRows(ENTITY_PAGE_BLOCKS, all, ["page", "parent"]);
661
+ const parentId = idOf(rows.get(ids[0])?.parent ?? null);
662
+ const list = parentId === null ? topLevelBlocks(pageId) : { context: { field: "parent", value: parentId }, topLevelField: null };
663
+ const offPage = all.filter((id) => rows.has(id) && idOf(rows.get(id)?.page ?? null) !== pageId);
664
+ const why = listProblem(ENTITY_PAGE_BLOCKS, list, all, rows) ??
665
+ (offPage.length ? `Blocks ${offPage.join(", ")} are not on page ${pageId}.` : null);
666
+ if (why)
667
+ return jsonResponse({ error: `${why} Nothing was sent.` });
668
+ // Anchors as the editor sends them (front pageBlocksAdapter.ts): the side the
669
+ // reader sees, ids in the order given, read desc — customOrder.ts F3.
670
+ const anchor = afterId ? { afterId } : { beforeId: beforeId };
671
+ const body = reorderBody(ids, list.context, "desc", anchor);
651
672
  await makeRequest("POST", customOrderUrl(ENTITY_PAGE_BLOCKS), body);
652
673
  return jsonResponse({
653
674
  reordered: ids,
@@ -21,6 +21,7 @@ import { buildFileUpload, makeFilter, jsonResponse, parseJsonParam, mergeListPro
21
21
  import { compactEntitySchema, slimTitle, titleLanguages } from "../readEconomy.js";
22
22
  import { customFieldsHint } from "../customFieldHints.js";
23
23
  import { transliterationProblem, untranslatedTokens } from "./nameMap.js";
24
+ import { contextFilters, customOrderBy, orderByText, orderContextRefusal, parseCustomOrderBy, } from "./customOrder.js";
24
25
  // Builder field types that accept file uploads.
25
26
  export const FILE_FIELD_TYPES = ["file", "multi-file"];
26
27
  export const RELATION_FIELD_TYPES = [
@@ -253,6 +254,12 @@ export const HIERARCHY_DEPTH_LIMIT_MAX = 20;
253
254
  /** The two object-valued options (entity-metadata-schema.type.ts:18-51). */
254
255
  export const ENTITY_OPTION_COMMENTS_PRIVACY = "commentsPrivacy";
255
256
  export const ENTITY_OPTION_EXTERNAL_SOURCE = "externalSource";
257
+ /**
258
+ * The registers' document option (documents: architecture/entity-builder/registers.md "Documents"):
259
+ * `true` binds the platform fields `date` and `posted`, or `{ dateField, postedField }` binds fields
260
+ * the entity already has. Frozen once set — the platform refuses removing or rebinding it.
261
+ */
262
+ export const ENTITY_OPTION_DOCUMENT = "document";
256
263
  /** The two mode options, both `"single" | "multi"`. */
257
264
  export const ENTITY_OPTION_MODE_KEYS = [
258
265
  "hierarchy", // builder.txt:78 — "Hierarchy mode."
@@ -288,6 +295,7 @@ export const ENTITY_OPTION_KEYS = [
288
295
  ENTITY_OPTION_DEPTH_LIMIT,
289
296
  ENTITY_OPTION_COMMENTS_PRIVACY,
290
297
  ENTITY_OPTION_EXTERNAL_SOURCE,
298
+ ENTITY_OPTION_DOCUMENT,
291
299
  ];
292
300
  /**
293
301
  * On an entity the tenant does not own — initiator "system" or "application" — the options a
@@ -418,6 +426,17 @@ export function normalizeEntityOptions(raw, param = "options_json") {
418
426
  `(entity-metadata-schema.type.ts:49-51), got ${JSON.stringify(value)}.`);
419
427
  }
420
428
  }
429
+ else if (key === ENTITY_OPTION_DOCUMENT) {
430
+ const bound = isPlainObject(value) ? value : null;
431
+ // {} is true spelled as an object: both platform fields (document-option.util.ts normalizeDocumentOption).
432
+ const okBound = bound !== null &&
433
+ Object.entries(bound).every(([k, v]) => (k === "dateField" || k === "postedField") && typeof v === "string" && v.trim() !== "");
434
+ if (value !== true && !okBound) {
435
+ throw new Error(`Parameter '${param}': 'document' must be true (the platform fields date and posted) or ` +
436
+ '{"dateField": "<timestamp field>", "postedField": "<boolean field>"} binding fields the ' +
437
+ `entity already has; it cannot be turned off (registers.md "Documents"), got ${JSON.stringify(value)}.`);
438
+ }
439
+ }
421
440
  else if (key === ENTITY_OPTION_BROWSING_HISTORY) {
422
441
  const ok = typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value));
423
442
  if (!ok) {
@@ -626,7 +645,7 @@ export function toMultiLang(title, languages) {
626
645
  return out;
627
646
  }
628
647
  /** Resolve the tenant languages and expand `title` (falling back to `fallbackName`). */
629
- async function _expandTitle(title, fallbackName) {
648
+ export async function _expandTitle(title, fallbackName) {
630
649
  const langs = await resolvePlatformLanguages();
631
650
  const base = isPlainObject(title) ? title : (title || fallbackName);
632
651
  return toMultiLang(base, langs);
@@ -894,16 +913,45 @@ export async function searchRecords(entityName, filtersJson = "[]", fieldsJson =
894
913
  }
895
914
  fields = proj.fields;
896
915
  }
897
- const idx = orderBy.indexOf(":");
898
- const field = idx === -1 ? orderBy : orderBy.slice(0, idx);
899
- const rawDir = idx === -1 ? "" : orderBy.slice(idx + 1);
900
- const direction = rawDir.trim().toLowerCase() || "desc";
901
- if (direction !== "asc" && direction !== "desc") {
902
- return jsonResponse({
903
- error: `order_by direction must be 'asc' or 'desc', got '${direction}'.`,
904
- });
916
+ // order_by is either 'field:dir' or a read of the platform's MANUAL order,
917
+ // custom_order(<field>, <id>) — see customOrder.ts for what that list is.
918
+ let custom;
919
+ try {
920
+ custom = parseCustomOrderBy(orderBy);
921
+ }
922
+ catch (e) {
923
+ return jsonResponse({ error: e instanceof Error ? e.message : String(e), records: [], returned: 0 });
924
+ }
925
+ let order;
926
+ if (custom) {
927
+ const check = await orderContextRefusal(entityName, custom.context);
928
+ if (check.refusal !== null) {
929
+ return jsonResponse({ error: check.refusal, records: [], returned: 0 });
930
+ }
931
+ order = customOrderBy(custom.context, custom.direction);
932
+ // The read is the rows OF that list: one outside it has no place in it and
933
+ // would sort by its creation time among the rest — and an owner list of a
934
+ // hierarchy kept per owner holds its top level only (parent = null). ANDed
935
+ // with the caller's filters even under match_any, which keeps its OR among them.
936
+ const scoped = contextFilters(check.list.context, check.list.topLevelField);
937
+ if (scoped.length) {
938
+ const own = filters;
939
+ filters = matchAny && own.length > 0 ? [{ operator: "or", filters: own }, ...scoped] : [...own, ...scoped];
940
+ matchAny = false;
941
+ }
942
+ }
943
+ else {
944
+ const idx = orderBy.indexOf(":");
945
+ const field = idx === -1 ? orderBy : orderBy.slice(0, idx);
946
+ const rawDir = idx === -1 ? "" : orderBy.slice(idx + 1);
947
+ const direction = rawDir.trim().toLowerCase() || "desc";
948
+ if (direction !== "asc" && direction !== "desc") {
949
+ return jsonResponse({
950
+ error: `order_by direction must be 'asc' or 'desc', got '${direction}'.`,
951
+ });
952
+ }
953
+ order = [{ field: field.trim() || "createdAt", order: direction }];
905
954
  }
906
- const order = [{ field: field.trim() || "createdAt", order: direction }];
907
955
  // Fetch one extra row so the agent learns whether another page exists.
908
956
  // Cap at 500/page: larger responses blow the model's context — page instead.
909
957
  limit = Math.max(1, Math.min(limit, 500));
@@ -968,6 +1016,14 @@ export async function searchRecords(entityName, filtersJson = "[]", fieldsJson =
968
1016
  Object.assign(out, diag);
969
1017
  }
970
1018
  }
1019
+ if (custom) {
1020
+ out.custom_order = {
1021
+ context_field: custom.context.field,
1022
+ context_value: custom.context.value,
1023
+ direction: custom.direction,
1024
+ order_by: orderByText(custom.context, custom.direction),
1025
+ };
1026
+ }
971
1027
  return jsonResponse(out);
972
1028
  }
973
1029
  /**
@@ -1667,7 +1723,7 @@ export async function updateEntityOptions(entityName, options) {
1667
1723
  * the corresponding check rather than blocking a legitimate write (mirrors
1668
1724
  * `_refShapeProblems`). Returns a refusal JSON string, or the resolved target.
1669
1725
  */
1670
- async function _relationPreflight(entityName, fieldName, relationType, relationEntity) {
1726
+ async function _relationPreflight(entityName, fieldName, relationType, relationEntity, entityIsNew = false) {
1671
1727
  // 1. Target existence (+ case correction).
1672
1728
  let listing;
1673
1729
  try {
@@ -1704,7 +1760,9 @@ async function _relationPreflight(entityName, fieldName, relationType, relationE
1704
1760
  }
1705
1761
  }
1706
1762
  }
1707
- // 2. The field must not already exist on this entity.
1763
+ // 2. The field must not already exist on this entity — nothing to read on one being created.
1764
+ if (entityIsNew)
1765
+ return { relationEntity };
1708
1766
  let schema;
1709
1767
  try {
1710
1768
  schema = await makeRequest("GET", `/api/core/schema/${entityName}`);
@@ -1770,7 +1828,7 @@ export async function buildFieldDef(entityName, fieldName, fieldType, title, opt
1770
1828
  if (echo) {
1771
1829
  return refuse({ error: echo });
1772
1830
  }
1773
- const { required = false, defaultValue = null, unique = false, relationEntity = null, enumName = null, subType = null, maxLength = null, minLength = null, decimalPlaces = null, minValue = null, maxValue = null, onlyPositive = false, options = null, } = opts;
1831
+ const { required = false, defaultValue = null, unique = false, relationEntity = null, enumName = null, subType = null, maxLength = null, minLength = null, decimalPlaces = null, minValue = null, maxValue = null, onlyPositive = false, options = null, entityIsNew = false, } = opts;
1774
1832
  // The platform has no relation type literally called "relation"; a foreign
1775
1833
  // key is "many-to-one" with the target entity in `relationTarget`. That alias
1776
1834
  // is the ONLY rewrite: relation_entity used to turn ANY type into many-to-one
@@ -1889,7 +1947,7 @@ export async function buildFieldDef(entityName, fieldName, fieldType, title, opt
1889
1947
  // case-only target-name mismatch.
1890
1948
  let relTarget = relationEntity;
1891
1949
  if (RELATION_FIELD_TYPES.includes(resolvedType) && relTarget) {
1892
- const pf = await _relationPreflight(entityName, fieldName, resolvedType, relTarget);
1950
+ const pf = await _relationPreflight(entityName, fieldName, resolvedType, relTarget, entityIsNew);
1893
1951
  if (pf.error) {
1894
1952
  return { error: pf.error };
1895
1953
  }
@@ -2466,8 +2524,8 @@ async function _updateField(entityName, fieldName, opts, checkOnly) {
2466
2524
  notApplicable.push(`defaultValue was sent as the plain string ${JSON.stringify(body.defaultValue)} on ` +
2467
2525
  `'${fieldName}', which is a '${liveType}' — a default on a relation/enum/file field is a ` +
2468
2526
  "REFERENCE: `{ id }`, or `[{ id }, …]` for a multi (a Users relation also takes the " +
2469
- "`$current-user` token). Live examples on a tenant: `Tasks.priority` (enum) holds the " +
2470
- "Enums row id, `Tasks.createdBy` (many-to-one) holds `$current-user`. Read the field " +
2527
+ "`$current-user` token). An enum field holds the " +
2528
+ "Enums row id; a many-to-one to Users may hold `$current-user`. Read the field " +
2471
2529
  "back to check what was stored.");
2472
2530
  }
2473
2531
  }